2013-10-15 45 views
1

我發現下面的代碼是多餘的。我在這裏錯過了什麼基礎?有沒有辦法在這裏減少重複的代碼。我可以使用Intent或PendingIntent對象,爲什麼呢?PendingIntent和通知目的

Intent updateUI = new Intent(SENDTOBACKGROUND_SERVICE); 
    updateUI.putExtra("Signal", God.YELLOW); 
    sendBroadcast(updateUI); 

    Intent sendNotification = new Intent(DriverService.this, DriverHome.class); 
    sendNotification.putExtra("Signal", God.YELLOW); 

    PendingIntent pIntent = PendingIntent.getActivity(getApplicationContext(), 0, sendNotification, PendingIntent.FLAG_UPDATE_CURRENT); 

    Notification n = new NotificationCompat.Builder(DriverService.this) 
      .setContentTitle("Attempting to update location") 
      .setContentText("Cab @(last) " + currentLocationInText) 
      .setSmallIcon(R.drawable.yellow).setContentIntent(pIntent).setAutoCancel(true) 
      .build(); 

    ((NotificationManager) DriverService.this.getSystemService(NOTIFICATION_SERVICE)).notify("Taxeeta", R.id.cabLocation, n); 
+1

PendingIntent使您能夠在另一個可能缺少此類權限的應用中使用您的權限運行代碼。 – Kuffs

回答

1

不,你需要兩者。 A PendingIntent是圍繞Intent的包裝。如果沒有Intent包裝,則不能有PendingIntent。並且您不能將Intent置於Notification中。當您想將Intent移交給另一個組件時,您需要使用PendingIntent,以便其他組件可以在將來的某個時刻爲您發送Intent(作爲一種「代理」)。

1

如DOC

http://developer.android.com/reference/android/app/PendingIntent.html#getActivity%28android.content.Context,%20int,%20android.content.Intent,%20int%29

解釋 「檢索的PendingIntent,將開始一個新的活動,比如調用Context.startActivity(意圖)」,所以你需要的PendingIntent和意圖。

+1

作爲一個很好的答案表示感謝,我還+1你的另一個答案。自從他回答之前,我接受了大衛的回答。 – taxeeta

相關問題