Android Service is not killed and priority is increased. android priority
There are two ways to avoid the Android Service being killed: one is to set the APP as a system application, and the other is to enhance the vitality of the service, even when the screen backlight is off. Because root is required for system applications, the following method is generally used:
1. Androidmanifest. xml license:
<Uses-permission android: name = "android. permission. WAKE_LOCK"/>
<Service android: name = "com. xx. MyService"> </service>
2. Bind Activity:
Private ServiceConnection conn = null;
Private PowerManager. WakeLock mwl;
@ Override
Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. activity_mian );
PowerManager pm = (PowerManager) getSystemService (Context. POWER_SERVICE );
Mwl = pm. newWakeLock (PowerManager. PARTIAL_WAKE_LOCK, "MyTag ");
Mwl. acquire (); // The service continues after the screen is disabled.
Intent service = new Intent (this, MyService. class );
StartService (service );
Conn = new ServiceConnection (){
@ Override
Public void onServiceDisconnected (ComponentName name ){
}
@ Override
Public void onServiceConnected (ComponentName name, IBinder service ){
}
};
BindService (service, conn, BIND_AUTO_CREATE); // bind a service
}
@ Override
Protected void onDestroy (){
Mwl. release (); // release
UnbindService (conn); // unbind
Super. onDestroy ();
}
Android Service increases priority:
Public class MyService extends Service {
@ Override
Public IBinder onBind (Intent intent ){
Notification notification = new Notification (R. drawable. ic_launcher, "title", System. currentTimeMillis ());
PendingIntent pintent = PendingIntent. getService (this, 0, intent, 0 );
Notification. setLatestEventInfo (this, "Service", "service is running", pintent );
StartForeground (0, notification); // sets the highest level process. The notification with the id as 0 status bar is not displayed.
Return new MyBinder ();
}
Class MyBinder extends Binder {}
@ Override
Public void onDestroy (){
StopForeground (true); // cancel the highest level process
Super. onDestroy ();
}
}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.