CompEng
CompEng

Reputation: 7376

Is it wrong to use , startservice every on create meythod on my app?

I have a service in my app. And I use startservice method on oncreate method so it works every running of my app , is it wrong way to do it? if it is how can I manage it? should I control it and if it is not start then I start the service ? this is the right way?

thanks in advance

Upvotes: 0

Views: 65

Answers (3)

Warwicky
Warwicky

Reputation: 281

If you want a service that should run in background all the time.

There are a few things you can do.

First lets start with an utility method which checks if server is running. Although it is considered as antipattern to use singleton, it is working good for this case

public static void startYourServiceIfNotRunning(Context context) {
    if(YourService.getRunningInstance() == null)
        context.startService(new Intent(context, YourService.class));
}

Also you should define your service as sticky inside your service class

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // We want this service to continue running until it is explicitly
    // stopped, so return sticky.
    return START_STICKY;
}

And also you can define a broadcast reciever like

public class BootCompletedReceiver extends BroadcastReceiver {
  @Override
  public void onReceive(Context context, Intent arg1) {
    Util.startYourServiceIfNotRunning(context);
}

}

And xml code for the reciever, add to your manifest

 <receiver android:name="com.yourapp.BootCompletedReceiver" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" >
            </action>
            <category android:name="android.intent.category.HOME" >
            </category>
        </intent-filter>
    </receiver>

And as the last thing, I call startYourServiceIfNotRunning() method in my main launcher activity. I do not call it anywhere else. And service is up all the time.

Hope this helps.

Hadi kolay gelsin :)

Upvotes: 1

Ashish Tamrakar
Ashish Tamrakar

Reputation: 119

You can have a look to the life cycle of service - http://developer.android.com/reference/android/app/Service.html#ProcessLifecycle

I would suggest to use IntentService, as it is designed for handling asyncron tasks, it also start in a worker thread.

http://developer.android.com/reference/android/app/IntentService.html

To really make this useful you have to define it in proper way.

Upvotes: 0

Carsten
Carsten

Reputation: 806

Have you already looked at http://developer.android.com/guide/components/services.html ? If you need a service that is running in the background then yes, startService is the correct way. You don't control it but the service manages itself so if it is not needed anymore it should stop itself. If you just need the service on demand then another way is to bind and unbind to the service then it is controlled by the system. It really depends on your use case.

Upvotes: 0

Related Questions