簡單實現安卓進程保活

預期目標:

實現後臺定位功能。

實現方法:

核心是一個前臺進程,擁有正在“前臺”運行的 Service(服務已調用 startForeground())。

	public static final int NOTIFICATION_ID = 0x11;
@Override
public void onCreate() {
    super.onCreate();
    //API 18以下,直接發送Notification並將其置爲前臺
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
        startForeground(NOTIFICATION_ID, new Notification());
    } else {
        //API 18以上,發送Notification並將其置爲前臺後,啓動InnerService
        Notification.Builder builder = new Notification.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        startForeground(NOTIFICATION_ID, builder.build());
        startService(new Intent(this, InnerService.class));
    }
    // do what you want
}
public static class InnerService extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //發送與KeepLiveService中ID相同的Notification,然後將其取消並取消自己的前臺顯示
        Notification.Builder builder = new Notification.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        startForeground(NOTIFICATION_ID, builder.build());
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                stopForeground(true);
                NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                manager.cancel(NOTIFICATION_ID);
                stopSelf();
            }
        }, 100);
    }
}





知識共享許可協議
本作品採用知識共享署名-非商業性使用-相同方式共享 4.0 國際許可協議進行許可。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章