我正在構建一個帶有碎片的應用程序,並且正在使用Firebase通知。我想,當用戶點擊通知時,將他發送到MainActivity上的Fragment1。而且,我已經做到了,但問題在於,只有當應用程序處於前臺時纔有效。當應用程序處於後臺通知狀態時,將我發送到MainActivity而不是Fragment1。 這是MyFirebaseMessagingService:從應用程序在後臺的通知到片段?
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d(TAG, "From " + remoteMessage.getFrom());
Log.d(TAG, "Body " + remoteMessage.getNotification().getBody());
sendNotification(remoteMessage);
Log.d("Msg", "Poruka je stigla");
}
private void sendNotification(RemoteMessage remoteMessage){
Intent intent=new Intent(myFirebaseMessagingService.this, MainActivity.class);
intent.putExtra("action", "goToFragment1");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent=PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notification=new NotificationCompat.Builder(this)
.setSmallIcon(logo)
.setContentText(remoteMessage.getNotification().getBody())
.setContentTitle("Naslov")
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notification.build());
}}
這是我的MainActivity:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dugme=(Button)findViewById(R.id.dugme1);
dugme2=(Button)findViewById(R.id.subscribe);
dugme.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Fragment fragment = null;
if(view==dugme) {
fragment = new Fragment1();
}
FragmentTransaction transaction=getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.myFragment, fragment);
transaction.addToBackStack(null);
transaction.setTransition(FragmentTransaction.TRANSIT_NONE);
transaction.commit();
}
});
String msg=getIntent().getStringExtra("action");
FragmentManager fragmentManager=getSupportFragmentManager();
FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
if (msg!=null){
if (msg.equals("goToFragment1")){
Fragment1 fragment1=new Fragment1();
fragmentTransaction.replace(R.id.myFragment, fragment1);
fragmentTransaction.commit();
}
}
dugme2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FirebaseMessaging.getInstance().subscribeToTopic("android");
Log.d("Log", "Uspesno ste se pretplatili");
}
});
}
我該怎麼辦?
沒有廣播接收器,再次發送我的第一頁(主要活動) –
@RRR是正確的,onNewIntent將被調用而不是onCreate,因此您將不得不處理onNewIntent中的片段選擇。如果您有疑問,只需通過添加日誌來檢查:) – Doppie
但是,當上面的代碼沒有改變任何東西時,我必須在onNewIntent()中寫入。 –