aidl介绍

(1)远程服务 运行在其他应用里面的服务  
  (2)本地服务 运行在自己应用里面的服务 
  (3)进行进程间通信  IPC
  (4)aidl Android interface Defination Language Android接口定义语言 专门是用来解决进程间通信的 
  
 aidl 实现步骤和之前调用服务里面的方法的区别 
 (1)先把Iservice.java文件变成aidl文件 
 (2)adil 不认识public 把public 给我去掉
 (3)会自动生成一个Stub类 实现ipc 
 (4)我们定义的中间人对象 直接继承stub
 (5)想要保证2个应用程序的aidl文件是同一个 要求aidl文件所在包名相同
 (6)获取中间人对象Stub.asinterface(Ibinder obj) 
 
package com.test.localservice;

import com.test.remoteservice.Iservice;
import com.test.remoteservice.Iservice.Stub;

import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.view.Menu;
import android.view.View;

public class MainActivity extends Activity {

    private MyConn conn;


    private Iservice iservice; //是我们的中间人对象 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //[1]调用bindservice 获取我们定义的中间人对象 
        
        Intent intent = new Intent();
        //设置一个action
        intent.setAction("com.itheima.remoteservice");
        conn = new MyConn();
        //[2]目的是为了获取我们定义的中间人对象
        bindService(intent, conn,BIND_AUTO_CREATE);
        
        
    }

    
    //点击按钮 调用第8个应用程序服务里面的方法
    public void click(View v) {
        try {
            iservice.callTestMethod();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
    
    //当Activity销毁的时候调用
    @Override
    protected void onDestroy() {  
        //当Activity销毁的时候  取消绑定服务
        unbindService(conn);
        super.onDestroy();
    }
    
    //监视服务的状态
    private class MyConn implements ServiceConnection{


        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            
            //获取中间人对象 
            
        iservice = Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            
        }
        
    }
    
}
原文地址:https://www.cnblogs.com/xufengyuan/p/5997903.html