Search code examples
androidandroid-intentservicebundle

Map inside Bundle in intent is null in onStartCommand in Service


I am trying to start Service by passing some data through following code:

Intent countDownTimerIntent = new Intent(getActivity(), CountDownTimerService.class);
        Bundle bundle = new Bundle();
        bundle.putLong(CountDownTimerService.DURATION, ((Test) mcqDataSet).getDuration());

        countDownTimerIntent.putExtras(bundle);
        getContext().startService(countDownTimerIntent );

Now when I am trying to receive the bundle data from Intent than it shows that some data is there in bundle but its map is null

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    Bundle bundle = intent.getExtras();
    if (bundle != null) {
        final long duration = bundle.getLong(DURATION, 0l);

Here is how bundle looks will debugging the debug mMap values here


Solution

  • After a lot of struggle, I found that return type in onStartCommand should be START_REDELIVER_INTENT. It is because many times the intent gets lost and undelivered. So this return type forces it to redeliver it as it needs to get the data. Code is a follows:

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
    
        Bundle bundle = intent.getExtras();
        if (bundle != null) 
            final long duration = bundle.getLong(DURATION, 0l);
    
        return START_REDELIVER_INTENT;
    }