2

В настоящее время я работаю над push-уведомлением в своем проекте. Когда отображается push-уведомление, я хочу открыть активность Mynotification, когда вы нажимаете на уведомление, но всегда открываете MainActivity, почему? Я также google и SO для этого, но не могу найти правильный ответ.Как открыть мероприятие при нажатии кнопки pushnotification?

Вот мой MyFirebaseMessagingService:

public class MyFirebaseMessagingService extends FirebaseMessagingService { 

    private static final String TAG = "MyFirebaseMsgService"; 

    @Override 
    public void onMessageReceived(RemoteMessage remoteMessage) { 
     sendNotification(remoteMessage.getNotification().getBody()); 

    } 

    private void sendNotification(String messageBody) { 


     Intent intent = new Intent(this, MyNotification.class); 
     intent.putExtra("Message",messageBody); 
     intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
     PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 
       0); 

     Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
     NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) 
       .setSmallIcon(R.mipmap.ic_launcher) 
       .setContentTitle("Shri Sidhbali Baba") 
       .setContentText(messageBody) 
       .setAutoCancel(true) 
       .setSound(defaultSoundUri) 
       .setContentIntent(pendingIntent); 

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

     notificationManager.notify(0, notificationBuilder.build()); 
    } 
} 

И вот мой файл манифеста:

<activity android:name=".MyNotification" 
      android:parentActivityName=".MainActivity"> 
      <intent-filter> 
       <action android:name=".MyNotification" android:label="@string/app_name"/> 

       <category android:name="android.intent.category.DEFAULT"/> 


      </intent-filter> 

     </activity> 

Как я могу открыть Mynotification активность при нажатии ой толчок уведомления. Спасибо за ваше время ...

ответ

1

обновление этого:

private void sendNotification(String messageBody) { 


    Intent intent = new Intent(this, MyNotification.class); 
    intent.putExtra("Message",messageBody); 
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, 
      new Intent(this, MyNotification.class), 0); 

    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) 
      .setSmallIcon(R.mipmap.ic_launcher) 
      .setContentTitle("Shri Sidhbali Baba") 
      .setContentText(messageBody) 
      .setAutoCancel(true) 
      .setSound(defaultSoundUri) 
      .setContentIntent(pendingIntent); 

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

    notificationBuilder.setContentIntent(contentIntent); 

    notificationManager.notify(0, notificationBuilder.build()); 
} 
+0

Не работает @Himani – Manish

+0

добавить эту строку notificationBuilder .setContentIntent (contentIntent); –

+0

setContentIntent (pendingIntent); это изменение в setContentIntent (contentIntent); – Manish

0

попытка удалить эту строку в Manifest

android:parentActivityName=".MainActivity" 

Edit 1: Вы можете прочитать здесь https://developer.android.com/training/implementing-navigation/ancestral.html

И причина в том, что когда вы вызываете свою активность «MyNotification», задний стек «автоматически» добавляет родительскую активность в задний стек для вас, поэтому вы можете нажать назад для возврата в вашу «MainActivity»

+0

любая причина, почему @MinWan? – Manish

+0

@ManishYadav Я отредактировал свой ответ. Надеюсь, поможет. – MinWan

2

AFAIK, этот фрагмент кода запускается, когда приложение находится на переднем плане. Когда он находится в фоновом режиме, Firebase отправляет уведомление на системный трей. Я столкнулся с подобной проблемой. Когда он доставляет в системный лоток, он всегда открывал MainActivity. Я заметил, что firebase позволяет передавать аргументы в намерение. Я использовал эту технику, чтобы прочитать пользовательскую строку (открыть параметры опций из консоли сообщений firebase и указать ключ как «элемент» и значение как «MyNotification»). Прочитайте эту строку из основной деятельности и перенаправить управление соответствующей деятельностью с вашего MainActivity :: метод OnCreate()

//private String ITEM = "item"; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    //Parse the input passed to the activity 
    Intent intent = getIntent(); 
    String input = intent.getStringExtra(ITEM); 
    //Redirect to MyNotification 
    Intent redirect = new Intent(this, MyNotification.class); 
    startActivity(redirect); 
} 
+0

В моем варианте консоли консоли FCM для приложения «Удалить» ... можно сказать, как я добавляю ключ – Manish

+0

Я имею в виду «Новое сообщение» на console.firebase.google.com-> Уведомление Нажмите «Дополнительные параметры», что вы видите ниже события конверсии. Это та же консоль, что и для отправки уведомлений в ваше приложение. –

+0

Не работайте для меня. Он показывает ошибку. Невозможно запустить активность. Цель - null. –

0

Попробуйте один

public class VideoNotification extends AppCompatActivity { 
    public Bitmap image ,bmp; 
    public NotificationCompat.Builder nb; 
    final String url = "https://www.google.es/images/srpr/logo11w.png"; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_image_notification); 


    } 

    public void createNotification(View view) { 
     // Prepare intent which is triggered if the 
     // notification is selected 
     Intent intent = new Intent(this, VideoActivity.class); 
     PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0); 

     nb = new NotificationCompat.Builder(this); 
     nb.setSmallIcon(R.drawable.icon); 
     nb.setContentTitle("Image Notification"); 
     nb.setContentText("Set Content text"); 
     nb.setTicker("Set Ticker text"); 
     // nb.setStyle(new NotificationCompat.BigTextStyle().bigText("Big View Styles")); 



     /* try { 
      URL url = new URL("https://www.gstatic.com/webp/gallery3/1.png"); 
      image = BitmapFactory.decodeStream(url.openConnection().getInputStream()); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } */ 

     Glide. 
       with(this). 
       load(url). 
       asBitmap() 
       .centerCrop() 
       .into(new SimpleTarget<Bitmap>(200,200) { 
        @Override 
        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) { 

         NotificationCompat.BigPictureStyle bps = new NotificationCompat.BigPictureStyle().bigPicture(resource); 
         bps.setSummaryText("Summary text appears on expanding the notification"); 
         nb.setStyle(bps); 

        } 
       }); 


     // Width and height 


     // NotificationCompat.BigPictureStyle bps = new NotificationCompat.BigPictureStyle().bigPicture(bmp); 
     // bps.setSummaryText("Summary text appears on expanding the notification"); 
     // nb.setStyle(bps); 





     /* NotificationCompat.BigPictureStyle bps = new NotificationCompat.BigPictureStyle().bigPicture(bmp); 
     bps.setSummaryText("Summary text appears on expanding the notification"); 
     nb.setStyle(bps); */ 
     // Bitmap bitmap_image = BitmapFactory.decodeResource(this.getResources(), R.drawable.picture); 
     // NotificationCompat.BigPictureStyle s = new NotificationCompat.BigPictureStyle().bigPicture(bitmap_image); 
     // s.setSummaryText("Summary text appears on expanding the notification"); 
     // nb.setStyle(s); 

     TaskStackBuilder TSB = TaskStackBuilder.create(this); 
     TSB.addParentStack(VideoNotification.class); 
     // Adds the Intent that starts the Activity to the top of the stack 
     TSB.addNextIntent(intent); 
     PendingIntent resultPendingIntent = 
       TSB.getPendingIntent(
         0, 
         PendingIntent.FLAG_UPDATE_CURRENT 
       ); 

     nb.setContentIntent(resultPendingIntent); 
     nb.setAutoCancel(true); 
     nb.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE); 
     Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
     nb.setSound(alarmSound, AudioManager.STREAM_MUSIC); 
     NotificationManager mNotificationManager = 
       (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE); 
     // mId allows you to update the notification later on. 
     mNotificationManager.notify(11221, nb.build()); 
    } 


} 
+0

на самом деле я не хочу использовать внешние библиотеки ... но спасибо за ваше время @ vishnumm93 – Manish

Смежные вопросы