Activity 与 Service 之间的消息传递
BgService代码
public class BgService extends Service { public static final String TAG = "BgService"; private BgBinder binder; @Override public void onCreate() { super.onCreate(); binder = new BgBinder(); Log.d(TAG, "onCreate() executed"); } @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy() executed"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d(TAG, "onStartCommand() executed"); return super.onStartCommand(intent, flags, startId); } @Nullable @Override public IBinder onBind(Intent intent) { Log.d(TAG, "onBind() executed"); return binder; } class BgBinder extends Binder { public void doWork() { Log.d(TAG, "doWork() executed"); } } }
Activity 代码
public class MyActivity extends AppCompatActivity { private ServiceConnection bgServiceConnection; private BgService.BgBinder bgBinder; @Override protected void onCreate(Bundle savedInstanceState) { ... bgServiceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { bgBinder = (BgService.BgBinder)service; bgBinder.doWork(); // 异步回调必须在这里调用 Log.d("MyActivity", "onServiceConnected"); } @Override public void onServiceDisconnected(ComponentName name) { bgBinder = null; Log.d("MyActivity", "onServiceDisconnected"); } }; ... } public void startBg(View view) { Intent intent = new Intent(this, BgService.class); startService(intent); } public void stopBg(View view) { Intent intent = new Intent(this, BgService.class); stopService(intent); } public void bindBg(View view) { Intent intent = new Intent(this, BgService.class); bindService(intent, bgServiceConnection, BIND_AUTO_CREATE); } public void unbindBg(View view) { unbindService(bgServiceConnection); } }
其中
startService 调用onStartCommand, 如果service未create, 会在调用之前, 调用onCreate
stopService 会检查service被引用的情况, 如果没有其他引用, 则调用onDestroy
bindService 会调用onBind(之后在异步返回中执行onServiceConnected), 如果service未create, 会在调用之前, 调用onCreate. 注意, 不会调用onStartCommand
unbindService 会检查service被引用的情况, 如果没有其他引用, 则调用onDestroy,
unbindService与stopService的区别: stopService可多次调用, 不会抛异常, unbindService在执行后如果再调用会抛异常, 不处理则应用崩溃
onServiceDisconnected为什么没被调用? 这个只有在service因异常而断开连接的时候,这个方法才会被调用 This is called when the connection with the service has been unexpectedly disconnected -- that is, its process crashed. Because it is running in our same process, we should never see this happen.