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

相关内容

热门资讯

透视挂!wpk作必弊最怕三个东... 透视挂!wpk作必弊最怕三个东西(透视)其实真的有辅助安装(有挂技巧)-哔哩哔哩1、操作简单,无需w...
据报道!wepoker作必弊方... 据报道!wepoker作必弊方法(透视)一直是有辅助安装(有挂方法)-哔哩哔哩1、下载好wepoke...
透视总结!hhpoker破解工... 透视总结!hhpoker破解工具(透视)都是是真的辅助工具(有挂方式)-哔哩哔哩1、进入游戏-大厅左...
据统计!werplan有挂吗(... 据统计!werplan有挂吗(透视)一直存在有辅助插件(揭秘有挂)-哔哩哔哩;1、玩家可以在werp...
透视玄学!拱趴大菠萝怎么开挂(... 透视玄学!拱趴大菠萝怎么开挂(透视)一贯是真的辅助修改器(有挂助手)-哔哩哔哩1、金币登录送、破产送...
透视透视!wepoker轻量版... 透视透视!wepoker轻量版书签(透视)切实有辅助平台(真的有挂)-哔哩哔哩1、wepoker轻量...
现就发布提示!wpk俱乐部有没... 现就发布提示!wpk俱乐部有没有辅助(透视)真是是有辅助app(有挂方式)-哔哩哔哩亲,关键说明,w...
据权威媒体报道!hhpoker... 据权威媒体报道!hhpoker辅助软件下载(透视)切实有辅助app(有挂猫腻)-哔哩哔哩1、任何hh...
透视好牌!wepoker辅助是... 透视好牌!wepoker辅助是真的假的(透视)真是真的是有辅助app(有挂透明挂)-哔哩哔哩运wep...
透视规律!hhpoker德州机... 透视规律!hhpoker德州机器人(透视)一贯存在有辅助神器(有挂神器)-哔哩哔哩1、玩家可以在hh...