0

創建通知:Android的通知的addAction不啓動廣播

PendingIntent pIntent = PendingIntent.getActivity(context, (int) taskId, intent, 0); 
intent.setAction(Utils.MARK_AS_DONE); 

PendingIntent pIntentMarkAsDone = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); 

NotificationCompat.Builder builder = new NotificationCompat.Builder(context) 
     .setTicker(ticker) 
     .setContentTitle(title) 
     .setContentText(description) 
     .setSmallIcon(getAlarmIcon(type)) 
     .setLargeIcon(BitmapFactory.decodeResource(context.getResources(),R.mipmap.ic_launcher)) 
     .setContentIntent(pIntent) 
     .addAction(0, context.getString(R.string.mark_as_done), pIntentMarkAsDone); 

Notification notification = builder.build(); 
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 
notificationManager.notify((int) taskId, notification); 

我添加使用帶getBroadcast掛起的意圖增加。

接收機:

public class NotificationReceiver extends BroadcastReceiver { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     // Log to check 
    } 
} 

此類應 「接收」 的動作。我還加上清單

清單:

<receiver android:name=".NotificationReceiver"> 
    <intent-filter> 
     <action android:name="<package_name>.MARK_AS_DONE"/> 
    </intent-filter> 
</receiver> 

好,的onReceive不接收。我究竟做錯了什麼?

回答

0

TL; DR:創建一個新的Intent,而不是重複使用中的一個,並從<receiver>中刪除<intent-filter>


你的第一行是:

PendingIntent pIntent = PendingIntent.getActivity(context, (int) taskId, intent, 0); 

這意味着intent確定了一些活動。如果您是通過new Intent(context, YourActivityClass.class)創建的,則它會在其中設置ComponentName,以確定您的活動。

然後,您撥打電話setAction()intent並與getBroadcast()一起使用。但是,除了設置(或替換)動作之外,intent中的所有其他內容與原來的相同。特別是,識別活動的ComponentName仍然存在。所以,當廣播被髮送時,Android無法傳送它,因爲組件是無效的(一個活動不能直接接收廣播),並且操作字符串被忽略(因爲在Intent上設置ComponentName一次,諸如動作和類別不再計算路由)。

因此,我建議您創建兩個Intent對象,一個用於活動,一個用於接收器。

請注意,您不需要接收方的操作字符串。您可以使用顯式的Intent構造函數(new Intent(context, NotificationReceiver.class))。事實上,在接收器上使用動作字符串對安全性不利,因爲現在任何應用都可以向您發送該廣播。因此,我建議刪除<intent-filter>並使用明確的Intent來創建您的廣播PendingIntent

+0

解決!謝謝! 問題確實如此:new Intent(context,NotificationReceiver.class) –