安装未知开发者的应用后,前台服务会周期性地关闭且无法重启。
创始人
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() 方法中删除这个监听器,以避免内存泄漏。

相关内容

热门资讯

第3分钟辅助!xpoker辅助... 您好,wepoker透视脚本苹果版这款游戏可以开挂的,确实是有挂的,需要了解加去威信【1367043...
4分钟辅助!wepoker透视... 4分钟辅助!wepoker透视脚本网页,wepoker作弊辅助,模板教程(真的有挂)所有人都在同一条...
两分钟辅助!wepoker透视... 两分钟辅助!wepoker透视脚本免费下载pc,we poker辅助器v3.3,积累教程(有挂方针)...
第9分钟辅助!wepoker透... 第9分钟辅助!wepoker透视app下载,hhpoker俱乐部是干嘛的,教材教程(有挂秘诀)一、h...
第六分钟辅助!德州局透视脚本下... 第六分钟辅助!德州局透视脚本下载安装最新版本,wpk透视怎么安装,窍门教程(竟然有挂)1、德州局透视...
一分钟辅助!wepoker线上... 一分钟辅助!wepoker线上大神,智星菠萝可以辅助吗,演示教程(有挂透明挂)1、在智星菠萝可以辅助...
第7分钟辅助!hardrock... 第7分钟辅助!hardrock透视工具,cloudpoker作弊,练习教程(有挂细节)1、实时har...
第七分钟辅助!德州hhpoke... 第七分钟辅助!德州hhpoker脚本,wepoker透视app下载,指南书教程(有挂教程)1、首先打...
第一分钟辅助!epoker有透... 第一分钟辅助!epoker有透视吗,hhpoker德州透视挂,手筋教程(有挂助手)1、金币登录送、破...
第6分钟辅助!来玩德州破解器,... 第6分钟辅助!来玩德州破解器,hhpoker有没有辅助,经验教程(有挂方针)1、许多玩家不知道hhp...