2016-08-04 4 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

あなたのServiceBroadcastを指定して、通知に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として:あなたはあなたのService(おそらくonStartCommand()を中)で、このreceiverを登録

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

のみを使用:

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

Serviceが動作している必要があります。

関連する問題