android-service的简单用法
2015-06-30 10:34
561 查看
service是android开发中的四大组件之一,下面来介绍service的简单用法
1.需要新建一个service类,该类继承与service接口,需要实现onBind方法,这个方法之后介绍
2.创建intent对象,设置intent的目标为新建的service的类,启动service的方法有两种用startservice方法和bindservice方法
两种方法的不同在于startservice在启动服务之后,关闭当前的activity之后service还在系统后台运行
bindservice启动服务后将服务与主界面绑定,主界面关闭之后service也就结束了
3.主界面与service的信息交互需要用到aidl,需要在项目src下新建aidl包,并新建接口,会自动在gen目录下生成对应的java文件,这些东西都是不用进行修改的.
另外,一定记得在androiManifest中注册service
activity_main
1.需要新建一个service类,该类继承与service接口,需要实现onBind方法,这个方法之后介绍
2.创建intent对象,设置intent的目标为新建的service的类,启动service的方法有两种用startservice方法和bindservice方法
两种方法的不同在于startservice在启动服务之后,关闭当前的activity之后service还在系统后台运行
bindservice启动服务后将服务与主界面绑定,主界面关闭之后service也就结束了
3.主界面与service的信息交互需要用到aidl,需要在项目src下新建aidl包,并新建接口,会自动在gen目录下生成对应的java文件,这些东西都是不用进行修改的.
另外,一定记得在androiManifest中注册service
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffffff" android:orientation="vertical" android:padding="20dp" > <TextView android:id="@+id/tv" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Test" android:textColor="#000000" android:textSize="24sp" /> <Button android:id="@+id/btn01" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Start Service" /> <Button android:id="@+id/btn02" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Stop Service" /> <Button android:id="@+id/btn03" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="bind Service" /> <Button android:id="@+id/btn04" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="unbind Service" /> <Button android:id="@+id/btn05" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="work" /> </LinearLayout>
activity_main
相关文章推荐
- android studio 开发 gradle 详解(五)
- android-percent-support-lib-sample
- 百度经验:常用的Android.mk变量解释
- Android系统版本与API Level对照表
- Android中动态生成ListView及SimpleAdapter的使用
- Android studio ElasticDownloadView
- android 适配器的使用
- 完整的Android源码截屏事件的捕获--5.0
- android 中 EditText加入图标 更改边框颜色 设置透明
- android 自定义适配器BaseAdapter
- Android Drawable
- Android下拉列表Spinner
- Android开发中Fragment的使用
- PHP后台1:客户端(IOS/Android)GET请求PHP后台
- android 真机调试步骤
- Android中的adapter分析
- Android.mk
- android 横竖屏切换
- Android Studio常用快捷键
- android 包的获取方式