Android筆記三十四.Service綜合執行個體二,android.service

來源:互聯網
上載者:User

Android筆記三十四.Service綜合執行個體二,android.service
綜合執行個體2:用戶端訪問遠程Service服務實現:通過一個按鈕來擷取遠程Service的狀態,並顯示在兩個文字框中。思路:假設A應用需要與B應用進行通訊,調用B應用中的getName()、getAuthor()方法,B應用以Service方式向A應用提供服務。所以,我們可以將A應用看成是用戶端,B應用為服務端,分別命名為AILDClient、AILDServer.
一、服務端應用程式1.src/com.example.aildserver/song.aidl:AILD檔案    當完成aidl檔案建立後,選擇儲存,eclipse會自動在項目的gen目錄中同步產生Song.java介面檔案。介面檔案中產生一個Stub抽象類別,裡麵包括aidl定義的方法,還包括一些其它輔助性的方法,如geName()、getSong()方法,我們可以通過這兩個方法實現用戶端讀寫Service服務端資料。

  1.     package com.example.aildserver;  
  2.     interface Song  
  3.     {  
  4.          String getName();  
  5.          String getSong();  
  6.     } 
位置如下:
    編寫Aidl檔案時,需要注意:          1.介面名和aidl檔案名稱相同;        2.介面和方法前不用加存取權限修飾符public,private等,也不能用final,static;        3.Aidl預設支援的類型包話java基本類型(int、long、boolean等)和(String、List、Map、CharSequence),使用這些類型時不需要import聲明。對於List和Map中的元素類型必須是Aidl支援的類型。如果使用自訂類型作為參數或返回值,自訂類型必須實現Parcelable介面。        4.自訂類型和AIDL產生的其它介面類型在aidl描述檔案中,應該顯式import,即便在該類和定義的包在同一個包中。                5.在aidl檔案中所有非Java基本型別參數必須加上in、out、inout標記,以指明參數是輸入參數、輸出參數還是輸入輸出參數。        6.Java原始類型預設的標記為in,不能為其它標記。  2.src/com.example.aildserver/MyService.java功能:Service子類,完成Service服務開發核心步驟:    (1)重寫Service的onBind()方法(用於返回一個IBinder對象)、onCreate()方法、onDestroy() 方法、onUnbind()方法;    (2)定義一個Stub的子類,該內部類實現了IBinder、Song兩個介面,該子類對象將作為遠程Service的onBind()方法返回IBinder對象的代理傳給用戶端的ServiceConnection的onServiceConnected方法的第二個參數。
  1. package com.example.aildserver;  
  2. import com.example.aildserver.Song.Stub;  
  3. import android.app.Service;  
  4. import android.content.Intent;  
  5. import android.os.Binder;  
  6. import android.os.IBinder;  
  7. import android.os.RemoteException;  
  8. public class MyService extends Service {  
  9.  private String[] names = new String[] {"林俊傑","蔡依林","鄧紫棋"};  
  10.  private String[] songs = new String[] {"可惜沒如果","第三人稱","多遠都要在一起"};  
  11.  private String name,song;  
  12.  private int current=1;  //當前位置  
  13.  private MyBinder binder = new MyBinder();  //執行個體化一個IBinder對象  
  14.  /*0.Stub內部類 
  15.   * 該內部類實現了IBinder、Song兩個介面,這個Stub類將會作為遠程Service的回調類。*/  
  16.  public class MyBinder extends Stub  
  17.  {  
  18.   //a.用戶端回調該方法擷取歌手名  
  19.   public String getName() throws RemoteException  
  20.   {  
  21.    return name;  
  22.   }  
  23.   //b.用戶端回調該方法擷取歌曲  
  24.   public String getSong() throws RemoteException  
  25.   {  
  26.    return song;  
  27.   }  
  28.    
  29.  }  
  30.  /*1.onBind方法 
  31.   * service用於返回一個IBinder對象給用戶端方便通訊 
  32.  */  
  33.  @Override  
  34.  public IBinder onBind(Intent arg0) {  
  35.   return binder;  
  36.  }  
  37.  /*2.onCreate方法 
  38.   * 當Service啟動後,自動調用該方法,用於初始化 
  39.   * */  
  40.  public void onCreate() {  
  41.   name = names[current];     //給name、song賦值  
  42.   song = songs[current];  
  43.   System.out.println("Service print:name="+name+"song="+song);  
  44.   super.onCreate();  
  45.  }  
  46.  /*3.onDestroy方法 
  47.   * 當訪問者調用Context.stopService方法後,調用該方法關閉Service服務 
  48.   * */  
  49.  public void onDestroy() {  
  50.   super.onDestroy();  
  51.  }  
  52.  /*4.onUnbind方法 
  53.   * 當訪問者調調用Context.unBind()方法後,調用該方法與Service解除綁定*/  
  54.  public boolean onUnbind(Intent intent) {  
  55.   return false;  
  56.  }  
  57.    
  58. }  
注意1:用戶端訪問Service時,Android並不是直接返回Service對象給用戶端,Service只是將一個回調對象(IBinder對象)通過onBind()方法回調給用戶端。  注意2:與綁定本地Service不同的是,本地Service的onBind()方法會直接把IBinder對象本身傳給用戶端的ServiceConnection的onServiceConnected方法的第二個參數。但遠程Service的onBind()方法只是將IBinder對象的代理傳給用戶端的ServiceConnection的onServiceConnected方法的第二個參數。當用戶端擷取了遠端Service的IBinder對象的代理之後,接下來可通過該IBinder對象去回調遠程Service的屬性或方法。 3.AndroidManifest.xml功能:配置Service組件,並指定其action屬性(方便其他應用程式啟動該Service服務)
  1.     <application  
  2.         ........  
  3.         <!-- 配置service -->  
  4.         <service android:name=".MyService">  
  5.             <intent-filter>  
  6.                     <action android:name="com.jiangdongguo.service"/>  
  7.             </intent-filter>  
  8.         </service>  
  9.     </application> 

二、用戶端應用程式
1.拷貝服務端.aidl檔案到用戶端    把AIDLService應用中aidl檔案所在package連同aidl檔案一起拷貝到用戶端AIDLClient應用,eclipse會自動在A應用的gen目錄中為aidl檔案同步產生Song.java介面檔案,接下來就可以在AIDLClient應用中實現與AIDLService應用通訊。2.src/com.example.aildclient/MainActivity.java功能:(1)啟動服務端Service服務;(2)擷取返回的IBinder代理對象,並完成與服務端程式的通訊
  1. package com.example.aildclient;  
  2.   
  3. import com.example.aildserver.Song;  
  4.   
  5. import android.app.Activity;  
  6. import android.app.Service;  
  7. import android.content.ComponentName;  
  8. import android.content.Intent;  
  9. import android.content.ServiceConnection;  
  10. import android.os.Bundle;  
  11. import android.os.IBinder;  
  12. import android.os.RemoteException;  
  13. import android.view.View;  
  14. import android.view.View.OnClickListener;  
  15. import android.widget.Button;  
  16. import android.widget.EditText;  
  17. public class MainActivity extends Activity {  
  18.     private Button getBtn;  
  19.     private EditText song;  
  20.     private EditText name;  
  21.     private Song binder;  
  22.     //1.建立一個ServiceConnection對象  
  23.     private ServiceConnection conn = new  ServiceConnection()  
  24.     {  
  25.   public void onServiceConnected(ComponentName name, IBinder service)  
  26.   {  
  27.    binder = Song.Stub.asInterface(service); //擷取Service返回的代理IBinder對象  
  28.      
  29.   }  
  30.   public void onServiceDisconnected(ComponentName name) {  
  31.   }  
  32.     };  
  33.  protected void onCreate(Bundle savedInstanceState) {  
  34.         super.onCreate(savedInstanceState);  
  35.         setContentView(R.layout.main);  
  36.         getBtn=(Button)findViewById(R.id.get);  
  37.         song=(EditText)findViewById(R.id.song);  
  38.         name=(EditText)findViewById(R.id.name);  
  39.     //2.指定要啟動的Service  
  40.         Intent intent = new Intent("com.jiangdongguo.service");  
  41.         bindService(intent, conn, Service.BIND_AUTO_CREATE);  
  42.         getBtn.setOnClickListener(new OnClickListener(){  
  43.            
  44.    public void onClick(View arg0)  
  45.    {  
  46.     try {  
  47.      name.setText(binder.getName());  
  48.      song.setText(binder.getSong());  
  49.     } catch (RemoteException e) {  
  50.      e.printStackTrace();  
  51.     }  
  52.    }  
  53.         });  
  54.     }  
  55. }  
    對於遠程服務調用,遠程服務返回給用戶端的對象為代理對象,用戶端在onServiceConnected(ComponentName name, IBinder service)方法引用該對象時不能直接強轉成介面類型的執行個體,而應該使用asInterface(IBinder iBinder)進行類型轉換。 三、效果示範

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.