Service (Associate Android Developer Certification)

Service works in background, used for long time operations. It has 3 lifecycle methods: onCreate(), onStartCommand(), onDestroy();
In order to start and stop service: you can use startService() and stopService() methods. Or you can use startSelf() and stopSelf() methods inside service.
If you want to interact with service you can use bindService() and unbindService() methods. When you bindService(), if service is not running, it will start.
If you want to connect to service from another application, you can use following methods:

  • IBinder onBind(Intent intent)
  • onUnbind(Intent intent)
  • onRebind(Intent intent)
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return Service.START_STICKY;
}

START_NOT_STICKY – service won’t be restarted after stopped by system
START_STICKY – service will be restarted after stopped by system
START_REDLIVER_INTENT – service wil be restarted after stopped by system. receives all startService calls.

Example:

PlayService.java

public class PlayService extends Service
{
    MediaPlayer mPlayer;
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate()
    {
        Toast.makeText(this, "Служба создана",
            Toast.LENGTH_SHORT).show();
        mPlayer = MediaPlayer.create(this, R.raw.zara);
        mPlayer.setLooping(false);
    }

    @Override
    public void onStart(Intent intent, int startid)
    {
        Toast.makeText(this, "Служба запущена",
            Toast.LENGTH_SHORT).show();
        mPlayer.start();
    }
   
    @Override
    public void onDestroy()
    {
        Toast.makeText(this, "Служба остановлена",
            Toast.LENGTH_SHORT).show();
        mPlayer.stop();
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {

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

        final Button btnStart = (Button) findViewById(R.id.btn_start);
        final Button btnStop = (Button) findViewById(R.id.btn_stop);

        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startService(new Intent(MainActivity.this, PlayService.class));
            }
        });

        btnStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                stopService(new Intent(MainActivity.this, PlayService.class));
            }
        });
    }
}

AndroidManifest.xml

        <service
           android:enabled="true"
           android:name=".PlayService">
        </service>

How to start service on boot completed:

public class BootBroadcast extends BroadcastReceiver {
 
    @Override
    public void onReceive(Context context, Intent intent) {      
        context.startService(new Intent(context, TestService.class));
    }
}
<receiver android:name=".BootBroadcast">  
    <intent-filter >
        <action android:name="android.intent.action.BOOT_COMPLETED"/>              
    </intent-filter>
</receiver>

How to get list of running services?

ActivityManager am = (ActivityManager) this
        .getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> rs = am.getRunningServices(50);

for (int i = 0; i < rs.size(); i++) {
    ActivityManager.RunningServiceInfo rsi = rs.get(i);
    Log.i("Service", "Process " + rsi.process + " with component "
            + rsi.service.getClassName());
}

Source