2016-08-04 60 views
0

我有一個通知,我正在通過服務呼叫。我想在通知點擊時再次致電該服務。但通知點擊無法進入該方法。在點擊通知後調用服務方法

Intent intent = new Intent(this, MyService.class).setAction(ACTION_1); 
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0,intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT); 

    NotificationCompat.Builder mBuilder = 
      new NotificationCompat.Builder(this) 
        .setSmallIcon(R.drawable.food) 
        .setContentTitle("notification") 
        .setContentText("near by you!"); 
    NotificationManager mNotificationManager =(NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE); 

的方法,我想打電話給是

if (ACTION_1.equals(resultPendingIntent)) { 
     getRecommendation(); 
    } 
     mBuilder.setContentIntent(resultPendingIntent); 
    mNotificationManager.notify(id, mBuilder.build()); 

我曾嘗試以下鏈接,但沒能解決我的問題。 How to execute a method by clicking a notification

回答

1

您可以在Service中指定Broadcast,然後在您的通知中通過PendingIntent啓動它。

Intent stopIntent = new Intent("my.awersome.string.name"); 
PendingIntent stopPi = PendingIntent.getBroadcast(this, 4, stopIntent, PendingIntent.FLAG_CANCEL_CURRENT); 

然後,在您的通知建設者:

NotificationCompat.Builder builder; 
builder = new NotificationCompat.Builder(context) 
    ...  
    .setContentIntent(stopPi); 

在你Service你可以設置一個BroadcastReceiver爲:

private final BroadcastReceiver myReceiver = new BroadcastReceiver() { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     // Code to run 
    } 
}; 

您註冊此receiverService(可能在onStartCommand())僅使用:

registerReceiver(myReceiver, new IntentFilter("my.awersome.string.name")); 

您的Service必須運行此工作。

相關問題