Android 進(jìn)程間通信AIDL簡單使用

最近出去面試經(jīng)常會(huì)被問到Android進(jìn)程間通信,因?yàn)轫?xiàng)目中基本上用不到進(jìn)程間通信,所以不是特別了解,下來之后專門去查詢了下資料,Android進(jìn)程通信有4種,下面簡單介紹下AIDL 的通信方法,簡單的寫個(gè)demo。那么首先什么是AIDL呢 ,aidl是 AnInterface definition language的縮寫,一看就明白,它是一種android內(nèi)部進(jìn)程通信接口的描述語言。首先新建一個(gè)aidl類型的類命名為IMyAidlInterface

aidl.png

androidstudio會(huì)自動(dòng)在main 目錄下新建一個(gè)aidl目錄,我們新建的文件會(huì)放到這個(gè)目錄下面,目錄的包路徑和java 目錄下的包路徑一致。
Paste_Image.png

package example.admin.com.testaidl;  
interface IMyAidlInterface {   
      void hello(String str); /** Demonstrates some basic types that you can use as parameters * and return values in AIDL. */   
      void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString);   
}

我們發(fā)現(xiàn)aidl文件其實(shí)就是一個(gè)接口文件,as會(huì)自動(dòng)新建一個(gè)方法basicTypes方法,這個(gè)方法并沒什么卵用,可以直接刪掉,我們新定義一個(gè)方法叫hello 接收一個(gè)String類型的參數(shù).然后重新編譯一下,編譯完成后,在build目錄下面自動(dòng)生成了一個(gè)IMyAidlInterface的接口文件,它集成了android.os.IInterface接口,有一個(gè)名為Stub的內(nèi)部類,stub類繼承Binder。
自動(dòng)生成文件路徑如下圖

Paste_Image.png

接著新建一個(gè)MyService類繼承Service

package example.admin.com.testaidl;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;
/** * Created by admin * date 16/10/11. */
public class MyService extends Service {    
   public MyService() {        
      Log.i("TAG", "MyService: ");   
   } 
   @Override   
   public void onCreate() {        
      super.onCreate();        
      Log.i("TAG", "onCreate: ");    
   }   
   @Nullable   
   @Override    
   public IBinder onBind(Intent intent) {        
      Log.i("TAG", "onBind: " + intent);        
      return mBinder;   
    }   
    public final IMyAidlInterface.Stub mBinder = new IMyAidlInterface.Stub() {       
       @Override        
       public void hello(String str) throws RemoteException {            
            Log.i("TAG", "hello: " + str);       
       }       
       @Override        
        public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException { 
     
        }   
     };
}

核心代碼就是mBinder 這一段,創(chuàng)建一個(gè)IMyAidlInterface的內(nèi)部類Stub的實(shí)力,里面實(shí)現(xiàn)我們接口中定義的方法,此處就是接受輸入?yún)?shù) 并打印出來。然后在manifest.xml 文件中注冊這個(gè)service

<service android:name=".MyService"> 
      <intent-filter> 
          <action android:name="example.admin.com.testaidl.MyService" />
      </intent-filter>
</service>

到目前為止服務(wù)端的代碼我們已經(jīng)完成。接下來是客戶端的代碼

package example.admin.com.testaidl;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;import android.content.ServiceConnection;
import android.os.IBinder;import android.os.RemoteException;import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;import android.util.Log;
import android.view.View;import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity { 
    TextView mTextView;
    Button mButton; 
    IMyAidlInterface mIMyAidlInterface; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) {                
         super.onCreate(savedInstanceState); 
         setContentView(R.layout.activity_main); 
         initView();
     } 
     private void initView(){ 
          mTextView = (TextView) findViewById(R.id.textview); 
          mButton = (Button) findViewById(R.id.button);           
          mButton.setOnClickListener(new View.OnClickListener() { 
                    @Override
                    public void onClick(View v) { 
                        Intent intent = new Intent();           
                        intent.setAction("example.admin.com.testaidl.MyService");//你定義的service的action 
                        intent.setPackage("example.admin.com.testaidl");//這里你需要設(shè)置你應(yīng)用的包名 
                        bindService(intent,mConnection, Context.BIND_AUTO_CREATE); } });
           } 
        ServiceConnection mConnection = new ServiceConnection() { 
            @Override 
              public void onServiceConnected(ComponentName name, IBinder service) {
               mIMyAidlInterface = IMyAidlInterface.Stub.asInterface(service); 
              Log.i("TAG", "onServiceConnected: " + mIMyAidlInterface); 
              try { 
                    mIMyAidlInterface.hello("World!!!"); 
              }  catch (RemoteException e) { e.printStackTrace(); } } 
              @Override 
              public void onServiceDisconnected(ComponentName name) {
                   Log.i("TAG", "onServiceDisconnected: " + name); 
                }
         };
}

布局文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:id="@+id/activity_main" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:paddingBottom="@dimen/activity_vertical_margin" 
android:paddingLeft="@dimen/activity_horizontal_margin" 
android:paddingRight="@dimen/activity_horizontal_margin" 
android:paddingTop="@dimen/activity_vertical_margin" 
tools:context="example.admin.com.testaidl.MainActivity">

   <TextView android:id="@+id/textview"
       android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Hello World!"/>

     <Button android:id="@+id/button" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="Button"/>
</RelativeLayout>

點(diǎn)擊按鈕 查看輸出日志

Paste_Image.png

運(yùn)行正常?。?br> 中間遇到一個(gè)錯(cuò)誤,報(bào)錯(cuò)信息IllegalArgumentException: Service Intent must be explicit 解決辦法 如何解決Android 5.0中出現(xiàn)的警告:Service Intent must be expli

github地址:https://github.com/cnexcelee/TestAIDL/tree/master
推薦閱讀:Android:學(xué)習(xí)AIDL,這一篇文章就夠了(上)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容