2017-08-31 79 views
1

我在某個點顯示通知,當點擊時會打開一個活動(活動A)。我試着用IntentFilter註冊一個接收器來監聽用戶點擊通知。我想要的是,當活動A已經存在時,避免系統再次啓動活動。可悲的是,接收器永遠不會被調用。RegisterReceiver來自通知的PendingIntent

這是啓動通知代碼:

//Create the BackStack for the back navigation when opening from intent 
TaskStackBuilder builder = TaskStackBuilder.create(this); 

//Create the intent to open this activity, allowing the implementing class add some parameters 
Intent thisClassIntent = new Intent(this, ActivityA.class); 
onPrepareIntent(thisClassIntent); 
thisClassIntent.setAction(ACTION_OPEN_CHAT); 

builder.addParentStack(this); 
builder.addNextIntent(thisClassIntent); 

PendingIntent pendingIntent = builder.getPendingIntent(0, 
PendingIntent.FLAG_UPDATE_CURRENT); 

Notification.Builder builder = new Notification.Builder(context).setContentTitle("some title") 
       .setContentText("some text") 
       .setSmallIcon(R.drawable.icon) 
       .setPriority(Notification.PRIORITY_MAX) 
       .setDefaults(Notification.DEFAULT_ALL) 
       .setAutoCancel(true) 
       .setContentIntent(pendingIntent); 

Notification notification = builder.build(); 
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 
     manager.notify(0, notification); 

在這個活動,我想監聽的意圖定義的操作:

public class ActivityA extends AppCompatActivity { 

private BroadcastReceiver mReceiver = new BroadcastReceiver() { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     //This should be called when the user taps in the notification 
    } 
}; 

@Override 
protected void onStart() { 
    super.onStart(); 
    registerReceiver(mReceiver, new IntentFilter(ACTION_OPEN_CHAT)); 
} 

... 
} 

將是巨大的,如果您有任何線索。 謝謝!

+0

你是否聲明瞭將在你的Android清單中激活你的廣播接收器的意圖? – Rafa

回答

0

TaskStackBuilder創建的PendingIntent用於Activity目標,而不是BroadcastReceiver目標。如果您想讓您的通知發送專門的廣播,您需要爲BroadcastReceiver創建自己的PendingIntent,並讓您的Activity爲其註冊一個接收器。