Creating a Service in Android
CheckBox checkBox =
(CheckBox) findViewById(R.id.check_box);
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
startService(new Intent(this, TheService.class));
}
}
});
And the service:
public class TheService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "Service created!", Toast.LENGTH_LONG).show();
}
@Override
public void onDestroy() {
Toast.makeText(this, "Service stopped", Toast.LENGTH_LONG).show();
}
@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "Service started by user.", Toast.LENGTH_LONG).show();
}
}
In Android Studio, right-click package, then choose New | Service | Service. Now add this method:
@Override
int onStartCommand(Intent intent, int flags, int startId) {
// Your code here...
return super.onStartCommand(intent, flags, startId);
}
Note: onStart is deprecated.
To start the service: From an activity's onCreate method (or a broadcast receiver's onReceive method):
Intent i = new Intent(context, MyService.class);
context.startService(i);