• Android AIDL 遠程服務器使用示例

    0
    Android Java XML C/C++ Go 17902 次瀏覽
    很多網友來函表示對Android AIDL不是很理解,這里Android123準備了一個簡單的例子,幫助大家了解Android上比較強大的遠程服務設計吧。

    一、為什么要使用AIDL,他的優勢有哪些呢?
        AIDL服務更像是 一個Server,可以為多個應用提供服務。由于使用了IDL這樣類似COM組件或者說中間語言的設計,可以讓后續的開發者無需了解內部,根據暴漏的接口實現相關的操作,AIDL可以工作在獨立的進程中。

    二、學習AIDL服務需要有哪些前置知識?
        作為Android上服務的擴展,首先你要了解Android Service模型,Android Serivice我們可以分為兩種模式,三個類型,1.最簡單的Service就是無需處理onBind方法,一般使用廣播通訊,效率比較低。2. 使用Binder模式處理Service和其他組件比如Activity通訊,Android開發網提示對于了解了Binder模式的服務后,開發 AIDL遠程服務就輕松容易的多。
    三、具體實例
        我們以com.android123.cwj.demo為工程名,首先在工程目錄的com.android123.cwj目錄下創建一個ICWJ.aidl文件,內容為
    package com.android123.cwj;
      interface ICWJ {
      String getName();
    } 
    如果格式AIDL格式沒有問題,在Eclipse中ADT插件會在工程的gen目錄下會自動生成一個Java實現文件。

    在Service中代碼如下:
    public class CWJService extends Service {
    public static final String BIND = "com.android123.cwj.CWJService.BIND";  
    public String mName="android123";
    private final ICWJ.Stub mBinder = new ICWJ.Stub()
      {
         @Override 
         public String getName() throws RemoteException
         {    //重寫在AIDL接口中定義的getName方法,返回一個值為我們的成員變量mName的內容。
            try
            {
              return CWJService.this.mName;
            }
            catch(Exception e)
            {
               return null;
            }
        }
    };
    
      @Override
      public void onCreate() {
       Log.i("svc", "created."); 
      }
    
      @Override
      public IBinder onBind(Intent intent) {
         return mBinder;    //這里我們要返回mBinder而不是一般Service中的null
      }
    
    }
    接著在AndroidManifest.xml文件中定義 
    <service android:name=".CWJService">
       <intent-filter>
        <action android:name="com.android123.cwj.CWJService.BIND" />
        <category android:name="android.intent.category.DEFAULT"/>
       </intent-filter>
      </service>
    接下來在Activity中的調用,我們可以
     private ICWJ objCWJ = null;
       private ServiceConnection serviceConn = new ServiceConnection() {
    
      @Override
      public void onServiceDisconnected(ComponentName name) {
       }
    
      @Override
      public void onServiceConnected(ComponentName name, IBinder service) {
       objCWJ = ICWJ.Stub.asInterface(service);
      }
    };
    在Activity的onCreate中加入綁定服務的代碼
    Intent intent = new Intent();
      intent.setClass(this, CWJService.class);
      bindService (intent, serviceConn, Context.BIND_AUTO_CREATE);
    同時重寫Activity的onDestory方法
    @Override
       public void onDestroy() {
            unbindService(serviceConn);  // 取消綁定
        super.onDestroy();
       }
    執行AIDL的getName可以通過下面的方法 
    if (objCWJ == null)
       {
           try {
                String strName = obj.getName();
           } 
           catch (RemoteException e) 
           {}
       }
    以上過程中,如果ADT插件沒有自動生成ICWJStub類在工程的gen目錄下時,可以手動在sdk根目錄下platform-tools目錄下,手動實用AIDL.exe來生成,這樣可以看清楚AIDL文件到底是哪里存在格式上的錯誤。

    相似問題

    相關經驗

    相關資訊

    相關文檔

  • sesese色