Android Service 不被殺死並提高優先順序,android優先順序
Android Service 不被殺死有兩種思路,一種是將APP設定為系統應用,另一種是增強service的生命力,即使螢幕背光關閉時也能運行。由於設定為系統應用需要root,所以一般使用後一種方法:
1.Androidmanifest.xml的許可:
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<service android:name="com.xx.MyService" ></service>
2.綁定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();//螢幕關閉後服務繼續
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);//綁定服務
}
@Override
protected void onDestroy() {
mwl.release();//釋放
unbindService(conn);//解除綁定
super.onDestroy();
}
Android Service 提高優先順序:
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);//設定最進階進程, id 為 0狀態列的 notification 將不會顯示
return new MyBinder();
}
class MyBinder extends Binder{ }
@Override
public void onDestroy() {
stopForeground(true);//取消最進階進程
super.onDestroy();
}
}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。