Android中的AIDL Android studio中建aidl

來源:互聯網
上載者:User

標籤:

1.aidl: android interface definition language,是一種它是一種android內部進程通訊介面的描述語言,通過它我們可以定義進程間的通訊介面
icp:interprocess communication :內部進程通訊

2.既然aidl可以定義並實現進程通訊,那麼我們怎麼使用它呢?文檔/android-sdk/docs/guide/developing/tools/aidl.html中對步驟作了詳細描述:

--1.Create your .aidl file - This file defines an interface (YourInterface.aidl) that defines the methods and fields available to a client. 
建立你的aidl檔案,我在後面給出了一個例子,它的aidl檔案定義如下:寫法跟java代碼類似,但是這裡有一點值得注意的就是它可以引用其它aidl檔案中定義的介面,但是不能夠引用你的java類檔案中定義的介面

[java] view plain copy 
  1. package com.cao.android.demos.binder.aidl;    
  2. import com.cao.android.demos.binder.aidl.AIDLActivity;  
  3. interface AIDLService {     
  4.     void registerTestCall(AIDLActivity cb);     
  5.     void invokCallBack();  
  6. }   

 

Android studio中建aidl

先在main目錄下建立一個檔案夾,命名為aidl,再在該目錄下建立一個包,包名跟AndroidManifest中的package同名,然後在該包下建立aidl檔案,建立完之後在build/generated/source/aidl/debug下就可以見到自動產生的java檔案

卓學騰
連結:http://www.zhihu.com/question/21581761/answer/45895797
來源:知乎
著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。     android中的AIDL處理序間通訊

    關於IPC應該不用多介紹了,Android系統中的進程之間不能共用記憶體,那麼如果兩個不同的應用程式之間需要通訊怎麼辦呢?比如公司的一個項目要更新,產品的需求是依附於當前項目開發一個外掛程式,但是呢這個外掛程式功能以及介面比較複雜,不能和當前項目在一個進程中,同時呢,還要用到當前項目中已經寫好了的一些東西,那麼因為新開發的依附於當前項目的外掛程式和當前項目不是一個進程,因此不能共用記憶體,就出現了問題,於是,需要提供一些機制在不同進程之間進行資料通訊,這個機制就是AIDL了。

一、一個android中AIDL的簡單例子

  假如是這樣,現在有一個項目中提供了比較成熟的計算的方法,而現在我想開發一款軟體其中一個模組想用到一個計算類,而我又不想重新寫了,那麼就可以通過AIDL實現啦。假設,已經開發完成的那個已經提供了比較成熟的計算類的程式叫AIDLCalculateDemoServer(相當於伺服器),而我要寫的程式叫AIDLCalculateDemoClient(相當於用戶端),類似與用戶端伺服器模式。首先至關的看下工程結構圖:

                               

 

             圖1-1 伺服器                   圖1-2 用戶端 

  現在假設自己寫的程式要調用服務端的運算介面,輸入num1和num2,進行遠程運算,調用服務端的介面,服務端運算好之後,返回結果給用戶端,如下:

          

  然後來看看實現,首先需要定義AIDL介面,用戶端和伺服器端都要定義,並且要在同一包中,也就是圖1-1和圖1-2 com.example.aidl.calculate中的CalculateInterface,其中的代碼如下:

1 package com.example.aidl.calculate;2 3 interface CalculateInterface {4     double doCalculate(double a, double b);5 }

  編譯發現,目錄結構1-1和圖1-2中gen/com.example.aidl.calculate中多了CalculateInterface.java檔案,內容如下:

1 package com.example.aidl.calculate;2 3 interface CalculateInterface {4     double doCalculate(double a, double b);5 }

  定義好介面就是要看服務端和用戶端的代碼啦,其中服務端主要看CalculateService代碼,這個一個繼承Service的類,在其中對AIDL中的介面進行賦予實際意義,如下:

 1 package com.example.calculate; 2  3 import com.example.aidl.calculate.CalculateInterface; 4 import com.example.aidl.calculate.CalculateInterface.Stub; 5  6 import android.app.Service; 7 import android.content.Intent; 8 import android.os.IBinder; 9 import android.os.RemoteException;10 import android.util.Log;11 12 public class CalculateService extends Service {13     14     private static final String                            TAG                        =    "CalculateService";15     16     @Override17     public IBinder onBind(Intent arg0) {18         // TODO Auto-generated method stub19         logE("onBind()");20         return mBinder;21     }22     23     @Override24     public void onCreate() {25         // TODO Auto-generated method stub26         logE("onCreate()");27         super.onCreate();28     }29     30     @Override31     public void onStart(Intent intent, int startId) {32         // TODO Auto-generated method stub33         logE("onStart()");34         super.onStart(intent, startId);35     }36     37     @Override38     public boolean onUnbind(Intent intent) {39         // TODO Auto-generated method stub40         logE("onUnbind()");41         return super.onUnbind(intent);42     }43     44     @Override45     public void onDestroy() {46         // TODO Auto-generated method stub47         logE("onDestroy()");48         super.onDestroy();49     }50     51     private static void logE(String str) {52         Log.e(TAG, "--------" + str + "--------");53     }54     55     private final CalculateInterface.Stub mBinder = new CalculateInterface.Stub() {56         57         @Override58         public double doCalculate(double a, double b) throws RemoteException {59             // TODO Auto-generated method stub60             Log.e("Calculate", "遠程計算中");61             Calculate calculate = new Calculate();62             double answer = calculate.calculateSum(a, b);63             return answer;64         }65     };66 }

  然後可以看看,關鍵的服務都提供完畢,那麼在用戶端是怎麼訪問的呢,要進行綁定服務和一個ServiceConnection類完成,如下:

 1 package com.example.calculate; 2  3 import android.app.Activity; 4 import android.content.ComponentName; 5 import android.content.Context; 6 import android.content.Intent; 7 import android.content.ServiceConnection; 8 import android.graphics.Color; 9 import android.os.Bundle;10 import android.os.IBinder;11 import android.os.RemoteException;12 import android.util.Log;13 import android.view.View;14 import android.widget.Button;15 import android.widget.EditText;16 import android.widget.TextView;17 18 import com.example.aidl.calculate.CalculateInterface;19 import com.example.aidlcalculatedemoclient.R;20 21 public class CalculateClient extends Activity {22     private static final String                 TAG                        =            "CalculateClient";23     24     private              Button                 btnCalculate;25     26     private              EditText                etNum1;27     28     private                 EditText                etNum2;29     30     private              TextView                tvResult;31     32     private               CalculateInterface      mService;33     34     private              ServiceConnection        mServiceConnection = new ServiceConnection() {35         36         @Override37         public void onServiceDisconnected(ComponentName name) {38             // TODO Auto-generated method stub39             logE("disconnect service");40             mService = null;41         }42         43         @Override44         public void onServiceConnected(ComponentName name, IBinder service) {45             // TODO Auto-generated method stub46             logE("connect service");47             mService = CalculateInterface.Stub.asInterface(service);48         }49     };50     51     @Override52     protected void onCreate(Bundle savedInstanceState) {53         // TODO Auto-generated method stub54         super.onCreate(savedInstanceState);55         setContentView(R.layout.main);56         57         Bundle args = new Bundle();58         Intent intent = new Intent("com.example.calculate.CalculateService");59         intent.putExtras(args);60         bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);61         62         etNum1 = (EditText) findViewById(R.id.et_num_one);63         etNum2 = (EditText) findViewById(R.id.et_num_two);64         65         tvResult = (TextView) findViewById(R.id.tv_result);66         67         btnCalculate = (Button) findViewById(R.id.btn_cal);68         69         btnCalculate.setOnClickListener(new View.OnClickListener() {70             71             @Override72             public void onClick(View v) {73                 // TODO Auto-generated method stub74                 75                 logE("開始遠程運算");76                 try {77                     double num1 = Double.parseDouble(etNum1.getText().toString());78                     double num2 = Double.parseDouble(etNum2.getText().toString());79                     String answer = "計算結果:" + mService.doCalculate(num1, num2);80                     tvResult.setTextColor(Color.BLUE);81                     tvResult.setText(answer);82                             83                 } catch (RemoteException e) {84                 }85             }86         });87     }88     89     private void logE(String str) {90         Log.e(TAG, "--------" + str + "--------");91     }92 }

  如此一來,大功已經基本告成,最後,我們在來看看服務端的設定檔吧:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.aidlcaculatedemoserver"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="17" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.example.aidlcaculatedemoserver.MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <service android:name="com.example.calculate.CalculateService">            <intent-filter>                <action android:name="com.example.calculate.CalculateService" />            </intent-filter>        </service>    </application></manifest>

Android中的AIDL Android studio中建aidl

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.