惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园_首页
博客园 - Franky
大猫的无限游戏
大猫的无限游戏
博客园 - 三生石上(FineUI控件)
量子位
博客园 - 聂微东
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
S
SegmentFault 最新的问题
Apple Machine Learning Research
Apple Machine Learning Research
爱范儿
爱范儿
V
Visual Studio Blog
雷峰网
雷峰网
T
Tailwind CSS Blog
宝玉的分享
宝玉的分享
Blog — PlanetScale
Blog — PlanetScale
有赞技术团队
有赞技术团队
博客园 - 叶小钗
Microsoft Azure Blog
Microsoft Azure Blog
T
The Blog of Author Tim Ferriss
U
Unit 42
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
小众软件
小众软件
阮一峰的网络日志
阮一峰的网络日志
Y
Y Combinator Blog

博客园 - MSTK

PCB检测算法YOLO-EMAC(2) PCB检测算法YOLO-EMAC(1) Android Studio提高Build速度 Android创建LiteOrmManager类(4) DecoView的使用 Android创建LiteOrmManager类(3) Android创建LiteOrmManager类(2) Android创建LiteOrmManager类(1) Android使用Snackbar Unable to add window -- token null is not valid; is your activity running? Android Studio集成通义灵码 MonoDETR(2) MonoDETR(1) The color "XXX" in values has no declaration in the base values folder; this can lead to crashes when the resource is queried in a configuration that does not match this qualifier LiteORM的使用(2) LiteORM的使用(1) 使用AlarmManager实现APP保活(2) 使用AlarmManager实现APP保活(1) CEC2017的30个函数 Process finished with exit code 137 (interrupted by signal 9: SIGKILL) GIT RE-BASIN: MERGING MODELS MODULO PERMUTATION SYMMETRIES (1) MMpretrain使用Tiny ImageNet数据集 Ubuntu使用dd命令实现硬盘级复制 PyCharm debug collecting data...
使用双进程实现Android APP保活
MSTK · 2025-01-30 · via 博客园 - MSTK

Android APP保活是一个很重要的问题,很多APP需要在后台持续运行,比如在后台持续定位、即时通讯、播放音乐等,但是Android系统为了省电,经常把在后台运行的进程杀死,造成APP不能保活,影响功能和使用.因此需要进行APP保活,APP保活有很多方法,如设置白名单,但是效果不是很好,即使设置了进程也可能被杀死,还有就是设置闹钟,但是会把闹钟搞乱,用户看一眼闹钟设置就能看出来,相对而言,使用双进程保活是一种比较好的方法,不容易被杀死,对用户也没有影响.

双进程保活首先要定义两个Service,并且让这两个Service在不同的进程中运行.这里定义了LocalService和RemoteService,其中LocalService在主进程中运行,RemoteService另外新建一个进程.

LocalService:

public class Local_Service extends Service {
    private Handler handler;
    private Runnable runnable;

    @Override
    public void onCreate() {
        super.onCreate();
        // 初始化工作
        handler = new Handler();
        runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    // 执行任务操作
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException(e);
                }
                handler.postDelayed(this, 3000);
            }
        };
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new LocalBinder();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int start_id) {
        handler.postDelayed(runnable, 3000);

        bindService(new Intent(this, RemoteService.class),
                connection, Context.BIND_AUTO_CREATE);
        return super.onStartCommand(intent, flags, start_id);
    }

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // 绑定成功
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // 当RemoteService所处进程被干掉就重新启动
            startService(new Intent(LocalService.this, RemoteService.class));
            bindService(new Intent(LocalService.this, RemoteService.class),
                    connection, Context.BIND_IMPORTANT);
        }
    };

    private class LocalBinder extends Binder {

    }

}

RemoteService:

public class Remote_Service extends Service {
    private Handler handler;
    private Runnable runnable;
    private boolean is_map_service_running;
    private boolean is_pos_service_running;

    public Remote_Service() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        // 初始化工作
        handler = new Handler();
        runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    // 
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException(e);
                }
                // 执行任务操作
                handler.postDelayed(this, 3000);
            }
        };
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new RemoteBinder();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int start_id) {
        handler.postDelayed(runnable, 3000);

        bindService(new Intent(this, LocalService.class),
                connection, Context.BIND_AUTO_CREATE);
        return super.onStartCommand(intent, flags, start_id);
    }

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // 绑定成功
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // 当LocalService所处进程被干掉就重新启动
            startService(new Intent(RemoteService.this, LocalService.class));
            bindService(new Intent(RemoteService.this, LocalService.class),
                    connection, Context.BIND_IMPORTANT);
        }
    };

    private class RemoteBinder extends Binder {

    }
}

两个Service相互绑定,如果其中一个Service所在的进程被kill了,另外一个就对回调onServiceDisconnected()方法,重新启动被kill的进程,这样就保证了这两个Service能够一直运行.

在AndroidManifest.xml中定义两个Service:

        <service android:name=".Service.LocalService" />

        <service
            android:name=".Service.RemoteService"
            android:enabled="true"
            android:exported="true"
            android:process=":remote" />

其中LocalService在主进程中运行,RemoteService通过android:process=":remote"指定了在另外一个进程中运行.