2016-03-09 40 views
0

在我的IntentService類中,我創建了通知並分配ID = 1213,並且一旦應用程序打開,通知就會顯示出來。Android我的BroadcastReceiver類沒有收到通知發送的動作

Intent cancelScan = new Intent(); 
    cancelScan.setAction(CANCEL); 
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1213, cancelScan, PendingIntent.FLAG_UPDATE_CURRENT); 
    mNbuilder.addAction(android.R.drawable.ic_menu_close_clear_cancel,"Cancel Scanning",pendingIntent); 

    NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); 
    manager.notify(NOTIFICATION_ID, mNbuilder.build()); 
在我的廣播接收器類

if(CANCEL.equals(intent.getAction())){ 
     Log.i(TAG,"Received Broadcasr Receiver"); 
     NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); 
     //context.stopService(new Intent(context,ScanService.class)); 
     nm.cancel(NOTIFICATION_ID); 
    } 
} 

和我的manifest.xml

<receiver android:name=".WifiScanReceiver" android:enabled="true"> 
     <intent-filter> 
      <action android:name="CANCEL"/> 
     </intent-filter> 
    </receiver> 

我試過幾次,當我點擊下方的通知的動作按鈕,但沒有logcat中不打印任何東西。我做錯了哪些部分?預先感謝。

+0

這行中'CANCEL'的值是什麼:'cancelScan.setAction(CANCEL)' – 0xDEADC0DE

+0

private final String CANCEL =「CANCEL」,變量和值全部使用相同的名字。感謝您的回覆:) – noleavename

+0

您是否確定您的'BroadcastReceiver'中的'CANCEL'的值是否相同? – 0xDEADC0DE

回答

0

清單中的值和聲明爲action(「CANCEL」)的值必須相等,否則將無法工作。你的不要,這就是爲什麼你沒有達到你的陳述。雖然您的接收器被觸發,因爲您使用正確的操作發送廣播。

要確保你在代碼中使用正確的價值觀,你可以聲明static final您WifiScanReceiver

public class WifiScanReceiver { 
    public static final String CANCEL = "CANCEL"; 
    ... 
} 

所以,你也可以用它在你的代碼,當你發送廣播:

Intent cancelScan = new Intent(); 
cancelScan.setAction(WifiScanReceiver.CANCEL); 

這樣你總是確定你使用相同的值。唯一一個你必須確定的也是正確的,就是你清單中的那個。

+0

非常感謝,因爲我在這裏參考[鏈接](http://stackoverflow.com/questions/15350998/determine-addaction-click-for-android-notifications) – noleavename