Android12中前台服务在1分钟后停止的问题。
创始人
2024-09-30 22:30:35
0

在Android 12中,Google进行了限制,从而限制了前台服务的最长运行时间。这意味着前台服务在1分钟后可能会停止,即使它仍在运行。

为了解决这个问题,我们需要通过以下代码在前台服务中使用一个称为“startForegroundForeground”的新方法:

public class MyForegroundService extends Service {

    private static final String CHANNEL_ID = "MyForegroundServiceChannel";
    private static final int NOTIFICATION_ID = 123;

    @Override
    public void onCreate() {
        super.onCreate();
        createNotificationChannel();
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "My Foreground Service", NotificationManager.IMPORTANCE_LOW);
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("My Foreground Service")
                .setContentText("Running...")
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setContentIntent(pendingIntent)
                .build();

        startForeground(NOTIFICATION_ID, notification);

        // Your code here...

        return START_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

以上代码使用了一个新的方法startForeground来启动前台服务并显示通知。此方法指定了一个常量通知ID和通知构建器,它将通知内容设置为前台服务正在运行,并将选择MainActivity作为通知点击后的意图。

在上述代码中,我们需要通过创建一个通知渠道,并将通知渠道与通知一起使用。

最后,我们需要确保在

相关内容

热门资讯

WePoKe透明挂!德扑快速计... WePoKe透明挂!德扑快速计算胜率(透视)本然是有挂(详细辅助AA德州教程)1、超多福利:超高返利...
透视规律!aapkoer德州辅... 透视规律!aapkoer德州辅助挂下载,wepoker养号规律(详细辅助安装教程)一、aapkoer...
德州之星外挂!wpk微扑克真的... 德州之星外挂!wpk微扑克真的有辅助(透视)从前是真的有挂(详细辅助黑科技教程)1、不需要AI权限,...
透视实锤!wpk辅助器安装,w... 透视实锤!wpk辅助器安装,wpk俱乐部是做什么的(详细辅助透明挂教程)1、wpk辅助器安装系统规律...
WePoKe透明挂!wpk微扑... WePoKe透明挂!wpk微扑克辅助ai(透视)其实有挂(详细辅助wepoke教程)(1)WePoK...
透视神器!wpk透视辅助靠谱吗... 透视神器!wpk透视辅助靠谱吗,wepoker国外版透视(详细辅助AI教程)1、这是跨平台的wpk透...
wepoke有挂!nzt德州辅... wepoke有挂!nzt德州辅助(透视)一直存在有挂(详细辅助专业教程)1、金币登录送、破产送、升级...
透视插件!wepoker透视脚... 透视插件!wepoker透视脚本网页,wepoker免费辅助器(详细辅助透牌教程)1、金币登录送、破...
微扑克游戏辅助器!红龙扑克模拟... 微扑克游戏辅助器!红龙扑克模拟器(透视)原生真的是有挂(详细辅助技巧教程)(1)微扑克游戏辅助器!红...
透视攻略!wpk辅助插件,we... 透视攻略!wpk辅助插件,wepoker轻量版透视(详细辅助2025新版教程);在进入wpk辅助插件...