2016-05-20 75 views
1

我想要在同一個Service類中接收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

在第三行:'.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方法不再需要。 –

相關問題