Creating a Service in Android

半世苍凉 提交于 2019-12-18 04:04:07

问题


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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/4360074/creating-a-service-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!