Android中遠程Service淺析

來源:互聯網
上載者:User

標籤:des   android   style   blog   http   io   ar   os   使用   

上一篇文章中簡單的寫了一下關於Android中Service的兩種啟動方式,不過都是本地的服務,今天就簡單的寫下關於Android中遠程Service的使用,學習之前先瞭解兩個概念,AIDL( Android Interface definition language)字面上的意思就是借口定義語言,專業一點理解就是Android進程之間通訊的借口描述語言。IPC(Inter-Process Conmmunication)內部進程之間的通訊,同一個手機上,如果你的APP需要訪問調用另外一個APP的服務,通訊的方式就是IPC。

同一個APP中Service調用

跟上篇文章不同,這次先自行建立一個名稱為BookAIDLService.aidl的AIDL檔案:

 

package com.remote.service;interface BookAIDLService {    int  sum(int a,int b);}

 

  吐槽一下,網上很多都是這麼寫的,自己新增的時候沒有找到如何建立一個AIDL檔案,你首先需要建一個BookAIDLService.java檔案,然後修改尾碼名為aidl,這個時候看到效果如下:

儲存之後,會自動的在gen目錄下產生一個BookAIDLService.java檔案,還是跟最開始一樣,看下應用程式頁面:

本地事件針對的是第三個按鈕,先來重寫下BookService:

 

public class BookService extends Service {private String tag = "BookService";    BookAIDLService.Stub bookAIDLBinderStub=new Stub() {@Overridepublic int sum(int a, int b) throws RemoteException {// TODO Auto-generated method stubreturn a+b;}};@Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.onCreate();Log.i(tag, "開始onCreate啟動了"); Log.i("BookService","BookService的ID:"+Process.myPid());//try {//Thread.sleep(40000);//} catch (InterruptedException e) {//// TODO Auto-generated catch block//e.printStackTrace();//}  }@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {// TODO Auto-generated method stubLog.i(tag, "開始執行onStartCommand啟動了");Toast.makeText(this, "BookService開始了", Toast.LENGTH_SHORT).show();return super.onStartCommand(intent, flags, startId);}@Overridepublic void onDestroy() {// TODO Auto-generated method stubLog.i(tag, "銷毀onDestroy啟動了");super.onDestroy();}@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubLog.i(tag, "綁定onBind啟動了");return bookAIDLBinderStub;}@Overridepublic boolean onUnbind(Intent intent) {// TODO Auto-generated method stubLog.i(tag, "解除綁定onUnbind啟動了");return super.onUnbind(intent);}class BookBinder extends Binder {public BookService getCurrentService() {return BookService.this;}}}

 

  跟之前最大的不同就是在onBind方法中返回一個bookAIDLBinderStub,同時上次寫的BookConnection也要衝洗寫一下:

    class BookServiceConnection implements ServiceConnection{private BookAIDLService bookAIDLService;public BookServiceConnection() {super();// TODO Auto-generated constructor stub}@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {// TODO Auto-generated method stub//擷取執行個體//BookService  bookService=((BookService.BookBinder)service).getCurrentService();//just  do  wo  you  want to do BookAIDLService  bookAIDLService=BookAIDLService.Stub.asInterface(service);  try {int result=bookAIDLService.sum(10, 100);Log.i("BookService", "BookAIDLService調用結果:"+result);} catch (RemoteException e) {// TODO Auto-generated catch blocke.printStackTrace();}  }@Overridepublic void onServiceDisconnected(ComponentName name) {// TODO Auto-generated method stub}        } }

  前台的調用是:

Intent binderStartIntent=new Intent("com.example.googleservice.BookService.AIDL");  connection=new BookServiceConnection();bindService(binderStartIntent, connection,Context.BIND_AUTO_CREATE);

  這裡Intent是隱式調用,如果不是很熟悉可以參考我之前的文章,AndroidManifest.xml檔案中需要重新改動一下:

       <service android:name="com.example.googleservice.BookService"            android:process=":remote">            <intent-filter>               <action android:name="com.example.googleservice.BookService.AIDL"/>            </intent-filter>        </service>

  調用結果如下:

不同的App之間的調用

不同之間的調用,由於相互之間要相互連信,同樣的需要定義與服務端的aidl名相同的aidl,建立一個Android項目,然後結構如下:

 

用戶端頁面就不用寫了,就一個調用按鈕,用戶端把服務端的BookConnection拷貝過來:

   class BookServiceConnection implements ServiceConnection{private BookAIDLService bookAIDLService;public BookServiceConnection() {super();// TODO Auto-generated constructor stub}@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {// TODO Auto-generated method stub//擷取執行個體//BookService  bookService=((BookService.BookBinder)service).getCurrentService();//just  do  wo  you  want to do BookAIDLService  bookAIDLService=BookAIDLService.Stub.asInterface(service);  try {int result=bookAIDLService.sum(10, 100);Log.i("BookService", "用戶端BookAIDLService調用結果:"+result);} catch (RemoteException e) {// TODO Auto-generated catch blocke.printStackTrace();}  }@Overridepublic void onServiceDisconnected(ComponentName name) {// TODO Auto-generated method stub}        } 

  用戶端調用:

Intent binderStartIntent=new Intent("com.example.googleservice.BookService.AIDL");  connection=new BookServiceConnection();bindService(binderStartIntent, connection,Context.BIND_AUTO_CREATE);

  調用結果如下:

 

好了,至此簡單的講了一下Android中的遠程服務調用,很多概念沒有講,不會掉書袋,有興趣可以自己私下瞭解下,不同的進程之間傳遞資料,Android對這類資料的格式支援是非常有限,基本上只能傳遞Java的基礎資料型別 (Elementary Data Type)、字串、List或Map,如果想傳一個自訂的類,必須要讓這個類去實現Parcelable介面,並且要給這個類也定義一個同名的AIDL檔案。大同小異,各位可以自行研究,一不小心又周五了,哎~

 

Android中遠程Service淺析

聯繫我們

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