本来打算对Notification进行详细说明 和源码解读的 发现写的时刻又不想写。
Notification 保活
算了 直接上源代码
@Overridepublic 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); }}
时间: 2024-10-02 21:22:20