Android 进程保活 Notification详细说明

本来打算对Notification进行详细说明  和源码解读的  发现写的时刻又不想写。

 Notification 保活

算了 直接上源代码 

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (Build.VERSION.SDK_INT < 18) {
startForeground(GRAY_SERVICE_ID, new Notification());
} else {
Intent innerIntent = new Intent(context, AuxiliaryService.class);
startService(innerIntent);
Notification notification = new Notification();
startForeground(GRAY_SERVICE_ID, notification);
}
return super.onStartCommand(intent, flags, startId);
}

/**
* 辅助Service 用来开启一个通知 就结束 不要创建内部类 不然回收有问题
*/
public class AuxiliaryService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
startNotification();
return super.onStartCommand(intent, flags, startId);
}
/** 启动通知*/
private void startNotification(){
Notification notification = new Notification();
this.startForeground(MQTTService.GRAY_SERVICE_ID, notification);
stopSelf(); //关键 如果AuxiliaryService 没有与什么组件绑定 系统就会回收
stopForeground(true);
}
}
posted @ 2017-11-24 17:01  不一样的农民  阅读(1359)  评论(0编辑  收藏  举报