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

相关内容

热门资讯

透视安卓版"hhpk... 透视安卓版"hhpkoer辅助器"详细辅助安装教程(本然有挂);原来确实真的有挂(需添加指定薇136...
推荐一款!pokemmo手机脚... 推荐一款!pokemmo手机脚本,wepoker怎么拿到好牌,分享教程(有挂软件)1、不需要AI权限...
透视工具"wepok... 透视工具"wepoker私人局可以透视"详细辅助必赢教程(果然真的是有挂),支持语音通讯、好友开房及...
必备辅助推荐!pokemmo脚... 必备辅助推荐!pokemmo脚本辅助器下载,aapoker万能辅助器,力荐教程(有挂透视);实战中需...
透视透视"wepok... 透视透视"wepoker辅助器有哪些功能"详细辅助辅助教程(往昔真的是有挂)1、玩家可以在wepok...
每日必看推荐!hhpoker透... 每日必看推荐!hhpoker透视方法,德扑圈透视挂,曝光教程(有挂软件);实战中需综合运用上述技巧,...
透视总结"wpk显示... 透视总结"wpk显示有作弊"详细辅助2025版教程(最初有挂)科技教程也叫必备教程,这是一款功能强大...
最新技巧!wpk透视插件,德普... 最新技巧!wpk透视插件,德普之星透视辅助软件是真的吗,透明挂教程(有挂神器)这是由厦门游乐互动科技...
透视科技"wepok... 透视科技"wepoker透视苹果系统"详细辅助辅助教程(本然是有挂)1、玩家可以在wepoker透视...
最新技巧!wepoker底牌透... 最新技巧!wepoker底牌透视脚本,wepoker透视破解版,可靠教程(有挂辅助);大神普及一款德...