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

Android应用被killed时,Service不被一起kill的方法

2015-07-12 16:50 471 查看
其实很简单,只需要将服务设置成前台服务即可

@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。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: