2017-09-05 79 views
0

我正在通知部分。我可以將用戶導航到通知消息的點擊活動。我的實際任務是將用戶導航到片段。onClick通知要碎片Android

這是通知代碼,它工作正常。

NotificationCompat.Builder builder = 
      new NotificationCompat.Builder(getApplicationContext()) 
        .setSmallIcon(R.mipmap.ic_launcher) 
        .setContentTitle("Lugmah Order Status") 
        .setContentText("The Order Status of Order Id: "+selectedOrderId+ " is: "+status_desc) 
        .setDefaults(NotificationCompat.DEFAULT_SOUND) 
        .setAutoCancel(true); 
    int NOTIFICATION_ID = 12345; 

    Intent targetIntent = new Intent(getApplicationContext(), MainActivity.class); 

    targetIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); 

    targetIntent.putExtra("isTrackOrder", false); 
    targetIntent.putExtra("orderNotification", "orderNotification"); 
    targetIntent.putExtra("isLoggedIn", true); 
    targetIntent.putExtra("status_desc", status_desc); 
    targetIntent.putExtra("selectedOrderId", selectedOrderId); 

    PendingIntent contentIntent = PendingIntent 
       .getActivity(getApplicationContext(), 0, targetIntent, PendingIntent.FLAG_ONE_SHOT); 

    builder.setContentIntent(contentIntent); 


    NotificationManager nManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE); 
    nManager.notify(NOTIFICATION_ID, builder.build()); 

我已經加入MainActivity.java的意圖,因爲這是我加載所有碎片的地方。在這個活動中,我做了這樣的事情。

這裏是內部的onCreate()的代碼:

String orderNotification = getIntent().getStringExtra("orderNotification"); 

     android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); 

     if (orderNotification != null) 
     { 
      if (orderNotification.equals("orderNotification")) 
      { 
       TrackOrderFragment trackOrderFragment = new TrackOrderFragment(); 
       fragmentTransaction.replace(android.R.id.content, trackOrderFragment); 
       fragmentTransaction.addToBackStack(null); 
       fragmentTransaction.commit(); 
      } 
     } 

幫助將不勝感激。

+0

檢查'if(!TextUtils.isEmpty(orderNotification))'而不是'(orderNotification!= null)' – Piyush

+0

您還需要重寫'onNewIntent' –

+0

@ Michal_196 onNewIntent ..我應該把它放在哪裏? – Jacky

回答

3

你的通知代碼工作正常,你需要調整一下代碼onCreate。

if(getIntent().getExtras() != null) { 
    String orderNotification = getIntent().getStringExtra("orderNotification"); 

    if (orderNotification.equals("orderNotification")) 
      { 
       TrackOrderFragment trackOrderFragment = new TrackOrderFragment(); 
       fragmentTransaction.replace(android.R.id.content, trackOrderFragment); 
       fragmentTransaction.addToBackStack(null); 
       fragmentTransaction.commit(); 
      } 
     } 

您需要檢查是否正在接收每一個你的活動的onCreate運行,因爲可能會出現一個空指針異常時任臨時演員。

+0

如果您發現它有幫助,您可以將答案標記爲正確答案。謝謝。 –