служба переднего плана для постоянного уведомления - PullRequest
0 голосов
/ 09 ноября 2018

У меня есть приложение, которое было построено на уровне API 22, теперь мне пришлось обновить его до уровня API 26, а созданное изначально постоянное уведомление больше не работает. Я пробовал несколько кодов из stackoverflow, но безуспешно для меня.

Мой код:

    void setUpAsForeground(String text) {
        Intent mainActivity = new Intent(getApplicationContext(), MainActivity.class);
        PendingIntent openMainActivity = PendingIntent.getActivity(getApplicationContext(), 0,
                mainActivity, 0);
        // Build the notification object.
        mNotificationBuilder = new Notification.Builder(getApplicationContext())
                .setSmallIcon(R.drawable.radio_icon_128px)
                .setTicker(text)
                .setWhen(0)
//                .setWhen(System.currentTimeMillis())
                .setContentTitle(getResources().getString(R.string.app_name) + text)
                .setContentText(mMusicProvider.getCurrentSongTitle())
                .setContentIntent(openMainActivity)
                .setOngoing(true);
        startForeground(NOTIFICATION_ID, mNotificationBuilder.build());
//        broadcastAction(MainActivity.ACTION_UPDATE_TITLE);
    }

Любой совет будет высоко оценен.

Ответы [ 2 ]

0 голосов
/ 09 ноября 2018

Прежде чем вы сможете доставить уведомление на Android 8.0 и выше, вы должны зарегистрировать канал уведомлений вашего приложения в системе, передав экземпляр NotificationChannel Если все, что вам нужно, это сделать уведомление из вашего приложения, то вы можете использовать этот код.

 public class makeNotification {
        private static final String ChannelId = "ChannelId";
        private static final String CHANNEL_ID = "cahhnel";
        private static final int NOTIFICATION_ID = 99;

        public static void makenotification(Context context) {
          Intent intent = new Intent(context,DemoVolleyActivity.class);
          PendingIntent pendingIntent = PendingIntent.getActivity(context,0,intent,0);
            NotificationManager notificationManager = (NotificationManager)
                    context.getSystemService(Context.NOTIFICATION_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel mChannel = new NotificationChannel(
                        CHANNEL_ID,
                        "Channel Name",
                        NotificationManager.IMPORTANCE_HIGH);
                notificationManager.createNotificationChannel(mChannel);
            }
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context,ChannelId)
                    .setColor(ContextCompat.getColor(context, R.color.colorPrimary))
                    .setSmallIcon(R.drawable.ic_lock_black_24dp)
                    .setContentTitle("My Notification")
                    .setContentText("notification_body")
                    .setDefaults(Notification.DEFAULT_VIBRATE)
                    .setContentIntent(pendingIntent)
                    .setAutoCancel(true);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN
                    && Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
                notificationBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
            }
            notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
        }
    }
0 голосов
/ 09 ноября 2018

Начиная с API 26, вы должны предоставить канал уведомлений для своего приложения, прежде чем будут отображаться какие-либо уведомления. Для Android 7 и ниже установка приоритета обязательна. См. Этот документ для получения дополнительной информации и примеров: https://developer.android.com/training/notify-user/build-notification

...