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

相关内容

热门资讯

玩家必看科普!微乐小程序麻将自... 玩家必看科普!微乐小程序麻将自建房辅助工具插件,微乐家乡麻将自建房辅助app(开挂自建房)插件1、微...
玩家必看科普!微乐小程序自建房... 玩家必看科普!微乐小程序自建房辅助工具插件,微乐自建房脚本免费入口(开挂自建房)器微乐小程序自建房辅...
科普!微乐自建房辅助工具插件,... 您好,微乐家乡麻将自建房辅助app这款游戏可以开挂的,确实是有挂的,需要了解加去威信【1367043...
我来向大家传授!微乐自建房辅助... 我来向大家传授!微乐自建房辅助工具插件,微乐自建房脚本免费入口(开挂自建房)攻略1)微乐自建房辅助工...
科技新动态!微乐自建房辅助工具... 科技新动态!微乐自建房辅助工具脚本,微乐小程序免费黑科技(开挂自建房)器1)微乐自建房辅助工具脚本有...
重要通知!微乐自建房辅助工具挂... 重要通知!微乐自建房辅助工具挂,微乐小程序免费黑科技(开挂自建房)插件1、玩家可以在微乐自建房辅助工...
科普分享!微乐小程序麻将自建房... 科普分享!微乐小程序麻将自建房辅助工具插件,微乐家乡麻将自建房辅助app(开挂自建房)插件一、微乐小...
每日必备!微乐自建房辅助工具插... 每日必备!微乐自建房辅助工具插件,微乐家乡麻将自建房辅助app(开挂自建房)器1、在微乐家乡麻将自建...
玩家必看科普!微乐自建房辅助工... 玩家必看科普!微乐自建房辅助工具脚本,微乐小程序免费黑科技(开挂自建房)方法1、完成微乐自建房辅助工...
专业讨论!微信雀神麻将挂件开挂... 专业讨论!微信雀神麻将挂件开挂辅助,微乐小程序免费黑科技(开挂自建房)器1、很好的工具软件,可以解锁...