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

相关内容

热门资讯

透视科技!拱趴大菠萝挂(透视)... 透视科技!拱趴大菠萝挂(透视)黑科技教程(2025已更新)(哔哩哔哩)1、游戏颠覆性的策略玩法,独创...
透视透视!aapoker万能辅... 透视透视!aapoker万能辅助器(透视)真的假的(其实存在有挂)1、上手简单,内置详细流程视频教学...
透视规律!拱趴大菠萝怎么开挂(... 透视规律!拱趴大菠萝怎么开挂(透视)介绍教程(2025已更新)(哔哩哔哩);所有人都在同一条线上,像...
透视了解!aapoker怎么拿... 透视了解!aapoker怎么拿好牌(透视)发牌逻辑(一直真的有挂)1、aapoker怎么拿好牌系统规...
透视脚本!hardrock透视... 透视脚本!hardrock透视工具(透视)必胜教程(2022已更新)(哔哩哔哩)1、hardrock...
透视攻略!agpoker辅助(... 透视攻略!agpoker辅助(透视)线上教程(2023已更新)(哔哩哔哩)1、全新机制【agpoke...
透视存在!aapoker怎么设... 透视存在!aapoker怎么设置抽水(透视)万能辅助器(其实真的有挂);1、在aapoker怎么设置...
透视辅助!pokemmo内置修... 透视辅助!pokemmo内置修改器(透视)揭秘攻略(2024已更新)(哔哩哔哩)1、pokemmo内...
透视玄学!aapoker辅助软... 透视玄学!aapoker辅助软件合法吗(透视)免费透视脚本(一贯真的是有挂)1、让任何用户在无需aa...
透视规律!werplan辅助软... 透视规律!werplan辅助软件(透视)必赢方法(2022已更新)(哔哩哔哩)该软件可以轻松地帮助玩...