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

相关内容

热门资讯

近日!hh poker插件下载... 近日!hh poker插件下载,微乐广西麻辣辅助器,推荐脚本(有挂透明挂)-哔哩哔哩hh poker...
脚本推荐!wepoker怎么设... 脚本推荐!wepoker怎么设置盖牌,wepokerplus外g挂(透视)确实有app(哔哩哔哩)1...
出现新变化!竞技联盟透视插件,... 出现新变化!竞技联盟透视插件,微乐贵阳足鸡麻将开挂,详情脚本(真的有挂)-哔哩哔哩1、下载好竞技联盟...
脚本解密!wpk德州局透视,w... 脚本解密!wpk德州局透视,wpk模拟器多开(透视)果然是有器(哔哩哔哩)1、每一步都需要思考,不同...
透视演示!htx矩阵wepok... 透视演示!htx矩阵wepoker辅助,WePoKer钻石一贯真的有教程,八分钟教程(有挂猫腻)1、...
最终!线上德州的辅助器是什么,... 最终!线上德州的辅助器是什么,微乐广西自建房免费黑科技下载,透视透视(有挂猫腻)-哔哩哔哩1、进入游...
透视操作!hhpoker可以控... 透视操作!hhpoker可以控制吗,HHpoker德州竟然真的是有安装,2分钟教程(详细教程)1、操...
围绕透视问题!德州hhpoke... 围绕透视问题!德州hhpoker是真的吗,小程序微乐贵阳捉鸡麻将挂,详情透视(有挂猫腻)-哔哩哔哩所...
透视必备!aapoker透视方... 透视必备!aapoker透视方法,aapoker公共底牌(透视)本来是真的教程(哔哩哔哩)1、很好的...
透视辅助!wejoker开挂,... 透视辅助!wejoker开挂,微乐小程序游戏辅助器脚本官网,分享脚本(有挂规律)-哔哩哔哩透视辅助!...