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及更高版本上,将前台服务设置为具

相关内容

热门资讯

攻略教程!wepoker有什么... 您好:wepoker有什么规律这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多...
实测必看!如何下载wpk透视版... AI 黑科技赛道又上新,这款智能处理工具堪称效率开挂,专门面向短视频创作者打造。它打通脚本撰写、AI...
终于懂了!wpk辅助软件,WP... 本地部署 AI 黑科技工具迎来新版本,不用上传文件到云端就能完成wpk辅助软件解析、 AI 处理、w...
盘点一款!!wpk真的有透视嘛... 盘点一款!!wpk真的有透视嘛,微扑克科技透视助手(原本是有辅助挂)AI 智能体黑科技再上新,自动化...
玩家必用!wepoker私人局... AI 黑科技赛道又上新,这款智能处理工具堪称效率开挂,专门面向短视频创作者打造。它打通脚本撰写、AI...
玩家攻略推荐!德普之星怎么开辅... 很多人使用云端 AI 时,都担心德普之星怎么开辅助、内部资料上传带来隐私风险。这款本地运行的 AI ...
热点推荐!!wepoker免费... 本地部署 AI 黑科技工具迎来新版本,不用上传文件到云端就能完成wepoker免费脚本咨询解析、 A...
透明教程!wpk系统是否存在作... AI 黑科技赛道又上新,这款智能处理工具堪称效率开挂,专门面向短视频创作者打造。它打通脚本撰写、AI...
重大消息!有没有人wepoke... AI 黑科技赛道又上新,这款智能处理工具堪称效率开挂,专门面向短视频创作者打造。它打通脚本撰写、AI...
技巧知识分享!wepoker公... 很多人使用云端 AI 时,都担心wepoker公共底牌、内部资料上传带来隐私风险。这款本地运行的 A...