创建于Android的服务 [英] Creating a Service in Android

查看:105
本文介绍了创建于Android的服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要创建我的第一个Android应用程序,我需要使用服务。该UI将有一个复选框(复选框preference)将用于打开服务开/关和服务将只能通过我的应用程序来访问(有没有需要共享它)。

目前此功能的用户界面已准备就绪,我知道如何响应该事件,有什么我不知道的是如何创建一个服务,也没有如何连接到它任何责任。

的想法是,在服务继续监听事件并响应它们的背景和该应用程序是唯一的,以用于将其打开/关闭或改变一些设置。

我看了在网络上的教程,但我似乎并没有得到处理。


解决方案

 复选框复选框=
    (复选框)findViewById(R.id.check_box);
checkBox.setOnCheckedChangeListener(新OnCheckedChangeListener(){    公共无效onCheckedChanged(CompoundButton buttonView,布尔器isChecked){
        如果(器isChecked){
            startService(新意图(这一点,TheService.class));
        }
    }
});

和服务:

 公共类TheService延伸服务{    @覆盖
    公众的IBinder onBind(意向意图){
        返回null;
    }    @覆盖
    公共无效的onCreate(){
        Toast.makeText(这一点,服务创造!,Toast.LENGTH_LONG).show();
    }    @覆盖
    公共无效的onDestroy(){
        Toast.makeText(这一点,服务已停止,Toast.LENGTH_LONG).show();
    }    @覆盖
    公共无效调用onStart(意向意图,诠释startid){
        Toast.makeText(这一点,服务启动用户,Toast.LENGTH_LONG).show();
    }
}

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.

解决方案

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

这篇关于创建于Android的服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆