安装未知开发者的应用后,前台服务会周期性地关闭且无法重启。
创始人
2024-09-01 06:30:14
0

可能是由于后台限制导致前台服务关闭,可以添加一个监听器来监测前台服务是否已经被关闭,并在其关闭时重新启动。下面是一个示例代码:

public class MyService extends Service {
    private static final String TAG = "MyService";
    private static final int SERVICE_ID = 12345;
    private static final long INTERVAL = 60000; // 1 minute

    private boolean isServiceRunning = false;
    private Handler mHandler = new Handler();

    private Runnable task = new Runnable() {
        @Override
        public void run() {
            if (!isServiceRunning) {
                Log.d(TAG, "Service has been stopped. Restarting...");
                Intent serviceIntent = new Intent(getApplicationContext(), MyService.class);

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    startForegroundService(serviceIntent);
                } else {
                    startService(serviceIntent);
                }
            }

            mHandler.postDelayed(this, INTERVAL);
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        startForeground(SERVICE_ID, new Notification());
        mHandler.post(task);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        isServiceRunning = true;
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isServiceRunning = false;
        mHandler.removeCallbacks(task);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

onCreate() 方法中,我们通过 startForeground() 方法来使服务成为前台服务,并传入一个空的 Notification 对象。在 onStartCommand() 方法中,我们将 isServiceRunning 设置为 true,以表示前台服务正在运行。在 onDestroy() 方法中,我们会将 isServiceRunning 设置为 false,表示前台服务已经停止。

最重要的是我们在 task 中添加了一个监听器来检测前台服务是否已经关闭。如果已经关闭了,我们就重新启动该服务。在此我们使用了 mHandler.postDelayed() 方法,以 1 分钟的间隔进行检测。注意需要在 onDestroy() 方法中删除这个监听器,以避免内存泄漏。

相关内容

热门资讯

据玩家消息!wepoker透视... 据玩家消息!wepoker透视脚本免费,禅游指尖四川作必弊,一直存在有辅助教程(哔哩哔哩)禅游指尖四...
记者获悉!hhpkoer辅助器... 记者获悉!hhpkoer辅助器,wepoker辅助软件视频,切实存在有辅助软件(哔哩哔哩)1、每一步...
近日!德州透视是真的假的,哥哥... 近日!德州透视是真的假的,哥哥打大a辅助,总是真的有辅助神器(哔哩哔哩)1、起透看视 德州透视是真的...
今日!hhpoker破解工具,... 今日!hhpoker破解工具,潮汕汇app辅助,其实有辅助方法(哔哩哔哩)1、实时潮汕汇app辅助透...
有玩家发现!pokemmo手机... 有玩家发现!pokemmo手机脚本辅助器,微乐兰州麻将小程序辅助,一直是真的有辅助攻略(哔哩哔哩)小...
昨日!wepoker透视版下载... 昨日!wepoker透视版下载,闲来辅助工具,确实是真的有辅助工具(哔哩哔哩)1、下载好闲来辅助工具...
有了最新消息!hhpoker有... 您好,杭州都莱到底有没有挂这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很...
为了进一步!pokeplus脚... 为了进一步!pokeplus脚本,邯郸胡乐辅助脚本下载,总是真的有辅助app(哔哩哔哩)1、邯郸胡乐...
目前来看!wepokerplu... 目前来看!wepokerplus作必弊,手机微乐小程序游戏破解器,原来存在有辅助软件(哔哩哔哩)1、...
据统计!aapoker透视脚本... 据统计!aapoker透视脚本下载,潮汕来物局开挂方法,总是是真的有辅助教程(哔哩哔哩)1、很好的工...