Question

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 dunno is 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.

Was it helpful?

Solution

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();
    }
}

OTHER TIPS

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top