服务的使用与知识点
服务分为:本地服务、远程服务;区别:本地服务指的是服务提供者与调用者是在同一个程序中,远程服务是服务提供者与调用者是属于不同的程序。
服务的生命周期:onCreate()----->> onStartCommand()----->> onDestroy();
如果服务已经开启,不会重复的执行onCreate(),而是会调用onStartCommand()方法,服务停止的时候会调用onDestory();
绑定服务的时候是异步的,bindService();
本地服务使用的方法:
绑定本地服务调用方法的步骤:
1.在服务的内部创建一个内部类提供一个方法,可以间接调用服务的方法
private class MiddlePerson extends Binder implements IMiddlePerson{}
2.实现服务的onbind方法,返回的就是中间人MiddlePerson
3.在activity 绑定服务。bindService();
4.在服务成功绑定的时候会执行一个方法onServiceConnected 传递过来一个IBinder对象
5.强制类型转化调用接口里面的方法。
一、服务的开启方法:
1、使用Intent的方法:(一旦服务开启跟调用者(开启者)就没有关系了,开启者没有调用服务里的方法)
Intent intent = new Intent(Context context, Class> cls);
startService(intent);
2、使用绑定的方式开启(调用者挂了,服务也会跟着挂掉,开启者可以调用服务里面的方法):
MyConn conn = new MyConn();
Intent intent = new Intent(Context context, Class> cls);
bindService(intent,conn,BIND_AUTO_CREATE);
private class MyConn implements ServiceConnection{
// 当服务被连接的时候调用服务别成功绑定的时候调用
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
把service强制转换成接口类型的
}
//当服务失去连接的时候调用(一般进程挂了,服务被异常杀死)
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
二、服务停止的方法:
1.使用Intent的方法:
Intent intent = new Intent(Context context, Class> cls);
stopService(intent);
2.使用解除绑定的方法:
unbindService(conn);
三、服务的定义:
1、一个简单的服务定义(继承Service类):
public class MyService extends Service {
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) { return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
2、一个定义了方法的服务:
定义一个接口:
public interface 接口名{
在这里定义要在服务里暴露出来的方法
}
定义一个服务:
public class MyService extends Service {
//实现服务成功绑定的代码,返回一个中间人。
@Override
public IBinder onBind(Intent arg0) {
return 内部类实例;
}
@Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) { return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
}
//用private 可以保护不希望暴露出来的方法,而要暴露出来的方法在接口里面定义private class 类名extends Binder implements 接口名{
实现接口的方法
}
}
3、清单文件的修改:
远程服务使用的方法:
aidl:android interface definition language 安卓接口定义语言
aidl文件都是公有的,没有访问权限修饰符
IPC:inter process communication
绑定远程服务调用方法的步骤:
1.在服务的内部创建一个内部类提供一个方法,可以间接调用服务的方法
2.把暴露的接口文件的扩展名改为aidl文件去掉访问修饰符public
private class MiddlePerson extends IMiddlePerson.Stub{} IPC的子类
3.实现服务的onbind方法,返回的就是中间人IMiddlePerson
4.在activity 绑定服务。bindService();
5.在服务成功绑定的时候会执行一个方法onServiceConnected 传递过来一个IBinder对象
6.IMiddlePerson.Stub.asInterface(binder) 调用接口里面的方法。
混合调用服务的方法
使用情景:即要服务长期运行,以能绑定服务调用服务里的方法。
步骤:
1、使用Intent的方式开启服务,以便让服务在后台长期运行。使用startService()方法启动服务;
2、使用绑定服务的方式绑定服务。使用bindService()方法绑定服务;
3、使用unbindService()方法解除绑定服务;
4、使用stopService()方法停止服务;