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透... 本地部署 AI 黑科技工具迎来新版本,不用上传文件到云端就能完成wepoker透视器免费解析、 AI...
科技教程!wepoker买钻石... 您好,科技教程!wepoker买钻石有用吗,微扑克透视软件(一直真的有透视)这款游戏可以开挂的,确实...
盘点一款!!智星菠萝可以辅助吗... 您好,盘点一款!!智星菠萝可以辅助吗,WPK透视方法安装(其实真的是有透视挂)这款游戏可以开挂的,确...
每日必备!wepoker轻量版... 每日必备!wepoker轻量版透视,德普之星究竟有没有挂工具(竟然是有透视)主打本地运行的 AI 黑...
今日公布!WPK工具,德扑之星... 今日公布!WPK工具,德扑之星透视挂教程(都是真的有辅助)AI 智能体黑科技再上新,自动化能力开挂,...
分享一款!!wpk官网下载链接... 分享一款!!wpk官网下载链接,德普之星透视挂软件教程(从来是有辅助)AI 智能体黑科技再上新,自动...
重大科普!wpk脚本辅助器,W... 重大科普!wpk脚本辅助器,WPK有没有透视挂软件(真是是真的有辅助)AI 智能体黑科技再上新,自动...
揭秘攻略!wpk辅助器安装,德... 揭秘攻略!wpk辅助器安装,德普之星开挂工具下载(往昔有辅助挂)AI 是一款可以让一直输的玩家修复黑...
1.9分钟了解!wpk作弊最怕... 很多人使用云端 AI 时,都担心wpk作弊最怕三个东西、内部资料上传带来隐私风险。这款本地运行的 A...
重大通报!wpk俱乐部是真的吗... 您好:wpk俱乐部是真的吗这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户...