android service 使用以及aidl使用
(2011-05-08 10:50:53) service
1:service的启动方式
service是一个在后台运行的服务。你所启动的这个service所做得工作最好在另一个线程中做。因为这个service的线程的工作将阻塞调用它的线程。
创建和启动一个service有两种方式
Intent in = new Intent(***);
startService(in) 和 bindService(in)。
与上面相对应,停止一个service也有两种方式
stopService(in) 和 unbindService(in)。
如果是本地的service 则 Intent in = newIntent(this,LocalService.class)。同时那个service要在manifest文件中标明自己的name
<service android:name =".serviceA"/>
如果是非本地的service 则在Intent中指明就可以了Intent in= new Intent("com.test.A")与此同时那个非本地的service也要在manifest文件中申明自己的name和intent-filter
<service android:name =".serviceA">
<intent-filter>
<actionandroid:name="com.test.A"/>
<categoryandroid:name="android.intent.category.DEFAULT"/>
</intent-filter>
</service>
2:使用startService 和stopService
这种启动和停止方式是比较简单的。只需要在调用Activity中直接写上就可以了。
2.1service客户端代码
调用service的客户端的activity的代码:
package com.D_activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class D_activity extends Activity {
Buttonb;
privateboolean running = false;
@Override
public voidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//设置一个按钮来开启和关闭服务
b=(Button)findViewById(R.id.button);
}
@Override
protectedvoid onResume() {
//指定一个Intent
final Intent in = new Intent("com.test.A");
super.onResume();
b.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
if(running){
running = false;
//关闭服务
stopService(in);
b.setText("start ");
}