Skip to content

Instantly share code, notes, and snippets.

@vijaybheda
Created February 21, 2021 12:53
Show Gist options
  • Select an option

  • Save vijaybheda/d2cc238e501acef5d7fa41b2ab6907df to your computer and use it in GitHub Desktop.

Select an option

Save vijaybheda/d2cc238e501acef5d7fa41b2ab6907df to your computer and use it in GitHub Desktop.
Android Start/Stop Service from Activity Example using HandlerThread
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
OnClickListener listener = new OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, MyService.class);
switch (view.getId()) {
case R.id.service_start:
//starts service for the given Intent
startService(intent);
break;
case R.id.service_stop:
//stops service for the given Intent
stopService(intent);
break;
}
}
};
findViewById(R.id.service_start).setOnClickListener(listener);
findViewById(R.id.service_stop).setOnClickListener(listener);
}
}
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service {
private static final String TAG = "MyService";
private boolean isRunning = false;
private Looper looper;
private MyServiceHandler myServiceHandler;
@Override
public void onCreate() {
HandlerThread handlerthread = new HandlerThread("MyThread", Process.THREAD_PRIORITY_BACKGROUND);
handlerthread.start();
looper = handlerthread.getLooper();
myServiceHandler = new MyServiceHandler(looper);
isRunning = true;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Message msg = myServiceHandler.obtainMessage();
msg.arg1 = startId;
myServiceHandler.sendMessage(msg);
Toast.makeText(this, "MyService Started.", Toast.LENGTH_SHORT).show();
//If service is killed while starting, it restarts.
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
isRunning = false;
Toast.makeText(this, "MyService Completed or Stopped.", Toast.LENGTH_SHORT).show();
}
private final class MyServiceHandler extends Handler {
public MyServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
synchronized (this) {
for (int i = 0; i < 10; i++) {
try {
Log.i(TAG, "MyService running...");
Thread.sleep(1000);
} catch (Exception e) {
Log.i(TAG, e.getMessage());
}
if(!isRunning){
break;
}
}
}
//stops the service for the start id.
stopSelfResult(msg.arg1);
}
}
}
@vijaybheda

Copy link
Copy Markdown
Author

Find some constants which are returned from onStartCommand(Intent, int, int).
START_STICKY : It starts the onStartCommand if killed while stating.
START_NOT_STICKY : If service is killed while starting, it does not restart until explicitly service is started.
START_REDELIVER_INTENT : If service is killed while starting, it will schedule to restart with the latest intent.

android.app.Service runs the long-running process in the background. Service does not interact with the user. It will run in the background even if the user switches to another application. While using Service we need to override methods. Some of them are as follows.
onCreate() : System calls it when service is first created. We can use it to initialize values for the process.
onStartCommand(Intent intent, int flags, int startId) : System calls it when service is started explicitly. For every service start call, it is called.
onBind(Intent): It is used for inter-process communication(IPC). It returns null if clients can not bind to the service.
onDestroy(): System calls it when service is completed or stopped. We can use it for resource cleanup purposes.

Service can stop itself by calling methods as follows.
stopSelf(): On calling it, Service is stopped if it is running.
stopSelfResult(int startId): Stops the service for the most recent start id.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment