简单实现安卓进程保活

预期目标:

实现后台定位功能。

实现方法:

核心是一个前台进程,拥有正在“前台”运行的 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 国际许可协议进行许可。

你可能感兴趣的:(Android)