Android10在内存清理时结束前台服务
创始人
2024-08-20 08:30:13
0次

在AndroidManifest.xml中,添加以下代码,使应用程序免受最新更新影响:




在对应的Service类中,添加以下代码,以确保前台服务不会在内存清理时被杀死:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        String channelId = "your_channel_id";
        NotificationChannel channel =
                new NotificationChannel(channelId, "Foreground Service Channel",
                        NotificationManager.IMPORTANCE_HIGH);
        ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
                .createNotificationChannel(channel);
        Notification notification = new NotificationCompat.Builder(this, channelId)
                .setContentTitle(getString(R.string.app_name))
                .setContentText(getString(R.string.notification_text))
                .setSmallIcon(R.mipmap.ic_launcher)
                .setOngoing(true)
                .build();

        serviceIntent = intent;
        startForeground(1, notification);
        return START_REDELIVER_INTENT;
    } else {
        return super.onStartCommand(intent, flags, startId);
    }
}

@Override
public void onTaskRemoved(Intent rootIntent) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
        restartServiceIntent.setPackage(getPackageName());

        PendingIntent restartServicePendingIntent =
                PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent,
                        PendingIntent.FLAG_ONE_SHOT);
        AlarmManager alarmService =
                (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        if (alarmService != null) {
            alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000,
                    restartServicePendingIntent);
        }
        super.onTaskRemoved(rootIntent);
    }
}

以上代码的作用是在Android 10及更高版本上,将前台服务设置为具

相关内容

热门资讯

发现一款!开挂!wpk软件是真... 『标题:当前标题』主打赛后复盘的 AI 游戏攻略黑科技走红,对局总结能力开挂。上传对局回放或者战绩截...
大神推荐透视挂!wepoker... 很多人使用云端 AI 时,都担心wepokerplus透视脚本免费、内部资料上传带来隐私风险。这款本...
分享实测辅助挂!wepoker... 分享实测辅助挂!wepoker养号规律,WPK怎么开挂脚本(果然真的是有辅助挂)AI 是一款可以让一...
研究成果透视挂!微扑克数据分析... 微扑克数据分析AI 游戏攻略黑科技上线本地缓存功能,离线查阅能力开挂。提前下载对应游戏攻略数据包,断...
安装程序教程辅助挂!wepok... 您好:wepoker破解工具这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用...
总算了解!开挂!wpk插件辅助... 总算了解!开挂!wpk插件辅助,WPK开挂脚本安装(固有真的有开挂)AI 智能体黑科技再上新,自动化...
德州论坛透视!wepoker怎... 『标题:当前标题』主打赛后复盘的 AI 游戏攻略黑科技走红,对局总结能力开挂。上传对局回放或者战绩截...
技巧教程辅助挂!wepoker... 本地部署 AI 黑科技工具迎来新版本,不用上传文件到云端就能完成wepoker轻量版辅助解析、 AI...
分享开挂内幕辅助器!德普之星a... 德普之星app安卓版破解版AI 游戏攻略黑科技上线本地缓存功能,离线查阅能力开挂。提前下载对应游戏攻...
一分钟揭秘辅助挂!wpk德州局... 您好:wpk德州局怎么透视这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户...