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有辅助... 新手必备!wepoker有辅助器吗,wpk有作弊吗,一直是有挂(有挂技术)1、每一步都需要思考,不同...
玩家必看教程!pokemmo脚... 玩家必看教程!pokemmo脚本辅助器,hh poker辅助器先试用,果然真的有挂(有挂方针)1、点...
一起来探讨!wepokerpl... 一起来探讨!wepokerplus开挂,德普之星怎么设置埋牌,其实是有挂(有挂助手)一起来探讨!we...
热点推荐!wepoker透视脚... 热点推荐!wepoker透视脚本网页,wepokerplus开挂,确实真的有挂(有挂教程)1、热点推...
玩家必备攻略!wepoker开... 玩家必备攻略!wepoker开脚本视频,hhpoker真能买到挂吗,一直存在有挂(有挂辅助)1、起透...
终于懂了!德扑圈有透视吗,微扑... 终于懂了!德扑圈有透视吗,微扑克数据分析,果然是有挂(有挂教学)1、下载好正确养号方法之后点击打开,...
玩家必备教程!hhpoker德... 玩家必备教程!hhpoker德州作弊,pokermaster脚本,真是存在有挂(证实有挂)运辅助工具...
总算明白!hhpoker德州透... 总算明白!hhpoker德州透视,pokermaster辅助器,总是是有挂(有挂透明挂)一、游戏安装...
一起来探讨!来玩德州破解器,w... 一起来探讨!来玩德州破解器,wepoker作弊视频,都是有挂(有挂秘笈)所有人都在同一条线上,像星星...
实测教程!sohoopoker... 实测教程!sohoopoker辅助,pokemmo脚本,本来是有挂(新版有挂)1、模拟器是什么优化,...