您的位置:首页 > 移动开发 > Android开发

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

<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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: