Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: start service with parameter

Tags:

To start my service from an Activiy I use startService(MyService.class). This works great, but in a special case the service should be started differently. I want to pass some parameters to the service start.

I tried the following in my Activity:

Intent startMyService= new Intent(); startMyService.setClass(this,LocalService.class); startMyService.setAction("controller"); startMyService.putExtra(Constants.START_SERVICE_CASE2, true);  startService(startMyService); 

In my Service I use:

public class MyIntentReceiver extends BroadcastReceiver {  @Override public void onReceive(Context context, Intent intent) {          if (intent.getAction().equals("controller"))          {                 // Intent was received                                        }      } }  

The IntentReceiver is registered in onCreate() like this:

IntentFilter mControllerIntent = new IntentFilter("controller"); MyIntentReceiver mIntentReceiver= new MyIntentReceiver(); registerReceiver(mIntentReceiver, mControllerIntent); 

With this solution the service starts but the intent is not received. How can I start a Service and pass my parameters?

Thanks for your help!

like image 994
Mike Avatar asked Mar 14 '11 17:03

Mike


People also ask

What is start sticky?

START_STICKY - If service is started with START_STICKY return type, it going to work in back ground even if activity is not foreground if android forcefully closed service due to memory problem or some other cases, it will restart service without interaction of the user.


1 Answers

Intent serviceIntent = new Intent(this,ListenLocationService.class);  serviceIntent.putExtra("From", "Main"); startService(serviceIntent); //and get the parameter in onStart method of your service class  @Override public void onStart(Intent intent, int startId) {     super.onStart(intent, startId);     Bundle extras = intent.getExtras();      if(extras == null) {         Log.d("Service","null");     } else {         Log.d("Service","not null");         String from = (String) extras.get("From");         if(from.equalsIgnoreCase("Main"))             StartListenLocation();     } } 
like image 57
Deepak Sharma Avatar answered Sep 21 '22 15:09

Deepak Sharma