当前位置:文档之家› Android 开发 Service讲解

Android 开发 Service讲解

Android 开发  Service讲解
Android 开发  Service讲解

Android 开发 Service讲解

学习要求:对ECLISPE中开发ANDROID有一定的认识。

Service是android 系统中的一种组件,它跟Activity的级别差不多,但是他不能自己运行,只能后台运行,并且可以和其他组件进行交互。Service的启动有两种方式:context.startService()和context.bindService()。需要在androidMainfest.xml中注册才能使用。调用流程如下:

context.startService()---->onCreate()- >onStartCommand()(旧版本为:onStart(),如果Service还没有运行,则android先调用onCreate()然后调用onStartCommand();如果Service已经运行,则只调用onStartCommand(),所以一个Service的onStartComand方法可能会重复调用多次)

context.stopService()---->onDestroy()

context. bindService ---->onCreate()->onBind()(onBind将返回给客户端一个IBind接口实例,IBind允许客户端回调服务的方法,比如得到Service运行的状态或其他操作。这个时候把调用者(Context,例如Activity)会和Service绑定在一起,Context退出了,Srevice就会调用onUnbind->onDestroy 相应退出。

onUnbind()---->onDestroy()

现在以startService()开始介绍其开发过程,bindService()差不多。

1.在layout文件夹中新建一个servicetest.xml(系统不能识别大写

字母),添加两个按钮代码,界面如下:

添加代码如下:

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="startService"

android:id="@+id/startService"

/>

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="stopService"

android:id="@+id/stopService"

/>

2.注册Service

在AndroidMainfest中添加如下代码:

3.新建一个class,命名为ServieceTest"(和注册的服务相同)。在

AndroidMainfest.xml中设置为启动文件。

android:label="ServiceActivity ">

android:name="android.intent.action.MAIN"/>

android:name="https://www.doczj.com/doc/639061486.html,UNCHER"/>

主要代码如下:

public class ServiceActivity extends Activity {

private Button startService=null;

private Button stopService=null;

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

//servicetest.xml文件作为显示文件

setContentView(https://www.doczj.com/doc/639061486.html,yout.servicetest);

//取得控件并绑定监听

startService=(Button)findViewById(R.id.startService);

startService.setOnClickListener(new

StartService());

stopService=(Button)findViewById(R.id.stopService);

stopService.setOnClickListener(new

StopService());

}

class StartService implements OnClickListener{

@Override

public void onClick(View v) {

// TODO Auto-generated method stub

Intent intent =new Intent();

intent.setClass(ServiceActivity.this, ServiceTest.class);

ServiceActivity.this.startService(intent);

}

}

class StopService implements OnClickListener{

@Override

public void onClick(View v) {

// TODO Auto-generated method stub

Intent intent =new Intent();

intent.setClass(ServiceActivity.this, ServiceTest.class);

ServiceActivity.this.stopService(intent);

}

}

}

相关主题
文本预览
相关文档 最新文档