尽可能简单理解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);
}
本文详细介绍了Android开发中Service组件的概念,如何在AndroidManifest.xml中配置,以及通过按钮控制Service的启动和停止。实例演示了在界面中使用按钮操作Service的开启和暂停功能。
7783

被折叠的 条评论
为什么被折叠?



