您的位置:首页 > 移动开发 > Android开发

android Service的一些注意点

2018-03-29 21:38 183 查看
onbind后台服务时会调用onServiceConnected方法 但unbind时不会调用onServiceDisconnected方法系统结束服务时才会调用。MainActivityprivate MyService myService;private ServiceConnection serviceConnection = new ServiceConnection() {@Overridepublic void onServiceConnected(ComponentName componentName, IBinder iBinder) {Log.d(TAG, "onServiceConnected: ");myService = ((MyService.MyBinder)iBinder).getService();}/*** 注意 该方法只有后台服务被强制终止时间才会调用 自己接触绑定不会调用* @param componentName*/@Overridepublic 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@Overridepublic 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);//渠道idString 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中关闭服务@Overrideprotected void onDestroy() {//避免服务在退出客户端后还存活unbindService(serviceConnection);Intent intent_close = new Intent(MainActivity.this, MyService.class);stopService(intent_close);super.onDestroy();}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息