Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android- How to send data from activity to service?

In my application I'm trying to send data from my MainActivity.class to a service called bgservice.class. This is my following code:

MainActivity.class:

public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  Intent serviceIntent = new Intent(bgservice.class.getName());
  serviceIntent.putExtra("UserID", "123456");
  this.startService(serviceIntent);
}

bgservice.class:

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

  String userID = intent.getStringExtra("userID");
  System.out.println(userID);
  Toast.makeText(this,userID, Toast.LENGTH_LONG).show();
  return START_STICKY;

}

but I'm not getting the data in the service class. these are the following error I get:

02-25 09:05:41.166: E/AndroidRuntime(2633):

java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.microapple.googleplace/com.microapple.googleplace. MainActivity}: java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { act=com.microapple.googleplace.bgservice (has extras) }

AndroidManifest.xml:

     ...
    <application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >



        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <service android:enabled="true" android:name=".bgservice" />
</application>
....
like image 703
Bala u1 Avatar asked Feb 25 '15 03:02

Bala u1


People also ask

How pass data from activity to running service?

You can send data to a running Service by calling startService() with an Intent . In the Service , onStartCommand() will be called on your running service. This is certainly the easiest method, although there are plenty of others.

How do you communicate between service and activity?

We know how much service are important in Android Application Development. We already know that we can communicate with Service from activity just by using method startService() and passing Intent to the argument in the method, or either we can use bindService() to bind the service to the activity with argument Intent.


1 Answers

Intent serviceIntent = new Intent(YourActivity.this, bgservice.class);
        serviceIntent.putExtra("UserID", "123456");
        this.startService(serviceIntent);

And in your service,

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

    String userID = intent.getStringExtra("UserID");

    //do something

    return START_STICKY;

}

This must work.

like image 90
Apurva Avatar answered Sep 28 '22 00:09

Apurva