Мое приложение является активным с тремя фрагментами «1», «2» и «3», когда я открываю приложение, оно всегда открывает первый фрагмент.
Я пытаюсь открыть другие фрагменты, второй и третий фрагменты через FCM, передавая данные через json, затем получаю их через MyFirebaseMessagingService, получая Extra, затем передаю его в mainacctivity, где я пытаюсь использовать его для открытия фрагмента. через FragmentTransaction. Но ничего не происходит, когда я нажимаю на уведомление (оно продолжает открывать первый фрагмент, даже если я передаю Extra для второго или третьего фрагмента).
Я проверил различные вопросы и использовал решение в этом FCM Open Activity и фрагмент вызова, когда приложение не работает на устройстве
но все еще не работает для меня.
Ниже всех моих кодов кто-нибудь знает, как я открываю фрагменты «2» и «3» при нажатии на уведомление FCM.
Мой код в 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);
});
});
}); * * 1 010
где tag: "2", это строка, которую я использую здесь для ссылки на второй фрагмент, и я использую аналогичный код для уведомления о третьем фрагменте.
Мой пожарный приемник:
открытый класс MyFirebaseMessagingService extends 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);
}
}
Тогда я передаю лишнюю часть основной деятельности.
Ниже моя основная деятельность, где я пытаюсь использовать 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() {
}