I'm creating my first android app and I need to use a service. The UI will have a checkbox (CheckBoxPreference) that will be used to turn the service on/off and the service will only be accessed by my app (there's no need to share it).
So far the UI for this functionality is ready and I know how to respond to the event. What I don't know, how to create a service nor how to connect to it whatsoever?
The idea is that the service continues to listen for events and responding to them on the background and that the application is only to used to turn it on/off or to change some settings.
I've looked for tutorials on the web but I don't seem to get the process.
A service is a component that runs in the background to perform long-running operations without needing to interact with the user and it works even if application is destroyed.
Android service is a component that is used to perform operations on the background such as playing music, handle network transactions, interacting content providers etc. It doesn't has any UI (user interface). The service runs in the background indefinitely even if application is destroyed.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With