Home > Mobile >  How to open fragment from the click of the notification?
How to open fragment from the click of the notification?

Time:04-22

This is my onMessageReceived method. I am getting data from notification i want to open fragment when i click on this notification and get the data from this.

  @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        Log.d("Firebase Push Received", "Frommm: "   remoteMessage.getFrom());
        Log.d("Firebase Push Received", "Notification "  
                " Data: "   remoteMessage.getData());


        // TODO(developer): Handle FCM messages here.
        Log.d(TAG, "From: "   remoteMessage.getFrom());

        // AGREGO EN EL PAYLOAD LA VARIABLE DATA PARA QUE APAREZCA EN EL FOREGROUND, SINO LEE LA VAR NOTIFICATION DEL PAYLOAD
        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            String type = remoteMessage.getData().get("type");
            String title = remoteMessage.getData().get("title");
            String message = remoteMessage.getData().get("body");
            String id = remoteMessage.getData().get("id");
            Log.d(TAG, "type"   type);
            Log.d(TAG, "id"   id);


            Log.d(TAG, "notidata"   remoteMessage.getData());

            boolean flag = false;
            Intent notificationIntent;
            /*SharedPreferences notificationStatus = getApplicationContext().getSharedPreferences(Constants.NotificationStatus, MODE_PRIVATE);
            String status = notificationStatus.getString("status", "");

            if (status.equals("true")) {
                flag = true;
                notificationIntent = new Intent(this.getApplicationContext(), MainActivity.class);
                notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            } else {
                notificationIntent = new Intent(this.getApplicationContext(), StarterActivity.class);
            }
            if (flag) {
                notificationIntent.addCategory((Intent.CATEGORY_LAUNCHER));
                notificationIntent.setAction(Intent.ACTION_MAIN);
            }*/
            notificationIntent = new Intent(this.getApplicationContext(), MainActivity.class);

            notificationIntent.putExtra("id", id);
            notificationIntent.putExtra("type", type);
            notificationIntent.putExtra("isfrom", "notification");
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                    | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            Bundle bundle = new Bundle();
            bundle.putString("lessonId", id);
            bundle.putString("type1", type);
            bundle.putString("isfrom", "notification");

            /*PendingIntent contentIntent = new NavDeepLinkBuilder(getApplicationContext())
                    .setGraph(R.navigation.nav_home)
                    .setDestination(R.id.playerController)
                    .setArguments(bundle)
                    .createPendingIntent();*/
            PendingIntent contentIntent = PendingIntent.getActivity(this.getApplicationContext(), 0, notificationIntent, PendingIntent.FLAG_ONE_SHOT);

            Notification notification = new NotificationCompat.Builder(this, getResources().getString(R.string.default_notification_channel_id))
                    .setContentTitle(title)
                    .setContentText(message)
                    .setSmallIcon(R.drawable.headblack)
                    .setDefaults(Notification.DEFAULT_SOUND)
                    .setContentIntent(contentIntent)
                    .build();

            NotificationManagerCompat manager = NotificationManagerCompat.from(getApplicationContext());
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel channel = new NotificationChannel(getResources().getString(R.string.default_notification_channel_id), getResources().getString(R.string.channel_name), NotificationManager.IMPORTANCE_HIGH);
                manager.createNotificationChannel(channel);
            }
            manager.notify(R.string.default_notification_channel_id, notification);

        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "MessageNotificationBody: "   remoteMessage.getNotification().getBody());
        }

        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated. See sendNotification method below.
    }

This is my main activity..

        public class MainActivity extends AppCompatActivity {
    
      @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
                if (!isTaskRoot() && getIntent().hasCategory(Intent.CATEGORY_LAUNCHER)
                    && getIntent().getAction() != null
                    && getIntent().getAction().equals(Intent.ACTION_MAIN)
            ) {
                finish();
                processIntent(getIntent());
                return;
            }
    
            SharedPreferences notificationStatus = getApplicationContext().getSharedPreferences(Constants.NotificationStatus, MODE_PRIVATE);
            SharedPreferences.Editor edit = notificationStatus.edit();
            edit.putString("status", "true");
            edit.apply();
            progressBar = findViewById(R.id.spin_kit);
            progressBarHolder = findViewById(R.id.progressBarHolder);
            mAuth = FirebaseAuth.getInstance();
            mDatabase = FirebaseDatabase.getInstance().getReference();
    
            final FirebaseUser user = mAuth.getCurrentUser();
            ActionBar actionBar = getSupportActionBar();
            actionBar.hide();
            navView = findViewById(R.id.nav_view);
            navView.setLabelVisibilityMode(LabelVisibilityMode.LABEL_VISIBILITY_LABELED);
    
            AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                    R.id.navigation_home, R.id.navigation_lessons, R.id.navigation_prematch, R.id.navigation_journals, R.id.navigation_move)
                    .build();
    
            navController = Navigation.findNavController(this, R.id.nav_host_fragment);
            NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
            NavigationUI.setupWithNavController(navView, navController);
    
        }
    


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        processIntent(intent);
    }
    


private void processIntent(Intent intent) {

        if (intent != null && intent.getExtras() != null) {
            mAuth = FirebaseAuth.getInstance();
            mDatabase = FirebaseDatabase.getInstance().getReference();

            final FirebaseUser user = mAuth.getCurrentUser();
            //   checkStatus();
            Bundle bundle = new Bundle();
            id = intent.getExtras().get("id").toString();

            type = intent.getExtras().get("type").toString();
}
        }

From process intent i want to open my fragment using navcontroller but it open the mainactivity and load the home fragment instead the the playerfragment that i want to implement on click of the notification.

The player fragment is in the nav graph of the main activity.

Most of the stack overflow answers contain the navdeeplink that doesnt work here it openes the main activity and load the data of the main activity instead the destination.

Anyone how to open a fragment when user click on the notification when activity is running and when activity is in the background ?

CodePudding user response:

There is no direct way to open fragment from notifications. In the notification pending intent add putextras and get it in activity and navigate corresponding fragment

notificationIntent.putExtra("redirect", "homefragment");

In your activity

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

      String value= intent.getExtras().get("redirect").toString();
      if(value=="homefragment")
       {
              // redirect your fragment
       }

CodePudding user response:

You can do that using Explicit Deep Links in Navigation Architecture.

You can check this article to proceed with it: Navigating with Deep Links

You should also check Developer Docs. They provide in-depth description of what's going on internally

  • Related