I have an application with a Service registered in the AndroidManifest to start up at boot time. I do this via an Intent Receiver for BOOT_COMPLETED, and this works fine. However, if the user is starting the app right after installation, I’d like to start off the Service from my main Activity since it may not be running.
I’m not sure of the best way to do this. I know I can call startService() from the activity, and that works, but then I can have multiple instances of the service running. I don’t want to stop the service first, becusae if it’s running, I just want that instance to keep running. The service could be in the middle of a task and I don’t want it to stop.
In Activity:
Intent serviceIntent = new Intent();
serviceIntent.setAction(MessageReceiverService.ClassName);
startService(serviceIntent);
Android Manifest registeing intent:
<receiver android:name="com.app.proto1.service.StartupIntentReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>
My Service overload methods:
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.d(Tag, "onCreate()");
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(Tag, "onDestroy()");
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.d(Tag, "onStart()");
this.registerReceiver(new SmsReceiver(), new IntentFilter(SMS_ACTION));
}
Is there a way I can check if the service is already running and not start it again, and without destroying the existing one?
Well if your Service is already running and you try to start service again, there will be no new instance created for the Service it will consider the previous running instance only. So, there is nothing to worry in that case. If you call the Service while its running its
onStartCommand(Intent, int, int)will be called and notonCreate().