1

我有一個Android Service,它創建一個通知和相應的狀態圖標。當用戶對通知作出反應時,我希望將其交付給我的Service。這一切似乎很簡單。狀態通知與Android服務通話

我可以創建通知,圖標出現在狀態欄中,當我拉下窗戶時,我看到我的通知。當我點擊通知時,沒有任何反應。當我什麼也不說,我的意思是這個意圖沒有交付給我的服務。

我感覺到的是,我在Notification,Intent或PendingIntent中錯誤地設置了某些內容,但我正在努力弄清楚哪個(哪些)是不正確的。

下面的代碼(全部在服務類):

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    Log.d(TAG, "onStartCommand(): intent=" + intent + ", startId=" + startId); 
    Log.d(TAG, LKServiceMessages.dumpExtras(intent)); 

    String command = LKServiceMessages.getMessageKind(intent); 


    if (command.equals(K_STATUS_NOTIFICATION)) { 
     cancelNotification(0); 
     command = null; 
    } else { 
     displayStatusNotification(); 
    } 

    if (command == null) { 
     Log.d(TAG, "Non-library command received - ignoring..."); 
    } else { 
     Log.d(TAG, "Handling action - partially processing this action"); 
    } 

    return START_REDELIVER_INTENT; 
} 

private void displayStatusNotification() { 
    Intent intent = new Intent(K_STATUS_NOTIFICATION,null,this,LKService.class); 

    PendingIntent pIntent = PendingIntent.getService(LKService.this, 0, intent, 0); 

    mNotification = new NotificationCompat.Builder(this) 
     .setContentTitle("Bacon") 
     .setContentText("Bacon is good for you. Tap to dismiss.") 
     .setSmallIcon(R.drawable.ic_status) 

     .addAction(R.drawable.ic_status, "Notification getAction()", pIntent) 

     .setAutoCancel(true) 
     .setDeleteIntent(pIntent) 

     .build(); 

    NotificationManager notificationManager = 
      (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
    notificationManager.notify(0, mLeafNotification); 
} 

private void cancelNotification(int notificationId) { 
    if (Context.NOTIFICATION_SERVICE != null) { 
     String ns = Context.NOTIFICATION_SERVICE; 
     NotificationManager nMgr = (NotificationManager) getApplicationContext().getSystemService(ns); 
     nMgr.cancel(notificationId); 
    } 
} 

我做錯了什麼,但我想不出什麼。我最初的想法是,PendingIntent是錯誤的,但這裏有很多移動部分,我不完全理解。

有什麼想法?

回答

1

當建立通知,您呼叫

.setDeleteIntent(pIntent) 

這臺Intent當用戶刪除通知將被使用。這聽起來像你想打電話

.setContentIntent(pIntent) 

改爲。這設置了當用戶點擊通知時將使用的Intent

+0

謝謝。就是這樣。現在我的意圖就像我期待的那樣到達onStartCommand()。 –