1

我想要點擊通知動作按鈕時執行一些方法。 我在這個網站上搜索過,但一切似乎都是按順序的,我的IntentService沒有被調用。IntentService onHandleEvent()not starting

我的動作,按鍵意圖

Intent off = new Intent(); 
    off.setAction("action"); 
    off.putExtra("test", "off"); 
    PendingIntent pOff = PendingIntent.getService(context, 22, off, 0); 

通知生成器

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context) 
      .setSmallIcon(/**/) 
      .setContentTitle(/**/) 
      .setContentText(/**/) 
      .addAction(/**/, "Off", pOff) 
      .setContentIntent(pendingIntent) 
      .setDefaults(Notification.DEFAULT_SOUND) 
      .setAutoCancel(true); 

意向服務類

public class NotificationServiceClass extends IntentService { 

public NotificationServiceClass(String name) { 
    super(name); 
} 

public NotificationServiceClass() { 
    super("NotificationServiceClass"); 
} 

@Override 
protected void onHandleIntent(Intent intent) { 
    Log.i("test", "onHandle"); 
    if (intent.getAction().equals("action")) { 
     Log.i("test", "action"); 
     Bundle bundle = intent.getExtras(); 
     if (bundle != null) { 
      Log.i("test", "onHandleBundleNotNull"); 
      if (bundle.containsKey("test")) { 
       Log.i("test", bundle.getString("test")); 
      } 
     } 
    } 
} 
} 

XML的服務類

<service 
     android:name=".Manager.NotificationServiceClass" 
     android:exported="false"> 
    </service> 
01宣言

回答

2

Intents and Intent Filters training,你已經建立的意圖是一個隱含的意圖:

隱式意圖不命名一個特定組成部分,而是宣佈執行一般的動作,這使得組件從另一個應用處理它。例如,如果要向用戶顯示地圖上的某個位置,則可以使用隱式意圖來請求另一個功能強大的應用程序在地圖上顯示指定的位置。

你真正需要的是一個明確的意圖:一個指定的組件按名稱按音符開始在同一頁上:

注:當啓動一個服務,你應該總是指定組件名稱。否則,您無法確定哪些服務會響應該意圖,並且用戶無法看到哪個服務啓動。

在構建你的意圖,你應該使用

// Note how you explicitly name the class to use 
Intent off = new Intent(context, NotificationServiceClass.class); 
off.setAction("action"); 
off.putExtra("test", "off"); 
PendingIntent pOff = PendingIntent.getService(context, 22, off, 0); 
+0

這是一個非常愚蠢的錯誤。 謝謝你指出。 –

0

在看你的代碼,我沒有看到你說的是什麼樣的PendingIntent類使用的爲您服務。

您應該添加:

off.setClass(this, NotificationServiceClass.class); 

否則的PendingIntent無關。