PendingIntent傳值接收時為null


時間:2016-4-20 11:01:20

描述:使用Notifaction時,使用到PendingIntent中使用intent傳值的問題,接收Activity接收時獲取到的內容為null。

解決:
    flags有四個取值:
    int FLAG_CANCEL_CURRENT:如果該PendingIntent已經存在,則在生成新的之前取消當前的。
    int FLAG_NO_CREATE:如果該PendingIntent不存在,直接返回null而不是創建一個PendingIntent。
    int FLAG_ONE_SHOT:該PendingIntent只能用一次,在send()方法執行后,自動取消。
    int FLAG_UPDATE_CURRENT:如果該PendingIntent已經存在,則用新傳入的Intent更新當前的數據。
    我們需要把最后一個參數改為PendingIntent.FLAG_UPDATE_CURRENT,這樣在啟動的Activity里就可以用接收Intent傳送數據     的方法正常接收。

發送方code:
    
  
  
  
          
  1. Intent intent = new Intent(context, XXActivity.class);
  2. intent.putExtra("recFile", recName);
  3. PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
  4. NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
  5. Notification.Builder builder = new Notification.Builder(context);
  6. builder.setTicker("新的通知");
  7. builder.setSmallIcon(R.drawable.ic_launcher);
  8. builder.setContentTitle("收到新的通知");
  9. builder.setContentText("您有一條新的通知");
  10. builder.setContentIntent(pendingIntent);
  11. Notification notification = builder.build();
  12. notification.flags = Notification.FLAG_AUTO_CANCEL;
  13. manager.notify(NOTIFACTION_FLAG_CODE, notification);

接收方code:
    
  
  
  
          
  1. String recFileName = getIntent().getStringExtra("recFile");
  2. if (recFileName != null) {
  3. //處理邏輯...
  4. }






免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM