Java Android:通过活动连接到服务,localBinder返回null
所以,我想创建一个TCP套接字通信,客户端运行在Android上。在第一个活动中,我创建了一个服务,没有问题。第一个活动正确绑定,工作正常。接下来,我从服务中解除绑定,然后开始下一个活动,当我尝试绑定到该服务时,我从localBinder中得到null。代码如下。如果有人知道,我洗耳恭听 第一个活动,效果很好Java Android:通过活动连接到服务,localBinder返回null,java,android,sockets,service,Java,Android,Sockets,Service,所以,我想创建一个TCP套接字通信,客户端运行在Android上。在第一个活动中,我创建了一个服务,没有问题。第一个活动正确绑定,工作正常。接下来,我从服务中解除绑定,然后开始下一个活动,当我尝试绑定到该服务时,我从localBinder中得到null。代码如下。如果有人知道,我洗耳恭听 第一个活动,效果很好 public class MainActivity extends Activity { private EditText getIpAddressEditText; pr
public class MainActivity extends Activity {
private EditText getIpAddressEditText;
private String IpAddress;
private Socket socket;
private boolean mIsBound;
private SocketService mService;
private EditText ipAddressEditText;
private Intent theIntent;
private ProgressDialog mDialog;
private BufferedWriter out;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
theIntent = new Intent(MainActivity.this,SocketService.class);
getIpAddressEditText = (EditText) findViewById(R.id.get_ip_address_edit_text);
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
}
public void onServiceDisconnected(ComponentName className) {
mService = null;
}
};
public void OnConnectToServerButtonClick(View view) {
IpAddress = getIpAddressEditText.getText().toString();
theIntent.putExtra("IPADDRESS", IpAddress);
startService(theIntent);
doBindService();
new GetServerSocket().execute();
}
private void ConnectToServer() {
socket = mService.getSocket();
if (socket.isConnected()) {
SendMessageToServer("HELLO SERVER");
doUnbindService();
Intent intent = new Intent(MainActivity.this,GpsInterfaceActivity.class);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Connection Failed", Toast.LENGTH_LONG).show();
doUnbindService();
stopService(theIntent);
}
}
public void OnGetIpFromSmsButtonClick(View view) {
}
private void doBindService() {
bindService(new Intent(MainActivity.this, SocketService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
private void doUnbindService() {
if (mIsBound) {
// Detach our existing connection.
unbindService(mConnection);
mIsBound = false;
}
}
public class GetServerSocket extends AsyncTask<Void, Void, String> {
public ProgressDialog progDailog;
public GetServerSocket() {}
private int a = 0;
@Override
public String doInBackground(Void... params) {
while ( a < 60) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
a++;
if (mService != null) {
socket = mService.getSocket();
if (socket.isConnected()) {
break;
}
}
}
return null;
}
@Override
protected void onPostExecute(String result) {
ConnectToServer();
}
}
public void SendMessageToServer(String string) {
try {
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
out.write(string);
out.flush();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
在第二个活动中,您在哪里得到null?您确定服务正在第二个活动中运行吗?mService=binder.getService();这里我得到null,这意味着服务断开了,但我不知道为什么。也许我需要传递intent、我的serviceConnection对象并绑定到它?您能提供更多详细信息吗(特别是服务中的doBindService()、onStartCommand()、onBind()和绑定器本身)?在第一次活动中断开连接后,您的服务似乎停止了。我刚刚更新了所有代码,希望能有所帮助。对我来说,这些代码运行良好。目前,我能够观察到以下问题:您在bindService()调用之后设置了mIsBound=true,但实际绑定只有在OnServiceConnection()回调之后才会发生(例如,onCreate()中的调用SendMessageToServer()在NPE中总是会失败)。您是否观察到与SocketService相关的任何日志(例如,服务停止或smth之类)?
public class GpsInterfaceActivity extends Activity {
private SocketService mService;
private Socket socket;
private BufferedWriter out;
private String[] list = new String[11];
private String DeviceId;
private String DeviceStatus;
private String DeviceTTFF;
private String DeviceNumberOfSatellites;
private String DeviceSpeed;
private String DeviceCourseOverGround;
private String DeviceAltitude;
private String DeviceLongitude;
private String DeviceLatitude;
private String DeviceNetworkStatus;
private String DeviceEnergykStatus;
private TextView ttffEditText;
private TextView satellitesEditText;
private TextView speedEditText;
private TextView courseOverGroundEditText;
private TextView networkStatusEditText;
private TextView deviceStatusEditText;
private TextView energyStatusEditText;
private ProgressBar energyProgressBar;
private boolean mIsBound = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps_interface);
deviceStatusEditText = (TextView) findViewById(R.id.deviceStatusTextView);
ttffEditText = (TextView) findViewById(R.id.ttff_edit_text);
satellitesEditText = (TextView) findViewById(R.id.satellites_edit_text);
speedEditText = (TextView) findViewById(R.id.speed_edit_text);
courseOverGroundEditText = (TextView) findViewById(R.id.course_over_ground_edit_text);
networkStatusEditText = (TextView) findViewById(R.id.network_status_edit_text);
energyStatusEditText = (TextView) findViewById(R.id.energy_status_text_view);
energyProgressBar = (ProgressBar) findViewById(R.id.energy_proccess_bar);
doBindService();
if (mService != null) {
socket = mService.getSocket();
}else {
Toast.makeText(getApplicationContext(), "Connection Lost", Toast.LENGTH_LONG).show();
}
new IncomingData().execute();
SendMessageToServer("HELLO SERVER");
}
private ServiceConnection mConnectionn = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
}
public void onServiceDisconnected(ComponentName className) {
mService = null;
}
};
private void InputStreamTokenizer(String input) {
if (input.contains("DEVICE")) {
try {
list = input.split(";");
DeviceId = list[0];
DeviceStatus = list[1];
DeviceTTFF = list[2];
DeviceNumberOfSatellites = list[3];
DeviceSpeed = list[4];
DeviceCourseOverGround = list[5];
DeviceAltitude = list[6];
DeviceLongitude = list[7];
DeviceLatitude = list[8];
DeviceNetworkStatus = list[9];
DeviceEnergykStatus = list[10];
deviceStatusEditText.setText(DeviceStatus);
ttffEditText.setText(DeviceTTFF);
satellitesEditText.setText(DeviceNumberOfSatellites);
speedEditText.setText(DeviceSpeed);
courseOverGroundEditText.setText(DeviceCourseOverGround);
networkStatusEditText.setText(DeviceNetworkStatus);
energyStatusEditText.setText(DeviceEnergykStatus);
} catch (Exception e){}
}
}
public void SendMessageToServer(String string) {
try {
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
out.write(string);
out.flush();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
private void doBindService() {
bindService(new Intent(GpsInterfaceActivity.this, SocketService.class), mConnectionn, Context.BIND_ADJUST_WITH_ACTIVITY);
mIsBound = true;
}
private void doUnbindService() {
if (mIsBound) {
// Detach our existing connection.
unbindService(mConnectionn);
mIsBound = false;
}
}
public class IncomingData extends AsyncTask<Void, Void, String> {
public BufferedReader input;
public String read = null;
public int time = 0;
public IncomingData() {}
@Override
public String doInBackground(Void... params) {
try {
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (input.ready()) {
read = input.readLine();
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e){
}
return read;
}
@Override
public void onPostExecute(String input) {
if (input != null) {
InputStreamTokenizer(input);
}
new IncomingData().execute();
}
}
}
public class SocketService extends Service {
Socket s;
String IpAddress;
Intent intent;
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return myBinder;
}
public Socket getSocket() {
return s;
}
private final IBinder myBinder = new LocalBinder();
public class LocalBinder extends Binder {
public SocketService getService() {
return SocketService.this;
}
}
@Override
public void onCreate() {
super.onCreate();
s = new Socket();
}
public void onStart(Intent intent, int startId){
super.onStart(intent, startId);
IpAddress = intent.getStringExtra("IPADDRESS");
new Thread(new SocketThread()).start();
}
public class SocketThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(IpAddress);
s = new Socket(serverAddr, 8080);
} catch (SocketException e1) {
e1.printStackTrace();
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
}