Creating a service on Android

I am creating my first Android application and I need to use the service. The user interface will have a checkbox (CheckBoxPreference) that will be used to enable / disable the service, and access to the service will be available only to my application (there is no need to share it).

So far, the user interface for this function is ready, and I know how to respond to the event, that I do not know how to create a service and how to connect to it at all.

The idea is that the service continues to listen to events and respond to them in the background, and that the application is used only to turn on / off or to change some parameters.

I searched for tutorials on the Internet, but I don't seem to get this process.

+6
android android-service
source share
2 answers
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(); } } 
+10
source share

In Android Studio, right-click the package, then select Create | Service | Service. Now add this method:

 @Override int onStartCommand(Intent intent, int flags, int startId) { // Your code here... } 

Note : onStart is deprecated.

To start the service: from the onCreate method (or the onReceive broadcast receiver):

 Intent i = new Intent(context, MyService.class); context.startService(i); 
+1
source share

All Articles