onbind后台服务时会调用onServiceConnected方法 但unbind时不会调用onServiceDisconnected方法
系统结束服务时才会调用。
MainActivity
private MyService myService; private ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { Log.d(TAG, "onServiceConnected: "); myService = ((MyService.MyBinder)iBinder).getService(); } /** * 注意 该方法只有后台服务被强制终止时间才会调用 自己接触绑定不会调用 * @param componentName */ @Override public void onServiceDisconnected(ComponentName componentName) { Log.d(TAG, "onServiceDisconnected: "); myService = null; } };
case R.id.bind_service: Intent intent_bind = new Intent(MainActivity.this, MyService.class); intent_bind.putExtra("message", "绑定后台服务"); bindService(intent_bind, serviceConnection, Context.BIND_AUTO_CREATE); break; case R.id.unbind_service: unbindService(serviceConnection); //不设置为null 解除绑定服务终止也会保存一份实例 可以照常调用Service中的方法 myService = null; break;
android O 通知需要添加渠道 前台服务也需要添加渠道才能显示
ForegroundService
@Override public void onCreate() { Notification.Builder builder = new Notification.Builder(this); builder.setSmallIcon(R.mipmap.ic_launcher); builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)); builder.setContentTitle("ForegroundService"); builder.setContentText("ForegroundService正在运行"); if(Build.VERSION.SDK_INT >= 26) { createChannel(); builder.setChannelId("channel_01"); } Notification notification = builder.build(); notification.flags = Notification.FLAG_AUTO_CANCEL; startForeground(1, notification); super.onCreate(); }
@RequiresApi(api=26) public void createChannel(){ /** * 创建通知渠道1 */ NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); //渠道id String id = "channel_01"; //用户可以看到的通知渠道的名字 String name = "前台通知"; int importance = NotificationManager.IMPORTANCE_HIGH; NotificationChannel channel = new NotificationChannel(id, name, importance); //配置通知渠道的属性 channel.setDescription("前台通知的专用渠道"); //设置通知出现时的闪灯(如果android设备支持的话) channel.enableLights(true); channel.setLightColor(Color.GREEN); //在notificationmanager中创建该通知渠道 manager.createNotificationChannel(channel); }
建议在Activity的onDestroy中关闭服务
@Override protected void onDestroy() { //避免服务在退出客户端后还存活 unbindService(serviceConnection); Intent intent_close = new Intent(MainActivity.this, MyService.class); stopService(intent_close); super.onDestroy(); }