Android Service

Service is one of the building blocks in Android.

  • A simple service is referred as unbound service or started service.
  • Service doesn’t have an UI but it is running on the UI thread.
  • Service is started by calling startService.
  • Service needs to be stopped manually by calling stopService.
  • etc.

Here are steps to create a simple service in Android.

1. Create a class extends from the Service class, SimpleService.java

public class SimpleService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("SimpleService", "SimpleService destroyed!");
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show();
    }
}

2. Register it in the manifest.xml file inside the application tag.


3. Start and stop it like the following assume these two method responds to a button click from a layout file.

public void startService(View view) {
    startService(new Intent(getBaseContext(), SimpleService.class));
}

public void stopService(View view) {
    stopService(new Intent(getBaseContext(), SimpleService.class));
}

Search within Codexpedia

Custom Search

Search the entire web

Custom Search