打开或关闭应用程序时,从Firebase Cloud Messaging通知打开片段

时间:2018-09-16 08:25:41

标签: android firebase android-fragments firebase-cloud-messaging

我的应用程序是具有三个片段“ 1”,“ 2”和“ 3”的mainactivity,当我打开应用程序时,它总是打开第一个片段。 我试图通过FCM通过json来打开其他片段,通过FCM打开第二个和第三个片段,然后通过MyFirebaseMessagingService接收它,获取Extra,然后将其传递给mainActivity,在这里我试图用它来打开片段通过FragmentTransaction。但是,当我单击通知时,什么也没有发生(即使我为第二个或第三个片段传递了Extra,它也会继续打开第一个片段)。 我检查了不同的问题,并在此FCM Open Activity and call fragment when the application is not running on device中使用了解决方案 但仍然不能为我工作。 在我所有代码的下方,任何人都知道,单击FCM通知时如何打开片段“ 2”和“ 3”。

我在FCM json中的代码。

exports.sendNotificationHb = functions.database.ref('/Posts/{post_key}').onCreate((snap, context) => {

  const post_key = context.params.post_key;
  console.log('this is the post key: ', post_key);
const fromPost = admin.database().ref(`/Posts/${post_key}`).once('value');
  return fromPost.then(fromPostResult =>{
const body = fromPostResult.val().body;
const title = fromPostResult.val().title;

console.log('body', body);
console.log('title', title);

const payload = {
  notification: {
    title: `${title}`,
    body: `${body}`,
    icon: "default",
    click_action : "com.mywebsite.com.Main"
  },
  data : {
    tag: "2"
  }

};

return admin.messaging().sendToTopic("nnh3", payload)
.then(function(response){
      console.log("Notification sent", response);
})
.catch(function(error){
      console.log("Error sending notification: ", error);
});

});

});

其中标记:“ 2”是一个字符串,我在这里使用它来引用第二个片段,并且我正在使用类似的代码来通知第三个片段。

我的Firebase接收器: 公共类MyFirebaseMessagingService扩展了FirebaseMessagingService {

private static final String MyChannel_ID = "com.mywebsite.com.NNH";


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

    String notification_title = remoteMessage.getNotification().getTitle();
    String notification_message = remoteMessage.getNotification().getBody();
    String id = remoteMessage.getNotification().getTag();

    String click_action = remoteMessage.getNotification().getClickAction();



    Intent resultIntent = new Intent(click_action);

    resultIntent.putExtra("id", id);
    resultIntent.putExtra("push", "tag");

    resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    PendingIntent resultPendingIntent = PendingIntent.getActivity(this,0, resultIntent,
            PendingIntent.FLAG_ONE_SHOT
            );


    NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(this, MyChannel_ID )
                    .setSmallIcon(R.mipmap.ic_launcher_round)
                    .setContentTitle(notification_title)
                    .setContentText(notification_message)
                    .setGroup(MyChannel_ID )
                    .setGroupSummary(true)
                    .setAutoCancel(true)
                    .setContentIntent(resultPendingIntent);



    int mNotificationId = 1;
    NotificationManager mNotifyMgr =
            (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    mNotifyMgr.notify(mNotificationId, notificationBuilder.build());

    notificationBuilder.setContentIntent(resultPendingIntent);

}

}

然后,我将多余的内容传递给mainactivity。 以下是我的主要活动,我试图从意图中使用Extra打开片段。 我在goToFragment(id)下创建了一个方法;看不同的文档,但没有用,我在做什么错? 我不知道在goToMenu()方法下创建什么;

public class  MainActivity extends BaseActivity {

private static final String TAG = "MainActivity";

private FragmentPagerAdapter mPagerAdapter;
private ViewPager mViewPager;

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

    Intent i = getIntent();
    Bundle extras = i.getExtras();

    if(extras != null) {
        String push = extras.getString("push");
        if (push != null) {
            Integer id = Integer.parseInt(extras.getString("id"));
            goToDetalleDenuncia(id);
        }else if (  extras.getString("tag") != null  ){
            Integer id = Integer.parseInt(extras.getString("tag"));
            goToFragment(id);
        }else
            goToMenu();
    }else
        goToMenu();

// Create the adapter that will return a fragment for each section
    mPagerAdapter = new 
FragmentPagerAdapter(getSupportFragmentManager()) {
        private final Fragment[] mFragments = new Fragment[] {
                new FirstFragment(),
                new SecondFragment(),
                new HabalFragment(),
        };
        private final String[] mFragmentNames = new String[] {
                getString(R.string.first_fragment),
                getString(R.string.second_fragment),
                getString(R.string.third_fragment)

        };
        @Override
        public Fragment getItem(int position) {return mFragments[position];
        }
        @Override
        public int getCount() {
            return mFragments.length;
        }
        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentNames[position];
        }
    };
    // Set up the ViewPager with the sections adapter.
    mViewPager = findViewById(R.id.container);
    mViewPager.setAdapter(mPagerAdapter);
    TabLayout tabLayout = findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

private void goToFragment(Integer id) {


    if (id == 1) {
        Fragment fragment = new FirstFragment();
        android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.container, fragment);
        transaction.addToBackStack(null);
        transaction.commit();
    }
    if (id == 2) {
        Fragment fragment = new SecondFragment();
        android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.container, fragment);
        transaction.addToBackStack(null);
        transaction.commit();
    }
    if (id == 3) {
        Fragment fragment = new ThirdFragment();
        android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.container, fragment);
        transaction.addToBackStack(null);
        transaction.commit();
    }

}
private void goToMenu() {
}

0 个答案:

没有答案