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

相关内容

热门资讯

开挂透视!aapoker能控制... 开挂透视!aapoker能控制牌吗,微乐自建房免费黑科技推荐,绝活儿教程(有挂分析)-哔哩哔哩1、a...
了解透视!pokemmo修改器... 您好,pokemmo修改器手机版这款游戏可以开挂的,确实是有挂的,需要了解加去威信【13670430...
分享透视!约局吧德州真的存在透... 分享透视!约局吧德州真的存在透视吗,微乐麻将脚本掌上程序,指引教程(有挂秘籍)-哔哩哔哩1、下载好约...
推荐透视!德普之星透视辅助,小... 推荐透视!德普之星透视辅助,小程序微乐陕西挖坑辅助器,练习教程(有挂辅助)-哔哩哔哩1、德普之星透视...
有挂透视!wepoker作弊方... 有挂透视!wepoker作弊方法,微乐麻将脚本掌上程序,教材教程(有挂讲解)-哔哩哔哩运wepoke...
总结透视!约局吧app有挂吗,... 总结透视!约局吧app有挂吗,微乐小程序辅助脚本平台,举措教程(有挂方式)-哔哩哔哩1、很好的工具软...
总结透视!wepoker有没有... 总结透视!wepoker有没有挂,微乐云南小程序辅助器,方式教程(有挂存在)-哔哩哔哩1、wepok...
科普透视!hhpoker的辅助... 科普透视!hhpoker的辅助是真的吗,微乐自建房辅助可信吗,大纲教程(有挂头条)-哔哩哔哩1、操作...
详细透视!德普之星透视,微乐小... 详细透视!德普之星透视,微乐小程序辅助器脚本,课程教程(有挂总结)-哔哩哔哩1、用户打开应用后不用登...
推荐透视!wepoker透视器... 推荐透视!wepoker透视器免费,微乐广西自建房免费黑科技下载,窍要教程(有挂技术)-哔哩哔哩1、...