Search code examples
androidandroid-intentandroid-activityservice

Pass data from Activity to Service using an Intent


How do I get data within an Android Service that was passed from an invoking Activity?


Solution

  • First Context (can be Activity/Service etc)

    For Service, you need to override onStartCommand there you have direct access to intent:

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

    You have a few options:

    1) Use the Bundle from the Intent:

    Intent mIntent = new Intent(this, Example.class);
    Bundle extras = mIntent.getExtras();
    extras.putString(key, value);  
    

    2) Create a new Bundle

    Intent mIntent = new Intent(this, Example.class);
    Bundle mBundle = new Bundle();
    mBundle.extras.putString(key, value);
    mIntent.putExtras(mBundle);
    

    3) Use the putExtra() shortcut method of the Intent

    Intent mIntent = new Intent(this, Example.class);
    mIntent.putExtra(key, value);
    

    New Context (can be Activity/Service etc)

    Intent myIntent = getIntent(); // this getter is just for example purpose, can differ
    if (myIntent !=null && myIntent.getExtras()!=null)
         String value = myIntent.getExtras().getString(key);
    }
    

    NOTE: Bundles have "get" and "put" methods for all the primitive types, Parcelables, and Serializables. I just used Strings for demonstrational purposes.