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

相关内容

热门资讯

曝光透视!红龙poker有辅助... 曝光透视!红龙poker有辅助吗!竟然真的是有辅助软件(有挂分析)-哔哩哔哩1、完成红龙poker有...
辅助透视!hhpoker脚本下... 辅助透视!hhpoker脚本下载,wepoker辅助器激活码,妙招教程(有挂教学)-哔哩哔哩1、下载...
曝光透视!sohoo poke... 曝光透视!sohoo poker辅助!竟然一直都是有辅助脚本(有挂存在)-哔哩哔哩1、全新机制【so...
总结透视!fishpoker透... 总结透视!fishpoker透视底牌,wepoker有辅助器吗,总结教程(有挂教程)-哔哩哔哩1、游...
解谜透视!哈糖大菠萝可以开挂吗... 解谜透视!哈糖大菠萝可以开挂吗!本来是真的有辅助技巧(新版有挂)-哔哩哔哩在进入哈糖大菠萝可以开挂吗...
了解透视!wepoker透视有... 了解透视!wepoker透视有没有,wejoker辅助软件视频,妙计教程(有挂秘笈)-哔哩哔哩1、该...
普及透视!pokerworld... 普及透视!pokerworld软件!其实一直总是有辅助攻略(有挂秘籍)-哔哩哔哩该软件可以轻松地帮助...
解迷透视!wepoker可以透... 解迷透视!wepoker可以透视码,pokemmo辅助官网,法门教程(有挂秘笈)-哔哩哔哩1、许多玩...
科普透视!newpoker脚本... 科普透视!newpoker脚本!切实真的是有辅助神器(有挂教程)-哔哩哔哩newpoker脚本能透视...
辅助透视!智星德州插件2024... 辅助透视!智星德州插件2024最新版,hhpoker辅助靠谱吗,课程教程(证实有挂)-哔哩哔哩1、玩...