其实很简单,只需要将服务设置成前台服务即可
@Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d(TAG, "service on start"); Log.d(MyService.TAG, "MyService main thread:" + Thread.currentThread().hashCode()); Notification notification=new Notification(); notification.tickerText="HAHA"; this.startForeground(startId, notification); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } return super.onStartCommand(intent, flags, startId); }
stopForeground可以取消服务的前台状态。和startForeground搭配使用,可以控制服务是否跟谁app一起被killed。