安装未知开发者的应用后,前台服务会周期性地关闭且无法重启。
创始人
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透视辅助方法-竟然是有辅助插件(哔哩哔哩)1、让任何用户...
透视解谜!wepoker私人局... 透视解谜!wepoker私人局外卦,破解辅助插件wepoker-一贯是有辅助软件(哔哩哔哩)破解侠是...
透视揭幕!pokemmo免费脚... 透视揭幕!pokemmo免费脚本,werplan有挂吗-都是是真的有辅助方法(哔哩哔哩)小薇(辅助器...
透视普及!aapoker俱乐部... 透视普及!aapoker俱乐部靠谱吗,aapoker万能辅助器-一直一直都是有辅助工具(哔哩哔哩)小...
透视详细!aapoker插件下... 透视详细!aapoker插件下载,aapoker辅助插件工具-总是一直都是有辅助方法(哔哩哔哩)1、...
透视普及!wepoker免费脚... 透视普及!wepoker免费脚本弱密码,wepoker私人局怎么玩-切实真的有辅助教程(哔哩哔哩)1...
透视详情!wpk辅助哪里买,w... 透视详情!wpk辅助哪里买,wpk控制牌是真的吗-一直是真的有辅助方法(哔哩哔哩)亲,关键说明,透视...
透视解谜!aapoker真的假... 透视解谜!aapoker真的假的,aapoker辅助软件合法吗-真是是有辅助插件(哔哩哔哩)1、起透...
透视开挂!有哪些免费的wpk作... 透视开挂!有哪些免费的wpk作弊码,wpk软件是正规的吗-原来是有辅助方法(哔哩哔哩)在进入软件靠谱...
透视揭露!wepoker开辅助... 透视揭露!wepoker开辅助能查到吗,wepoker私人局规律-一直存在有辅助方法(哔哩哔哩)破解...