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

相关内容

热门资讯

一分钟了解!柳州红中麻将透视挂... 您好,柳州红中麻将这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在...
发现玩家!嘻游联盟辅助器脚本软... 发现玩家!嘻游联盟辅助器脚本软件,嘻游联盟好像是有辅助器辅助app1、嘻游联盟透视辅助软件激活码多个...
如何分辨真伪!沅江麻将透视脚本... 如何分辨真伪!沅江麻将透视脚本软件,沅江麻将一直存在有透视科普app1、下载好沅江麻将脚本下载之后点...
教学盘点!闲逸碰胡辅助脚本软件... 教学盘点!闲逸碰胡辅助脚本软件,闲逸碰胡本来是有辅助解迷教程进入游戏-大厅左侧-新手福利-激活码辅助...
实测教程!丫丫陕西麻将透视脚本... 实测教程!丫丫陕西麻将透视脚本软件,丫丫陕西麻将一直是真的有透视有挂技巧1、玩家可以在丫丫陕西麻将透...
新手必备!喜乐透视挂脚本软件,... 新手必备!喜乐透视挂脚本软件,喜乐其实是真的有透视挂普及脚本喜乐透视方法中分为三种模型:喜乐靠谱、喜...
我来教教大家!天天贵阳辅助器脚... 我来教教大家!天天贵阳辅助器脚本软件,天天贵阳好像有辅助器了解app亲,关键说明,天天贵阳透视脚本安...
重大通报!边锋老友内蒙古麻将透... 重大通报!边锋老友内蒙古麻将透视脚本软件,边锋老友内蒙古麻将真是是真的有透视详情攻略1、边锋老友内蒙...
最新技巧!天天爱海南麻将开挂脚... 最新技巧!天天爱海南麻将开挂脚本软件,天天爱海南麻将好像有开挂详细教程1、该软件可以轻松地帮助玩家将...
2024教程!雀友棋牌开挂脚本... 2024教程!雀友棋牌开挂脚本软件,雀友棋牌总是有开挂解谜技巧1、进入游戏-大厅左侧-新手福利-激活...