Android Service 不被殺死並提高優先順序,android優先順序

來源:互聯網
上載者:User

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();
}

}

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.