2014-01-10 39 views
0

我有一個問題涉及在Android中通過附加操作創建通知。我的目標是要有一個不會重新打開我的應用程序的操作,但只需執行我的應用程序中類所指定的一些邏輯。這是我的代碼來創建所述通知。Android:通知,PendingIntent和操作

NotificationManager notificationManager = (NotificationManager)  context.getSystemService(Context.NOTIFICATION_SERVICE); 
Intent notificationIntent = new Intent(context, RetryReceiver.class); 
final PendingIntent retryIntent = PendingIntent.getBroadcast(context, notificationId, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); 

final NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(context) 
.setContentTitle(title) 
.setTicker(ticker) 
.setContentText(message) 
.setSmallIcon(R.drawable.notifcation_sprout_leaf) 
.setLargeIcon(largeIcon) 
.setAutoCancel(true); 

if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) { 
    mNotifyBuilder.addAction(R.drawable.refresh_action_bar, "Retry", retryIntent); 
} 

// Creates an explicit intent for an Activity in your app 
Intent mainIntent = new Intent(context, MainActivity.class); 

// The TaskStackBuilder needs multiple intents in case there are multiple failures in succession 
// Thus default it to have a MainActivity intent it can fall back on 
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context); 
stackBuilder.addNextIntent(mainIntent); 
stackBuilder.addNextIntent(composeIntent); 

PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(notificationId, PendingIntent.FLAG_UPDATE_CURRENT); 
mNotifyBuilder.setContentIntent(resultPendingIntent); 

// Because the ID remains unchanged, the existing notification is updated. 
notificationManager.notify(notificationId, mNotifyBuilder.build()); 

這裏是我的類接收廣播:

public class RetryReceiver extends BroadcastReceiver { 

@Override 
public void onReceive(Context context, Intent intent) { 
    final Bundle bundle = intent.getExtras(); 
      // do shit 
    } 
} 

我也註冊在AndroidManifest.xml接收這樣:

<receiver 
    android:name=".RetryReceiver" 
    android:enabled="true" 
    android:exported="true" > 
</receiver> 

出於某種原因,該代碼在我的接收器中永遠不會被解僱,任何人都有什麼建議?

+0

是RetryReceiver類文件Java或一個內部類? – ramaral

+0

這是一個類文件。 – robmadden

+0

我看到你的代碼沒有錯,當然,如果它運行在一個設備上,其中'Build.VERSION.SDK_INT> Build.VERSION_CODES.JELLY_BEAN' – ramaral

回答

1

您需要撥打setContentIntent(retryIntent)對您的mNotifyBuilder - 它不會自動設置。

+0

我試過這個,但什麼都沒有。 – robmadden

1

屬性android:exported="true"是讓廣播接收器從其應用之外的源接收消息。

沒有任何過濾器意味着它只能由Intent對象調用,這些對象指定了它的確切類名。這意味着接收器僅適用於內部使用的應用

因此android:exported應聲明爲android:exported="false"或未聲明,因爲它在這種情況下默認爲false。

因爲我看不出您的代碼沒有其他問題。請android:exported="false"

嘗試見Receiver Android documentation

+0

感謝您的輸入,我找到了它,結果我的設備出現故障。 – robmadden

+0

你能描述一下你的情況到底出錯了嗎?其他人可能會被重定向到同一問題的這個問題。 – Toverbal