0

Хочу у себя в приложении сделать кастомные notification, нашел на en-So пример того что мне нужно. Сделал все как в примере, но notification не всплывает хотя в доке он отображается.

Каким образом можно сделать так что бы notification всплывал? или может есть еще какие то альтернативные способы?

Вот код который я использую:

RemoteViews remoteViews = new RemoteViews(activity.getPackageName(),
                R.layout.notification_widget);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                activity).setContentTitle("sdgasgsag").setSmallIcon(R.drawable.icon).setContent(
                remoteViews);
        // Creates an explicit intent for an Activity in your app
        Intent resultIntent = new Intent(activity, activity.getClass());
        // The stack builder object will contain an artificial back stack for
        // the
        // started Activity.
        // This ensures that navigating backward from the Activity leads out of
        // your application to the Home screen.
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(activity);
        // Adds the back stack for the Intent (but not the Intent itself)
        stackBuilder.addParentStack(activity.getClass());
        // Adds the Intent that starts the Activity to the top of the stack
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.button1, resultPendingIntent);
        NotificationManager mNotificationManager = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE);
        // mId allows you to update the notification later on.
        mNotificationManager.notify(100, mBuilder.build());
6
  • Вот это не понятно notification не всплывает хотя в доке он отображается.
    – ЮрийСПб
    19 окт 2016 в 11:40
  • @ЮрийСПб ну в смысле , если опустить шторку то в ней виден этот notification, но при закрытой шторке оно не выплывает. не знаю как это объяснить по-другому. Т.е. я вижу только в стату баре маленькую иконку но не вижу выплывающего оповещения. 19 окт 2016 в 11:49
  • Это у вас на всех осях и девайсах?
    – ЮрийСПб
    19 окт 2016 в 13:24
  • Я тестил на Nexus 4 с прошивкой 5.2, попробую еще на других девайсах! Причина может быть в самом устройстве? 19 окт 2016 в 16:26
  • В чём угодно может быть. Но я бы поставил на настройки девайса/оси на реакцию на уведомления в разных режимах (блокирован/нет) и на приоритете/типе уведомлений
    – ЮрийСПб
    19 окт 2016 в 17:44

1 ответ 1

0

Вкратце, так:

            Intent i = new Intent(context, MainScreen.class);
            PendingIntent pi = PendingIntent.getActivity(context, (int) System.currentTimeMillis(), i, PendingIntent.FLAG_CANCEL_CURRENT); 

            android.app.Notification.Builder builder = new android.app.Notification.Builder(context)
                    .setContentTitle(title)
                    .setContentText(text)
                    .setTicker(title)
                    .setSmallIcon(R.drawable.ic_notification)
                    .setContentIntent(pi)
                    .setWhen(System.currentTimeMillis())
                    .setAutoCancel(true)
                    .setDefaults(android.app.Notification.DEFAULT_ALL);

            android.app.Notification notification;
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                //noinspection deprecation
                notification = builder.getNotification();
            } else {
                notification = builder.build();
            }

            NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            try {
                notificationManager.notify(0, notification);
            } catch (Exception e) {
                Log.e(TAG, "showAndroidNotification()", e);
            }

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.