Android之——AIDL深入

來源:互聯網
上載者:User

標籤:sso   androi   click   over   csdn   parcel   cti   rri   describe   

轉載請註明出處:http://blog.csdn.net/l1028386804/article/details/47071927

在上一篇博文《Android之——AIDL小結》中,我們簡介了一下Android AIDL的使用方法,而在這篇博文中。我們將深入解說Android AIDL的使用方法。相同。在這裡我們也通過一個小範例來學習Android 中 AIDL的使用方法。

優點:多個應用程式之間建立共同的服務機制。通過AIDL在不同應用程式之間達到資料的共用和資料相互操作。

本文包含: 1 、建立AIDL 服務端。

2 、建立AIDL client。 3、client調用服務端提供的服務介面。

1、建立AIDL 服務端。

在Android的src中建立IStudentService.aidl

package com.example.studentservice;import com.example.studentservice.Student;; interface IStudentService{    Map getMap(in String test_class,in Student student);    Student getStudent(); }
Student 類是一個序列化的類,這裡使用Parcelable 介面來序列化. Student  類代碼例如以下:
package com.example.studentservice; import android.os.Parcel;import android.os.Parcelable; public class Student implements Parcelable{    private int age;    private String name;     public Student(Parcel source) {        // TODO Auto-generated constructor stub        age = source.readInt();        name = source.readString();    }     public Student() {        // TODO Auto-generated constructor stub    }     public int getAge() {        return age;    }     public void setAge(int age) {        this.age = age;    }     public String getName() {        return name;    }     public void setName(String name) {        this.name = name;    }              public static final Parcelable.Creator<Student> CREATOR = new Creator<Student>() {                 @Override        public Student[] newArray(int size) {            // TODO Auto-generated method stub            return new Student[size];        }                 @Override        public Student createFromParcel(Parcel source) {            // TODO Auto-generated method stub            return new Student(source);        }    };     @Override    public int describeContents() {        // TODO Auto-generated method stub        return 0;    }     @Override    public void writeToParcel(Parcel dest, int flags) {        // TODO Auto-generated method stub        dest.writeInt(age);        dest.writeString(name);    }  }

在這裡必須注意例如以下三點:

1.在Student 類中必須有一個靜態常量,常量名必須是CREATOR。並且CREATOR 常量的資料類型必須是 Parcelable.Creator

2.在writeToParcel 方法中須要將要序列化的值寫入到 Parcel對象中。

3.編寫完Student 為時,必須再建立一個Student.aidl 檔案,此檔案輸入下面內容:
parcelable Student; 這裡的書寫是供上面我們說過的介面   *.aidl 檔案導包時能夠找到,並通過此檔案找到Student類對象。

假設上面的步驟順利通過的話,Android 將會自己主動在gen 檔案夾下R檔案的同樣檔案夾產生一個以*.aidl 檔案命名的*.java 檔案,例如以:


順利產生成功後,我們再來編寫一個AIDL 服務類,代碼例如以下:

package com.example.studentservice;import java.util.HashMap;import java.util.Map;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.os.RemoteException;  public class StudentService extends Service{     @Override    public IBinder onBind(Intent intent) {        // TODO Auto-generated method stub        return new StudentServiceImple();    }         public class StudentServiceImple extends IStudentService.Stub {                 @Override        public Student getStudent() throws RemoteException        {            Student student = new Student();            student.setAge(25);            student.setName("Zhang san");            return student;        }         @Override        public Map getMap(String test_class, Student student)                throws RemoteException {            // TODO Auto-generated method stub              Map<String, Object> map = new HashMap<String, Object>();                map.put("class", "06109091");                map.put("age", student.getAge());                map.put("name", student.getName());                return map;         }    } }

如上代碼。StudentService服務類有一個子類並繼承自我們上面產生的*.java 檔案重寫當中我們在*.aidl 中聲明的兩個介面方法,實現了其功能。

上面IBinder 必須返回此服務類的子類對象。否則client將無法獲得服務物件。

最後,即然有服務的操作,那麼就得在manifest檔案裡注冊服務類。代碼例如以下:

<service android:name=".StudentService"  android:exported="true"  android:enabled="true"    android:process=":remote">    <intent-filter>        <action android:name="com.example.studentservice.IStudentService"></action>        </intent-filter></service>
至此,服務端就己經開發完畢了。以下接著開發客啟端。2、建立AIDL client

相同是建立一個項目,這裡要注意,須要將服務端產生成功後的gen 檔案夾下的包複製過來。放到我們建立項目的src 檔案夾下,例如以:



由於IServiceService 這個產生類。引用到了Student, 所以這裡一併將Student也複製過來。

至此,client的建立己經完成,以下我們就要利用建立的client去調用服務端的方法。

3、client調用服務端提供的服務介面

package com.example.studentclient; import com.example.studentservice.IStudentService; import android.os.Bundle;import android.os.IBinder;import android.os.RemoteException;import android.app.Activity;import android.app.AlertDialog;import android.content.ComponentName;import android.content.Context;import android.content.Intent;import android.content.ServiceConnection;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button; public class MainActivity extends Activity {    private Button btn1, btn2;     private IStudentService stuService = null;    private ServiceConnection serviceConnection = new ServiceConnection() {                 @Override        public void onServiceDisconnected(ComponentName name) {            // TODO Auto-generated method stub                     }                 @Override        public void onServiceConnected(ComponentName name, IBinder service) {            // TODO Auto-generated method stub            stuService = IStudentService.Stub.asInterface(service);        }    };              @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        btn1 = (Button)findViewById(R.id.button1);        btn2 = (Button)findViewById(R.id.button2);        btn1.setOnClickListener(new OnClickListener() {                         @Override            public void onClick(View v) {                // TODO Auto-generated method stub                bindService(new Intent("com.example.studentservice.IStudentService"),                         serviceConnection, Context.BIND_AUTO_CREATE);//;            }        });        btn2.setOnClickListener(new OnClickListener() {                         @Override            public void onClick(View v) {                // TODO Auto-generated method stub                StringBuilder sb = new StringBuilder();                try {                    if (stuService == null) {                        new AlertDialog.Builder(MainActivity.this).setTitle("Error")                        .setMessage("stuService is null").setPositiveButton(                                android.R.string.ok, null).show();                         return;                    }                    sb.append("學生名稱為:" + stuService.getStudent().getName() + "\n");                    sb.append("年齡為:" + stuService.getStudent().getAge() + "\n");                    sb.append("map 對象內容為例如以下:"                            + stuService.getMap("中國", stuService.getStudent())                                    .toString());                } catch (RemoteException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }                new AlertDialog.Builder(MainActivity.this).setTitle("調用外部服務")                        .setMessage(sb.toString()).setPositiveButton(                                android.R.string.ok, null).show();             }        });    } }
在ServiceConnetction裡面對IMyService 進行初始化。就可以操作該對象 ,該對象就能夠得到我們全部要處理的資料。

4、 小結

使用aidl 必須同一時候存在client和服務端,即client在本機上。服務端也在本機上。要使用client必須服務端事先在本機上注冊過服務。

Android之——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.