第二步:引入Aidl文件以及用到的类,如上面的com.chapter8.aidl包。直接从服务端里代码copy过来就OK.
第三步:修改main.xml布局文件,增加一个按钮,代码如下:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:Android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <TextView
- android:id="@+id/textview"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/hello"
- />
- <Button
- android:id="@+id/button"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="调用AIDL服务"
- />
- </LinearLayout>
- package com.chapter8.aidlclient;
- import com.chapter8.aidl.IAIDLServerService;
- import android.app.Activity;
- import android.content.ComponentName;
- import android.content.Intent;
- import android.content.ServiceConnection;
- import android.os.Bundle;
- import android.os.IBinder;
- import android.os.RemoteException;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.TextView;
- public class AidlClientActivity extends Activity {
- private TextView mTextView;
- private Button mButton;
- private IAIDLServerService mIaidlServerService = null;
- private ServiceConnection mConnection = new ServiceConnection() {
- public void onServiceDisconnected(ComponentName name) {
- mIaidlServerService = null;
- }
- public void onServiceConnected(ComponentName name, IBinder service) {
- mIaidlServerService = IAIDLServerService.Stub.asInterface(service);
- //aidl通信
- try {
- String mText = "Say hello: " + mIaidlServerService.sayHello() + "/n";
- mText += "书名: " + mIaidlServerService.getBook().getBookName()+"/n";
- mText += "价格: " + mIaidlServerService.getBook().getBookPrice();
- mTextView.setText(mText);
- } catch (RemoteException e) {
- e.printStackTrace();
- }
- }
- };
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- //初始化控件
- mTextView = (TextView)findViewById(R.id.textview);
- mButton = (Button)findViewById(R.id.button);
- //增加事件响应
- mButton.setOnClickListener(new OnClickListener(){
- public void onClick(View v) {
- //bindService
- Intent service = new Intent("com.chapter8.aidl.IAIDLServerService");
- bindService(service, mConnection,BIND_AUTO_CREATE);
- }
- });
- }
- }
Ok,上面就完整的作了一个Aidl开发的流程,有什么不对的地方希望大家多多指教,今天就讲到这里。谢谢!
