Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Service in Android

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.

like image 846
PedroC88 Avatar asked Dec 05 '10 17:12

PedroC88


People also ask

What is a service in Android?

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.

What is service explain with example in Android?

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.


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();
    }
}
like image 114
whirlwin Avatar answered Oct 07 '22 13:10

whirlwin


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);
like image 22
Yster Avatar answered Oct 07 '22 12:10

Yster