SBotirov
SBotirov

Reputation: 14158

Android: How to user service with right way?

I have a service, when activity started I do bind to service with following way:

bindService(new Intent(BaseActivity.this, MyService.class), mConnection, Context.BIND_AUTO_CREATE);

this way correct?

I need service will start when application started and live in background mode always. If user manually stopped application in settings then when application started again service need start, too.

And I need don't create service if it is already exists(already running in background mode). Have a right way bind to existing service?

Anybody know how to can I do this with right way?

Thanks in advance!

Upvotes: 0

Views: 247

Answers (1)

kalyan pvs
kalyan pvs

Reputation: 14590

1.Just Start a Unbounded Service like

startService(new Intent(BaseActivity.this, MyService.class));

2.And For Automatic restart of your Service when killed by OS

in your onStartCommand() return START_STICKY

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_STICKY;
}

3.And For setting Button stop

in your onDestroy() of Service again start the Service like

    @Override
public void onDestroy() {
        // starting the service when the service is destroyed.
        Intent intent = new Intent(this, YourService.class);
        startService(intent);
        super.onDestroy();

};

NOTE:Service will stopped if you FORCE_STOP your app in Settings

Upvotes: 2

Related Questions