你好,游客 登录 注册 搜索
背景:
阅读新闻

Android AIDL的重新理解

[日期:2013-04-12] 来源:Linux社区  作者:ab_ba [字体:大 中 小]

4.客户端代码:(绑定远程Service,然后获取Binder对象,然后进行数据交换和方法调用)

package com.wenix.Androidclient;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.wenix.service.aidl.IPerson;

public class MainActivity extends Activity {
    private static final String TAG = "MainActivity";
    private class PersonServiceConnection implements ServiceConnection{
 @Override
 public void onServiceConnected(ComponentName cmp, IBinder service) {
    //客户端在这个回调方法中获得Binder对象
    IPerson p = IPerson.Stub.asInterface(service);
    try {
  //这里调用AIDL规定的接口来获取数据
  Log.i(TAG, p.getPerson(1).toString());
    } catch (RemoteException e) {
  e.printStackTrace();
    }
 }
 @Override
 public void onServiceDisconnected(ComponentName name) {
   
 }
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //界面采用动态布局
        LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        ll.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
       
        LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        Button btn = new Button(this);
        btn.setLayoutParams(params);
        btn.setText("获取Service数据");
        btn.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
  //启动相应的Service,由于是远程Service,所以不能使用显示Intent
  Intent service = new Intent("com.wenix.intent.action.AIDL_SERVICE");
  PersonServiceConnection conn = new PersonServiceConnection();
  bindService(service, conn, Context.BIND_AUTO_CREATE);
    }
 });
        TextView tv = new TextView(this);
        tv.setLayoutParams(params);
        ll.addView(btn);
        ll.addView(tv);
        setContentView(ll);
    }
}

工程彻底完成,然后我们运行后点击Button,就可以看到获取的数据:

只需掌握整个流程,AIDL就可以很容易的使用。后期会加入一些使用AIDL的具体实例。

更多Android相关信息见Android 专题页面 http://www.linuxidc.com/topicnews.aspx?tid=11

linux
相关资讯       Android AIDL 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款