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>
....
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With