看了一会书,总结下安卓service,加深下印象
MyService 类:
package com.example.com.binderservicedemo;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class MyService extends Service {
private binder Mybinder = new binder();
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
Log.i("test", "绑定服务");
return Mybinder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("test", "服务启动");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i("test", "服务关闭");
}
@Override
public boolean onUnbind(Intent intent) {
Log.i("test", "解除绑定");
return super.onUnbind(intent);
}
public void ServiceMethod() {
Log.i("test", "我是服务里面的方法");
}
public class binder extends Binder{
public void CallServiceMethod(){
ServiceMethod();
}
}
}
开启服务:服务一直在后台运行,会调MyService里的onStartCommand()方法,这种方式不能与MyService 通讯,但是服务一直在后台允许,除非服务被停止。
Intent intent = new Intent(Activity.this,MyService.class);
startService(intent);
关闭服务:MyService里的onDestroy()方法会被调用
stopService(intent);
绑定服务:这个方式可以与MyService通讯,可以调用里面的方法,例如 调用 ServiceMethod()方法,bindService()方法会,调用服务里的onCreate()(第一次把绑定时)->onBind() 并不会调用 onStartCommand()方法。
Intent intent = new Intent(Activity.this,MyService.class);
serviceconnection con = new serviceconnection();
bindService(intent, con, BIND_AUTO_CREATE);
public class serviceconnection implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
MyService.binder mybinder = (MyService.binder) service;
mybinder.CallServiceMethod();
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
解除绑定:调用Activity类的unbindService()方法,可以解除绑定。
unbindService(con);
混合调用:用startserivce 开启服务,bindservice 绑定服务,unbindservice 解除绑定,stopservice 关闭服务。服务会一直在后台运行,这样也能调用服务里面的方法。
区别:startService 开启服务,服务一直在后台运行,跟开启者没有关系,bind的方式开启服务,绑定服务,调用者挂了,服务也会跟着挂掉,开启者可以调用服务里面的方法。