1.ServiceTwo scenarios of being killed 1.2 system recovery
When the system is out of memory space, it may be killed by the system to reclaim memory, and when the memory is low, Android will be Service cleared by the priority level Service .
1.2 User cleanup
The user can clear the recently opened task in the "recently opened" (Multitasking window, Task Management window), when the user clears the Service task, Service may be killed (different ROM has different performance, in Millet, Meizu and other third-party production agreed ROM generally will be killed immediately, Not immediately killed on Android N).
2. Solution
For the first scenario (System recycling), if you do not use black technology (two-process mutual open, etc.), we can only maximize Service the priority, a better way is using the front-Office service.
For the second scenario (User manual cleanup), you can exclude the task that starts the service from the system's most recent task list.
2.1 Front Desk Service
The front-desk service is a service with a foreground interface (Notification) and a very high priority, which clears the foreground service only if the system memory is severely insufficient.
The service can be converted to a onCreate() onStartCommand() foreground service only if it is called from within the service startForeground . Examples are as follows:
Private Notification buildforegroundnotification () {Notification. BuilderBuilder = new Notification. Builder(this);Builder. setongoing(true);Builder. Setcontenttitle(GetString (R. String. Notification_title)). Setcontenttext(GetString (R. String. Notification_content)). Setsmallicon(R. Mipmap. IC_launcher). Setticker(GetString (R. String. Notification_ticker));Builder. SetPriority(Notification. Priority_max);Return builder. Build();} @Overridepublic int Onstartcommand (Intent Intent, int flags, int startid) {Log. E(TAG,"Onstartcommand");WindowManager WindowManager = (windowmanager) getsystemservice (Window_service);Mrootview = new Floatrootview (this);Mrootview. Attach(WindowManager);Mrootview. Showbubble();Startforeground (1, Buildforegroundnotification ());Return Start_sticky;}
2.2 Move out of recent tasks
In order to Service not be cleared by the user from recent open, we can remove the initiated Service task from the list of recent apps in the system. The practice is to set the task to Activity excludeFromRecents true , as follows:
<activity android:name = ". Mainactivity " android:excludefromrecents =" True "; <intent-filter ; Span class= "Hljs-tag" ><action android:name = "Android.intent.action.MAIN" /> << Span class= "Hljs-title" >category android:name = "Android.intent.category.LAUNCHER" /> </< Span class= "Hljs-title" >intent-filter ; </ Activity ;
Android prevents service from being killed