可以通过创建绑定Service,在多个Activity之间建立永久连接。在Service中使用Binder来提供对连接的访问。具体实现步骤如下:
public class MyService extends Service {
private final IBinder mBinder = new LocalBinder();
public class LocalBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
...
}
public class MyActivity extends Activity {
private MyService mService;
private boolean mBound = false;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
@Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, MyService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
if (mBound) {
unbindService(mConnection);
mBound = false;
}
}
...
}
public void myMethod() {
if (mBound) {
mService.myMethod();
}
}