1. 远程服务:调用者和服务在不同的工程代码里面。
本地服务:调用者和服务在同一个工程代码里面。
2. 远程服务,因为不在同一个程序中,所以只能用隐式调用,在配置文件中配置
-<service android:name="com.itheima.remoteservice.RemoteService"> -<intent-filter> <action android:name="com.itheima.remoteservice"/> </intent-filter> </service>
3. 一个应用程序都是运行在自己独立的进程里面的。
进程操作系统分配内存空间的一个单位。进程的数据都是独立的。独立的内存空间。
4. aidl:android interface definitionlanguage 安卓接口定义语言
aidl文件都是公有的,没有访问权限修饰符
5. IPC: inter process communication 进程间通讯
1.1远程服务:
public class RemoteService extends Service {
@Override
public void onCreate() {
System.out.println("远程服务被创建了。。。");
super.onCreate();
}
@Override
public void onDestroy() {
System.out.println("远程服务被销毁了。");
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
return new MiddlePerson();
}
private void methodInService(){
System.out.println("我是远程服务的方法,我被调用了。。。。");
}
//1.创建一个中间人 远程服务继承的是ipc的一个实现类
private class MiddlePerson extends IMiddlePerson.Stub{
@Override
public void callMethodInService() {
methodInService();
}
}
}
1.2 把接口改为aidl,新建文件:new file-------aidl interface IMiddlePerson {
/**
* 调用服务里面的方法
*/
void callMethodInService();
}
2.1 创建一个包,与远程服务中的包名一样,然后把远程服务接口aidl复制到新建包中
package com.itheima.remoteservice;
interface IMiddlePerson {
/**
* 调用服务里面的方法
*/
void callMethodInService();
}
2.2 调用远程服务
public class MainActivity extends Activity {
private MyConn conn;
private IMiddlePerson iMp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* 绑定远程服务
* @param view
*/
public void bind(View view){
Intent intent = new Intent();
intent.setAction("com.itheima.remoteservice");
conn = new MyConn();
bindService(intent, conn, BIND_AUTO_CREATE);
}
private class MyConn implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
iMp = IMiddlePerson.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
public void call(View view){
try {
iMp.callMethodInService();
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
protected void onDestroy() {
unbindService(conn);
super.onDestroy();
}
}
5.
绑定本地服务调用方法的步骤:
1. 在服务的内部创建一个内部类 提供一个方法,可以间接调用服务的方法
private class MiddlePerson extends Binder implements IMiddlePerson{}
2 . 实现服务的onbind方法,返回的就是中间人 MiddlePerson
3. 在activity 绑定服务。bindService();
4. 在服务成功绑定的时候 会执行一个方法 onServiceConnected 传递过来一个 IBinder对象
5. 强制类型转化 调用接口里面的方法。
6.
绑定远程服务调用方法的步骤:
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) 调用接口里面的方法。