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

相关内容

热门资讯

记者揭秘!创思维激k透视挂,雀... 记者揭秘!创思维激k透视挂,雀友会辅助潮汕麻将脚本,详细工具(有挂方法)1、首先打开雀友会辅助潮汕麻...
黑科技技巧!wepoker有脚... 黑科技技巧!wepoker有脚本吗,红龙poker辅助,果然是真的有挂(有挂方式)一、红龙poker...
一分钟快速了解!微信小程序微乐... 一分钟快速了解!微信小程序微乐辅助器教程,微乐家乡官方app下载,详细工具(有挂总结)1)微信小程序...
黑科技辅助挂!wepoker私... 黑科技辅助挂!wepoker私局辅助,德普之星有透视辅助吗,都是真的是有挂(有挂讲解)1、完成德普之...
一分钟快速了解!财神十三张脚本... 一分钟快速了解!财神十三张脚本辅助,小松宿松游戏辅助,详细教程(有挂详情)所有人都在同一条线上,像星...
软件辅助挂!wejoker辅助... 软件辅助挂!wejoker辅助软件,德普之星辅助软件,都是真的有挂(有挂技巧)1、每一步都需要思考,...
必备攻略!微乐陕西小程序破解器... 必备攻略!微乐陕西小程序破解器下载,微信小程序游戏破解微乐游戏,详细教程(有挂分析)1、该软件可以轻...
突发!哈糖大菠萝软件下载,德普... 突发!哈糖大菠萝软件下载,德普之星辅助器,切实存在有挂(有挂详细)1、操作简单,无需德普之星辅助器手...
科普攻略!超凡辅助软件,518... 科普攻略!超凡辅助软件,518互游辅助器下载,详细挂(了解有挂)1、这是跨平台的518互游辅助器下载...
无独有偶!wepoker怎么拿... 无独有偶!wepoker怎么拿到好牌,德普之星透视,本来是真的有挂(有挂分享)1、德普之星透视模拟器...