基本概念:
- Service是一种在后台运行,没有界面的组件,由其他组件调用开始。程序退出后仍然可以在后台运行
- 创建Service,定义类继承Service,AndroidManifest.xml中定义<service>
- 开启Service,在其他组件中调用startService方法
- 停止Service,调用stopService方法
绑定服务
- 使用bindService绑定服务,传入一个自定义的ServiceConnection用来接收IBinder
- 定义一个业务接口,其中定义需要的使用的方法
- 服务中自定义一个IBinder继承Binder并实现业务接口,在onBind方法中返回
- 调用端将IBinder转为接口类型,调用接口中的方法即可调用到服务中的方法
生命周期:
start - stop : onCreate- onStart- onStop
bind-unbind : onCreate- onStart - onBind - onUnBind - onDestory
bind - stop : onCreate - onStart - onBind - 无法关闭
start - unbind: 程序挂掉
start - bind - unbind : onCreate- onStart - onBind - onUnBind
start - bind - unbind
-stop : onCreate- onStart - onBind - onUnBind - onDestory
例:
public class MyServcice extends Service {
class MyBinder extends Binder implements InvokeInterface {
@Override
public void haha() {
System.out.println("haha");
}
}
@Override
public IBinder onBind(Intent intent) {
System.out.println("onBind");
return new MyBinder();
}
@Override
public boolean onUnbind(Intent intent) {
System.out.println("unbind");
return super.onUnbind(intent);
}
@Override
public int onStartCommand(Intent intent, int flags, final int startId) {
System.out.println("onStart");
new Thread(){
public void run() {
for(int i=0; i<20; i++) {
System.out.println(i);
SystemClock.sleep(500);
}
stopSelf(startId);
};
}.start();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onCreate() {
System.out.println("onCreate");
super.onCreate();
}
@Override
public void onDestroy() {
System.out.println("onDestory");
super.onDestroy();
}
}
/**
* 业务接口
* @author jiangwei
*
*/
public interface InvokeInterface {
void haha();
}
public class MainActivity extends Activity {
private Intent intent;
private ServiceConnection conn = new ServiceConnection() {
private InvokeInterface ii;
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
ii = (InvokeInterface) service;
ii.haha();
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intent = new Intent(this, MyServcice.class);
}
public void start(View v) {
startService(intent);
}
public void stop(View v) {
stopService(intent);
}
public void bind(View v) {
bindService(intent, conn, Context.BIND_AUTO_CREATE);
}
public void unbind(View v) {
unbindService(conn);
}
}