首页 > 解决方案 > 持久通知android

问题描述

我需要创建一个持久通知 - 即使在新的 Android 版本上也是如此。我使用带有 (START_STICKY) 的前台服务来显示通知。通知是在 onCreate() 方法中创建的,并且我不时重新启动前台服务 - 以防万一它被杀死。

这就是我创建通知的方式:

String CHANNEL_ID = MainActivity.packageName+".notification";// The id of the channel.
            CharSequence name = getString(R.string.app_name);// The user-visible name of the channel.
            int importance = NotificationManager.IMPORTANCE_HIGH;


            NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
                mChannel.setSound(null, null);
                notificationManager.createNotificationChannel(mChannel);

            }

            NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(this, MainActivity.packageName+".notification");

            Intent main = new Intent(this, MainActivity.class);
            main.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, main,  PendingIntent.FLAG_UPDATE_CURRENT);

            // set intent so it does not start a new activity
            Notification notification  = nBuilder
                    .setContentIntent(pendingIntent)
                    .setSmallIcon(R.drawable.icon)
                    .setWhen( System.currentTimeMillis())
                    .setContentTitle("my app")
                    .setContentText("my msg")
                    .setOngoing(true)
                    .setChannelId(MainActivity.packageName+".notification")
                    .build();

            notification.flags |= Notification.FLAG_AUTO_CANCEL;
            //notificationManager.notify(StaticMembers.notifId, notification);
         
            startForeground(StaticMembers.notifId+1, notification);

通知会显示,但在某些手机型号上,几天后通知不再显示,即使服务仍在运行。

我应该怎么办?我创建通知的方式有问题吗?如果显示通知,我应该检查服务何时运行,如果不重新创建它?

谢谢

标签: androidservicenotificationsforeground-service

解决方案


推荐阅读