安装未知开发者的应用后,前台服务会周期性地关闭且无法重启。
创始人
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有... 透视有挂!wpk插件,wpk有那种辅助吗(透视)一直真的是有脚本(哔哩哔哩)1、金币登录送、破产送、...
现有关情况通报如下!wepok... 现有关情况通报如下!wepoker怎么提高运气,微乐游戏竞技团辅助,揭露透视(的确有挂)-哔哩哔哩1...
备受关注的!wepoker免费... 备受关注的!wepoker免费脚本咨询,微信微乐辅助器免费,开挂脚本(有挂方法)-哔哩哔哩;wepo...
脚本总结!wpk有辅助器吗,w... 脚本总结!wpk有辅助器吗,wpk系统是否存在作必弊行为(透视)其实是真的挂(哔哩哔哩);1、实时透...
突发!wepoker透视器免费... 突发!wepoker透视器免费,微乐自建房脚本下载,开挂透视(有挂分析)-哔哩哔哩1、游戏颠覆性的策...
透视诀窍!aapoker辅助怎... 透视诀窍!aapoker辅助怎么用,AApoker辅助工具一直存在有脚本,第5分钟教程(有挂神器)1...
记者获悉!wepoker辅助器... 记者获悉!wepoker辅助器怎么弄,微乐小游戏万能修改器,揭露脚本(证实有挂)-哔哩哔哩1、打开软...
透视曝光!德普之星辅助器app... 透视曝光!德普之星辅助器app,德普之星怎么设置埋牌(透视)切实是有app(哔哩哔哩)1、这是跨平台...
透视有挂!wepokerplu... 透视有挂!wepokerplus透视脚本免费,微乐小程序黑科技辅助工具2026最新推荐,揭幕透视(有...
透视有挂!wepoker怎么破... 透视有挂!wepoker怎么破解游戏,wejoker辅助软件视频(透视)一贯有工具(哔哩哔哩)是不是...