|
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.view.View;
import android.widget.TextView;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.OnClick;
/**
* 服务器界面
*/
public class Function_Socket_Server extends BaseEventActivity {
@BindView(R.id.tv_localAddress)
TextView tv_localAddress;
@BindView(R.id.tv_receivedContent)
TextView tv_receivedContent;
@BindView(R.id.tv_decryptContent)
TextView tv_decryptContent;
private LocalService localService;//用于启动监听的服务
private ServiceConnection sc;//服务连接
@Override
protected void init() {
tv_localAddress.setText(ToolUtil.getHostIP());
sc = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
LocalService.LocalBinder localBinder = (LocalService.LocalBinder) service;
localService = localBinder.getService();
localService.startWaitDataThread();
ToastUtil.showToast(Function_Socket_Server.this, "监听已启动");
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
connection();
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void getData(String data) {
tv_receivedContent.setText(data);
tv_decryptContent.setText(AESUtil.decrypt(ConstantUtil.password, data));
}
/**
* 绑定service
*/
private void connection() {
Intent intent = new Intent(this, LocalService.class);
bindService(intent, sc, BIND_AUTO_CREATE);
}
@Override
protected int getLayoutResId() {
return R.layout.function_socket_server;
}
/**
* 获取连接到本机热点上的手机ip
*/
private ArrayList<String> getConnectedIP() {
ArrayList<String> connectedIP = new ArrayList<>();
try {
//通过读取配置文件实现
BufferedReader br = new BufferedReader(new FileReader(
"/proc/net/arp"));
String line;
while ((line = br.readLine()) != null) {
String[] splitted = line.split(" +");
if (splitted.length >= 4) {
String ip = splitted[0];
connectedIP.add(ip);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return connectedIP;
}
@OnClick({R.id.btn_startListener, R.id.btn_stopListener, R.id.btn_getUser})
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_startListener://启动监听
connection();
break;
case R.id.btn_stopListener://停止监听
if (sc != null)
unbindService(sc);
break;
case R.id.btn_getUser://刷新连接到此设备的IP并清空之前接收到的数据
ArrayList<String> connectedIP = getConnectedIP();
StringBuilder resultList = new StringBuilder();
for (String ip : connectedIP) {
resultList.append(ip);
resultList.append("\n");
}
ToastUtil.showToast(this, "连接到手机上的Ip是:" + resultList.toString());
tv_decryptContent.setText("");
tv_receivedContent.setText("");
break;
}
}
public void onDestroy() {
super.onDestroy();
if (sc != null)
unbindService(sc);
}
}
|