How to open fragment page, when pressed a notification in android

前端 未结 5 1734
一整个雨季
一整个雨季 2020-12-04 15:45

I am trying to open a fragment when I press a notification in the notification bar. My app structure is:

  • a base activity with a nav drawer menu
  • so

5条回答
  •  死守一世寂寞
    2020-12-04 16:00

    It is a detailed answer and i believe if you follow it carefully. You will solve your problem.

    When you send the notification from Firebase this methods runs first

    public class FirebaseMessageService extends FirebaseMessagingService {
    
    private static final String TAG = "MyFirebaseMsgService";
    Map data;
    // [START receive_message]
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
    
        if (remoteMessage.getData().size() > 0) {
            removeUserInfoByKeyAsStatic(getApplicationContext(), USER_KNOW_CREATED_EVENT_NOTIFICATION_DATA);
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
            data = remoteMessage.getData();
    
    
            HashMap copyData = new HashMap<>(data);
    
            //Calling method to generate notification
            sendNotification(data.get("body"), data.get("title"), copyData);
        }
    
    }
    

    then you run the above sendNotification(..) method. In this method i set the notification data to the SharedPref. Dont be offensive about it., we will remove it later immediately when we use it.

    I used my login data and set intent to diffrent Activity according to my roleID

    private void sendNotification(String messageBody, String messageTitle, HashMap data) {
    
        // this methods checks my notification data is null ? isNullOrEmptyExt : "simple java is null control method"
        if (!isNullOrEmptyExt(data.get("data"))) { 
    
            Intent intent;
            final User myInfos = getMyInfos(getApplicationContext()); // this gives me login user data.
            boolean isConsumerOrVolunteer = myInfos.getRoleID() == Constants.ROLES.CONSUMER || myInfos.getRoleID() == Constants.ROLES.VOLUNTEER;
            // I want to show here. You can select diffrent Activity with your data..
            if (isConsumerOrVolunteer) {
                // this set my notification data to SharedPref
                setUserInfoByKeyAsStatic(getApplicationContext(), USER_KNOW_CREATED_EVENT_NOTIFICATION_DATA, data.get("data"));
                intent = new Intent(this, EventListActivity.class);
            } else {
                intent = new Intent(this, ProducerActivity.class);
            }
    
            // after from here are the generally same. tricks above
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                    PendingIntent.FLAG_ONE_SHOT);
    
            String channelId = getString(R.string.default_notification_channel_id);
            Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            NotificationCompat.Builder notificationBuilder =
                    new NotificationCompat.Builder(this, channelId)
                            .setSmallIcon(R.mipmap.ic_launcher)
                            .setContentTitle(messageTitle)
                            .setContentText(messageBody)
                            .setAutoCancel(true)
                            .setSound(defaultSoundUri)
                            .setContentIntent(pendingIntent);
    
            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    
            // Since android Oreo notification channel is needed.
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel channel = new NotificationChannel(channelId,
                        "Channel human readable title",
                        NotificationManager.IMPORTANCE_DEFAULT);
                notificationManager.createNotificationChannel(channel);
            }
    
            notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    
        }
    
    }
    

    When you send notification this above two methods runs. So after that you will click the notification on your phone.. right.. This click operation opens the Intent(ActivityName) that you set before in sendNotification(..) method.

    E.g you click the notification and your ProducerActivity or EventListActivity opens..

    If your Role is Consumer or Volunteer ( according to my app roles ) you set the notification data to SharedPref

       boolean isConsumerOrVolunteer = myInfos.getRoleID() == Constants.ROLES.CONSUMER || myInfos.getRoleID() == Constants.ROLES.VOLUNTEER;
        // I want to show here. You can select diffrent Activity with your data..
        if (isConsumerOrVolunteer) {
            // this set my notification data to SharedPref
            setUserInfoByKeyAsStatic(getApplicationContext(), USER_KNOW_CREATED_EVENT_NOTIFICATION_DATA, data.get("data"));
            intent = new Intent(this, EventListActivity.class);
        } else {
            intent = new Intent(this, ProducerActivity.class);
        }
    

    So you opened the EventListActivity. Lets see what will we do in EventListActivity

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_event_list_main);
    
        GsonBuilder gsonBuilder = new GsonBuilder();
        gson = gsonBuilder.create();
    
        // this gives me data from `SharePref`
        String notificationEventDataString = getUserInfoByKeyAsStatic(this, USER_KNOW_CREATED_EVENT_NOTIFICATION_DATA);
    
        // then check the datastring that comes from SharedPref - simple java null check method
        if(!isNullOrEmptyExt(notificationEventDataString)){
            Bundle bundle = new Bundle();
            bundle.putParcelable(EVENT, gson.fromJson(notificationEventDataString, Event.class));
            removeUserInfoByKeyAsStatic(this, USER_KNOW_CREATED_EVENT_NOTIFICATION_DATA);
            openFragmentWithoutAnimation(this, R.id.drawer_layout, bundle, EventPreviewFragment.class, EVENT_PREVIEW_FRAGMENT);
        }
    

    You get the data from SharedPref . This will not be empty because when you get the notfication we already set it in sendNotification(..) method .

    So you put your data to bundle and open Fragment with bundle data. Right after you remove the SharedPref data that includes my notification data

    I'm ALSO SHARING MY CUSTOM METHODS WITH YOU

    This one is fragment open method

    public static void openFragmentWithoutAnimation(Context context, int replaceLayout, Bundle bundle, Class fragment, String fragmentTag) {
        Fragment dynamicFragment = null;
        try {
            Class clazz = Class.forName(fragment.getName());
            dynamicFragment = (Fragment) clazz.newInstance();
            System.out.println(clazz.getSuperclass());
            System.out.println(clazz.getName());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    
        AppCompatActivity activity = null;
        if (context instanceof AppCompatActivity) {
            activity = ((AppCompatActivity) context);
        }
        if (activity.getSupportFragmentManager().findFragmentByTag(fragmentTag) == null) {
            FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
            if (bundle != null) {
                dynamicFragment.setArguments(bundle);
            }
            transaction.add(replaceLayout, dynamicFragment, fragmentTag);
            transaction.addToBackStack(fragmentTag);
            transaction.commit();
        }
    }
    

    These are SharedPref set and get methods

    public static void setUserInfoByKeyAsStatic(Context context, String key, String value){
        final SharedPreferences prefs = context.getSharedPreferences(
                USER_INFO_PREFS_KEY, Context.MODE_PRIVATE);// Saved token can be accessed only from this app or other apps that shared same id with this app.
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(key, value);
        editor.apply();
    }
    
    public static String getUserInfoByKeyAsStatic(Context context, String key){
        final SharedPreferences controlPrefs = context.getSharedPreferences(
                USER_INFO_PREFS_KEY, Context.MODE_PRIVATE);
        return controlPrefs.getString(key,null);
    }
    

    And theese are the null check methods

    public static boolean isNullOrEmpty(String value){
    
        if(value == null){
            return true;
        }else return value.isEmpty() || value.equals("null");
    
    }
    
    public static boolean isNullOrEmptyExt(String value){
    
        if(value == null){
            return true;
        }else return value.isEmpty() || value.equals("null") || value.equals(JSON_ARRAY_EMPTY) || value.equals(JSON_OBJECT_EMPTY);
    
    }
    

提交回复
热议问题