Android开发基础之服务Service

尽可能简单理解Android开发四大组件中的服务Service,用简单的例子和语言。

概念

长期在后台运行,与用户没有交互,比如音乐,可以在后台播放,同时可以去看书,浏览新闻等

配置 

由于Service也是四大组件之一,所以也需要在项目的配置文件当中去注册,具体是在AndroidManifest.xml文件当中添加语句如:

<service android:name="cn.uprogrammer.sensordatacollect.IPSService"></service>

运行服务

首先在app界面写两个按钮用于设置服务开启或停止

    <Button
        android:onClick="startServiceClick"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="开启服务"/>

    <Button
        android:onClick="stopServiceClick"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="停止服务"/>

接着,写开启和暂停服务的代码

    //开启服务
    public void startServiceClick(View view){
        Intent intent = new Intent();
        intent.setClass(this,IPSService.class);
        startService(intent);
    }

    //停止服务
    public void stopServiceClick(View view){
        Intent intent = new Intent();
        intent.setClass(this,IPSService.class);
        stopService(intent);
    }

猜你喜欢

转载自blog.csdn.net/danielxinhj/article/details/132559943