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... 最新技巧辅助挂!如何判断wpk辅助软件的真假,德扑之星有挂么辅助平台(一贯存在有辅助挂)AI 是一款...
交流学习经验开挂!wpk辅助购... 您好:wpk辅助购买这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌特...
热点推荐辅助挂!wpk有那种辅... 热点推荐辅助挂!wpk有那种辅助吗,wepoker是如何开挂的神器(其实真的有辅助挂)AI 智能体黑...
重大通报透视!WPK靠谱,德普... 德普之星透视AI 游戏攻略黑科技上线本地缓存功能,离线查阅能力开挂。提前下载对应游戏攻略数据包,断网...
2分钟细说开挂!wepoker... 一款 AI 游戏攻略黑科技工具上线,查攻略效率直接开挂。它整合版本更新、装备搭配、BOSS 打法、牌...
最新技巧透视挂!poker辅助... 很多人使用云端 AI 时,都担心poker辅助器免费安装、内部资料上传带来隐私风险。这款本地运行的 ...
玩家必看科普辅助器!wepok... 玩家必看科普辅助器!wepoker能不能透视,WPK透视方法教程(好像是有辅助器)AI 智能体黑科技...
发现玩家辅助挂!wepoker... 本地部署 AI 黑科技工具迎来新版本,不用上传文件到云端就能完成wepoker透视挂底牌解析、 AI...
总算了解!透视挂!wepoke... 总算了解!透视挂!wepoker辅助透视,德扑之星辅助软件安装(一向是有透视挂)AI 智能体黑科技再...
玩家必备教程开挂!德扑之星透视... 德扑之星透视AI 游戏攻略黑科技上线本地缓存功能,离线查阅能力开挂。提前下载对应游戏攻略数据包,断网...