2016-05-20 5 views
1

同じサービスクラス内でPendingIntentを受信したいとします。 私はonReceiveメソッドでログを追加しましたが、LogCatには決して表示されません。PendingIntentを送信した後にonReceive()が呼び出されない

AndroidManifest:

<service android:name=".UpdateService" android:exported="true"> 
    <intent-filter> 
    <action android:name="monitoringStop" /> 
    </intent-filter> 
</service>` 

UpdateService:

public class UpdateService extends Service { 
    public static final String BROADCAST_NAME = "monitoringStop"; 
    private BroadcastReceiver receiver = new BroadcastReceiver() { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     //Never reached 
    } 
}; 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
    //registering   
    IntentFilter filter = new IntentFilter(); 
    filter.addAction(UpdateService.BROADCAST_NAME); 
    registerReceiver(receiver, filter); 

    //creating Intent + PendingIntent 
    Intent stopIntent = new Intent(this, UpdateService.class); 
    stopIntent.setAction(BROADCAST_NAME); 
    PendingIntent pendingIntent = 
     PendingIntent.getBroadcast(this, 1, stopIntent, PendingIntent.FLAG_ONE_SHOT); 

    //adding PendingIntent to action 
    NotificationCompat.Action stopService 
     = new NotificationCompat.Action(R.drawable.stop, getString(R.string.stop), pendingIntent); 

    NotificationCompat.Builder notificationBuilder 
     = new NotificationCompat.Builder(this)//settingText etc. 
      .addAction(stopService); 

    startForeground(1,notificationBuilder.build()); 
    return Service.START_STICKY; 
    } 
} 
+0

ここでブロードキャストを送信しますか?投稿コー​​ド – John

+0

最後の3行目: '.addAction(stopService);' [link](https://developer.android.com/reference/android/app/Notification .Builder.html#addAction(android.app.Notification.Action)) –

答えて

1

あなたはstopIntent.setAction代わりのintent.setActionを呼び出す必要があります。

サービス内にブロードキャスト受信機は必要ありません。 PedingIntent.getServiceを呼び出すだけで、onStartCommandメソッドが呼び出されます。この方法の中では、意図に反応することができます。

+0

ありがとうございます。すべてが今働きます。 onReceiveメソッドはもう必要ではありません。 –

関連する問題