StartedService使用步骤:
1.继承Service类实现自己的服务
Service过程如下:
a.onCreate() //只在服务第一次创建时调用
b.onStartCommand(Intent intent, int flags, int startId) //每次启动服务都会调用
c.onDestroy()
2.在AndroidManifest中注册服务
3.启动服务StartService() 注意:这里跟启动Activity类似
4.停止服务 使用stopService()和 stopSelf()
BoundService 的使用步骤:
1.继承Service或者IntentService类实现自己的服务
2.在AndroidManifest中注册服务
3.绑定服务bindService()
4.取消绑定服务unbindService()
代码如下
服务器端实现:
<span style="white-space:pre"> </span>//创建接口对象
private BindService myBindService = new BindService();
//定义binder接口实现
class BindService extends Binder
{
public String helloWorld(String name) {
return "Your name is :"+name ;
}
}
<span style="white-space:pre"> </span>public IBinder onBind(Intent intent) {
Log.i("yaotaineed", "MyService onbind");<span style="font-family: Arial, Helvetica, sans-serif;"> </span>
<span style="white-space:pre"></span><pre name="code" class="java"> //暴露binder
return myBindService;
}
客户端的实现:
Button b4=(Button) findViewById(R.id.BindServicebutton);
b4.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
intentstartService = new Intent(AActivity.this, MyService.class);
//获得连接服务
connection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO 自动生成的方法存根
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO 自动生成的方法存根
String string = ((BindService)service).helloWorld("lyt");
Toast.makeText(AActivity.this, string, 1000).show();
}
};
//连接bind
bindService(intentstartService, connection, BIND_AUTO_CREATE);
}
});
Button b5=(Button) findViewById(R.id.unBindServicebuttonn);
b5.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
unbindService(connection);
}
});
IntentService的简单使用:
网上资料:IntentService是继承于Service并处理异步请求的一个类,在IntentService内有一个工作线程来处理耗时操作,启动IntentService的方式和启动传统Service一样,同时,当任务执行完后,IntentService会自动停止,而不需要我们去手动控制。另外,可以启动IntentService多次,而每一个耗时操作会以工作队列的方式在IntentService的onHandleIntent回调方法中执行,并且,每次只会执行一个工作线程,执行完第一个再执行第二个,以此类推。
这里首先是要提供一个无参的构造函数,并且必须在其内部调用父类的有参构造函数。然后要在子类中实现onHandleIntent()这个抽象方法,在这个方法中可以去处理一些具体的逻辑,,而且不用担心ANR的问题,因为这个方法已经是在子线程中运行了。
代码如下:
public class MyIntentService extends IntentService {
public MyIntentService(String name) {
super(name);
// TODO 自动生成的构造函数存根
}
public MyIntentService()
{
super("hallo");//调用父类的有参构造函数
}
@Override
protected void onHandleIntent(Intent intent) {
// TODO 自动生成的方法存根
for (int i = 0; i < 10; i++) {
Log.i("need", i+"");
}
}