KIO
Kreative Ideen online
Service

Service

You start a service from an activity in a smilar way to how you start an activity. You create an xpplicit intent that’s directed at the service you want to start, then use the startService() method in your activity to start it:

Intent intent = new Intent(this, DelayedMessageService.class;
startService(intent);

Full code for context:

package eu.kio.joke;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.content.Intent;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void onClick(View view) {
        Intent intent = new Intent(this, DelayedMessageService.class);
        intent.putExtra(DelayedMessageService.EXTRA_MESSAGE,getResources().getString(R.string.response));
        startService(intent);
    }
}

The service code:

package eu.kio.joke;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;


/**
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 * <p>
 * TODO: Customize class - update intent actions and extra parameters.
 */
public class DelayedMessageService extends IntentService {

    public static final String  EXTRA_MESSAGE = "message";

    public DelayedMessageService(){
        super("DelayedMessageService");
    }

    /*Put the code you want the service to run in the onHandleIntent() method*/
    @Override
    protected void onHandleIntent(Intent intent){
        synchronized(this){

            try {
                wait(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        String text = intent.getStringExtra(EXTRA_MESSAGE);
        showText(text);
    }

    private void showText(final String text){
        //This logs a piece of text so we can see it in the logcat through Android Studio
        Log.v("DelayedMessageService","The message is: "+text);
    }
}

When an application component(such as an activity) starts an service, the service moves from being created to running to being destroyed.

The service inherits lifecycle methods

It triggers key service lifecyle methods, which it inherits from android.app.IntentService class.

  • onCreate()
  • onStartCommand()
  • onDestroy()

Are the three of the main service lifecycle methods.

Leave a Reply

Your email address will not be published. Required fields are marked *