Открывать фрагмент при нажатии уведомления в Android

#android #android-fragments #notifications

#Android #android-фрагменты #уведомления

Вопрос:

Я пытаюсь открыть фрагмент при нажатии уведомления в панели уведомлений. Структура моего приложения:

  • базовое действие с меню навигационного ящика
  • и некоторые фрагменты, которые открываются из меню

Когда я нажимаю на уведомление, действие снова открывается, но не в указанном фрагменте, а в LogCat данные из указанного фрагмента открываются и загружаются, но не с помощью пользовательского интерфейса.

Код уведомления :

        NotificationCompat.Builder  mBuilder = 
    new NotificationCompat.Builder(this);   
      mBuilder.setContentTitle("Comanda Noua");
      mBuilder.setContentText("S-a introdus o comanda noua");
      mBuilder.setTicker("Comanda noua!");
      mBuilder.setSmallIcon(R.drawable.calculator_icon);
     mBuilder.setAutoCancel(true);//inchide notificare dupa ce s-a dat click pe ea

      //creste numar notificare
      mBuilder.setNumber(  numMessages);

      // cream un intent 
      Intent resultIntent = new Intent(this, MainActivity.class);

      //am setat actiune pentru a deschide fragmentul corespunzator notificartii la apasare
      resultIntent.setAction("Action1");
      TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
      stackBuilder.addParentStack(MainActivity.class);


      // 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);

      mBuilder.setContentIntent(resultPendingIntent);

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

      // notificationID allows you to update the notification later on. 
      mNotificationManager.notify(notificationID, mBuilder.build());
  

Код, в котором я открываю фрагмент при нажатии уведомления:

  Intent intent = getIntent();
   try{
        String action = intent.getAction();
       // Log.d("action:",action);

        if(action.equals("Action1")){
             //Log.d("deschidem agenda:",action);
            AgendaFragment fragment = new AgendaFragment();
         FragmentTransaction transaction = getFragmentManager()
                    .beginTransaction();
         transaction.replace(R.id.frame_container, fragment)
            .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
            .addToBackStack(null).commit();
        }else{
           Log.d("eroare", "Intent was null");
        }
   }catch(Exception e){
        Log.e("eroare", "Problem consuming action from intent", e);             
    } 
  

Почему действие открыто, а фрагмент нет?

Комментарии:

1. Почему вы используете TaskStackBuilder для создания ожидающего намерения?

2. Я новичок в Android, и код уведомления у меня есть из Интернета. Я думаю, что использую это, чтобы поместить действие в стек. если я не использовал это, уведомление ничего не делает

Ответ №1:

Попробуйте приведенный ниже код, это более простой способ показать уведомление:

 Intent resultIntent = new Intent(this, MainActivity.class);

resultIntent.setAction("Action1");

PendingIntent resultPendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, resultIntent, PendingIntent.FLAG_CANCEL_CURRENT);

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

Notification notification = new Notification(R.drawable.icon_notification, "Your title", System.currentTimeMillis());
notification.flags = Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(this, "Your title", "Your text", pendingIntent);

mNotificationManager.notify(notificationID, notification);
  

Комментарии:

1. У меня такая ошибка: метод getActivity(Context, int, Intent, int) не определен для типа MainActivity

2. Появляется уведомление, но когда я нажимаю на него, запускается основное действие, но не конкретный фрагмент (фрагмент загружается в LogCat, но пользовательский интерфейс не отображается). И после того, как я вернусь из нового действия экземпляра из уведомления, появится другое уведомление…

3. Я повторяю тестирование. Уведомление запускает мою активность, но не открывает мой фрагмент. В LogCat появляется сообщение о загрузке, но пользовательский интерфейс не отображается на экране, вместо этого у меня есть только действие.

Ответ №2:

ПОПРОБУЙТЕ с широковещательной передачей

В классе уведомлений вы должны отправить broadcast. это метод по умолчанию.

         `intent.setAction("one");
        sendBroadcast(intent);`
  

В базовом действии просто создайте Broadcast reveiver

 private BroadcastReceiver receiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent!=null amp;amp; intent.getAction().equals("one")) 

        {
            displayView(fragement_position);
        }
    }
};
  

При создании BaseAcitivty изменить размер приемника broatcast

   IntentFilter filter = new IntentFilter();
    filter.addAction("one");
    registerReceiver(getList, filter);
  

Необходимо добавить IntentFilter

и вы должны отменить регистрацию при уничтожении базовой активности

@Override
protected void onDestroy() {
unregisterReceiver(receiver);
super.onDestroy();
}