前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Android开发基础之服务Service

Android开发基础之服务Service

作者头像
丹牛Daniel
发布2023-10-17 15:51:58
780
发布2023-10-17 15:51:58
举报

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

概念

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

配置 

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

代码语言:javascript
复制
<service android:name="cn.uprogrammer.sensordatacollect.IPSService"></service>

运行服务

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

代码语言:javascript
复制
    <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="停止服务"/>

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

代码语言:javascript
复制
    //开启服务
    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);
    }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2023-10-11,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 概念
  • 配置 
  • 运行服务
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档