• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps startService with objectdata as parameter

Hello,

I wanna start a Service and need some Objects in my Service to work with them.

I would like to have an custom constructor like this:
Code:
public MyService(Context context, Button button, Cursor cursor)

But the common way to start a Service is like that:
Code:
intent.setClass(this, MyService.class);
startService(intent);
In an Intent I can only put Data like Strings.

How I can start a Service with some Objects as parameters?
 
Make your object implement the Parcelable interface, then do the following:
Code:
Bundle bundle = new Bundle();
bundle.putParcelable(keyName, myObjectInstance);
Intent intent = new Intent(this, MyService.class);
intent.putBundle(bundle);
startActivity(intent);
 
More of a basic solution may work as well:

Code:
Intent intent = new Intent(getApplicationContext(),ServiceExample.class); 
		intent.putExtra("passedVariable", true);
		startService(intent);
		finish();

then to get that extra in the service:

Code:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
		
   if (intent != null) {
      if (intent.getBooleanExtra("passedVariable", false)) {
         ....
      } else {
         ....
      }
   }

}
 
Back
Top Bottom