zoukankan      html  css  js  c++  java
  • Android服务之Service(四)--ASDL传递复杂数据对象

      此实例与前面aidl不同之处在于,传递的数据比较复杂,传递了自定义数据对象,本实例使用到了两个数据对象Person和Pet,其中Person是作为远程调用Service传递的参数,Pet是远程Service返回调用端的数据。像Java的RMI需要将数据对象序列化一样,此数据对象也需要序列化,因此android要求远程Service传递的参数和返回值需要实现Parcelable接口。

      实例化Parcelable接口不仅需要实例化接口中的方法,而且要求在实现类中定义一个名为CREATOR,类型为Parcelable.Creator的静态Field,还要求使用ASDL代码定义这些数据类型。

      首先定义Person和Pet

       Person.aidl

    parcelable Person; 

     Person.java

    /**
     *
     */
    package org.crazyit.service;
    
    import android.os.Parcel;
    import android.os.Parcelable;
    
    /**
     * Description:
     * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
     * <br/>Copyright (C), 2001-2014, Yeeku.H.Lee
     * <br/>This program is protected by copyright laws.
     * <br/>Program Name:
     * <br/>Date:
     * @author  Yeeku.H.Lee kongyeeku@163.com
     * @version  1.0
     */
    public class Person implements Parcelable
    {
        private Integer id;
        private String name;
        private String pass;
    
    
        public Person()
        {
        }
        public Person(Integer id, String name, String pass)
        {
            super();
            this.id = id;
            this.name = name;
            this.pass = pass;
        }
        public Integer getId()
        {
            return id;
        }
        public void setId(Integer id)
        {
            this.id = id;
        }
        public String getName()
        {
            return name;
        }
        public void setName(String name)
        {
            this.name = name;
        }
        public String getPass()
        {
            return pass;
        }
        public void setPass(String pass)
        {
            this.pass = pass;
        }
        @Override
        public int hashCode()
        {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((name == null) ? 0 : name.hashCode());
            result = prime * result + ((pass == null) ? 0 : pass.hashCode());
            return result;
        }
        @Override
        public boolean equals(Object obj)
        {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Person other = (Person) obj;
            if (name == null)
            {
                if (other.name != null)
                    return false;
            }
            else if (!name.equals(other.name))
                return false;
            if (pass == null)
            {
                if (other.pass != null)
                    return false;
            }
            else if (!pass.equals(other.pass))
                return false;
            return true;
        }
    
        @Override
        public int describeContents()
        {
            return 0;
        }
    
        @Override
        public void writeToParcel(Parcel dest, int flags)
        {
            //把该对象所包含的数据写到Parcel
            dest.writeInt(id);
            dest.writeString(name);
            dest.writeString(pass);
        }
    
        // 添加一个静态成员,名为CREATOR,该对象实现了Parcelable.Creator接口
        public static final Parcelable.Creator<Person> CREATOR
            = new Parcelable.Creator<Person>()
        {
            @Override
            public Person createFromParcel(Parcel source)
            {
                // 从Parcel中读取数据,返回Person对象
                return new Person(source.readInt(), source.readString()
                    , source.readString());
            }
    
            @Override
            public Person[] newArray(int size)
            {
                return new Person[size];
            }
        };
    }

      Pet.aidl

    parcelable Pet; 
           

      Pet.Java

    /**
     *
     */
    package org.crazyit.service;
    
    import android.os.Parcel;
    import android.os.Parcelable;
    
    /**
     * Description:
     * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
     * <br/>Copyright (C), 2001-2014, Yeeku.H.Lee
     * <br/>This program is protected by copyright laws.
     * <br/>Program Name:
     * <br/>Date:
     * @author  Yeeku.H.Lee kongyeeku@163.com
     * @version  1.0
     */
    public class Pet implements Parcelable
    {
        private String name;
        private double weight;
        public Pet()
        {
        }
        public Pet(String name, double weight)
        {
            super();
            this.name = name;
            this.weight = weight;
        }
        public String getName()
        {
            return name;
        }
        public void setName(String name)
        {
            this.name = name;
        }
        public double getWeight()
        {
            return weight;
        }
        public void setWeight(double weight)
        {
            this.weight = weight;
        }
    
        @Override
        public int describeContents()
        {
            return 0;
        }
        /* (non-Javadoc)
         * @see android.os.Parcelable#writeToParcel(android.os.Parcel, int)
         */
        @Override
        public void writeToParcel(Parcel dest, int flags)
        {
            //把该对象所包含的数据写到Parcel
            dest.writeString(name);
            dest.writeDouble(weight);
        }
    
        // 添加一个静态成员,名为CREATOR,该对象实现了Parcelable.Creator接口
        public static final Parcelable.Creator<Pet> CREATOR
            = new Parcelable.Creator<Pet>()
        {
            @Override
            public Pet createFromParcel(Parcel source)
            {
                // 从Parcel中读取数据,返回Person对象
                return new Pet(source.readString()
                    , source.readDouble());
            }
    
            @Override
            public Pet[] newArray(int size)
            {
                return new Pet[size];
            }
        };
        @Override
        public String toString()
        {
            return "Pet [name=" + name + ", weight=" + weight + "]";
        }
    }

      定义自定义类后,接下来定义通信接口,定义通信接口

      IPet.aidl

    package org.crazyit.service;
    
    import org.crazyit.service.Pet;
    import org.crazyit.service.Person;
    
    /**
     * Description:
     * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> 
     * <br/>Copyright (C), 2001-2012, Yeeku.H.Lee
     * <br/>This program is protected by copyright laws.
     * <br/>Program Name:
     * <br/>Date:
     * @author  Yeeku.H.Lee kongyeeku@163.com
     * @version  1.0
     */
    interface IPet
    {
        // 定义一个Person对象作为传入参数
        List<Pet> getPets(in Person owner);
    }

    定义好远程通信接口后开始写Service

       ComplexService.Java

    /**
     *
     */
    package org.crazyit.service;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import org.crazyit.service.IPet.Stub;
    
    import android.app.Service;
    import android.content.Intent;
    import android.os.IBinder;
    import android.os.RemoteException;
    
    /**
     * Description:
     * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
     * <br/>Copyright (C), 2001-2014, Yeeku.H.Lee
     * <br/>This program is protected by copyright laws.
     * <br/>Program Name:
     * <br/>Date:
     * @author  Yeeku.H.Lee kongyeeku@163.com
     * @version  1.0
     */
    public class ComplexService extends Service
    {
        private PetBinder petBinder;
        private static Map<Person , List<Pet>> pets
            = new HashMap<Person , List<Pet>>();
        static
        {
            // 初始化pets Map集合
            ArrayList<Pet> list1 = new ArrayList<Pet>();
            list1.add(new Pet("旺财" , 4.3));
            list1.add(new Pet("来福" , 5.1));
            pets.put(new Person(1, "sun" , "sun") , list1);
            ArrayList<Pet> list2 = new ArrayList<Pet>();
            list2.add(new Pet("kitty" , 2.3));
            list2.add(new Pet("garfield" , 3.1));
            pets.put(new Person(2, "bai" , "bai") , list2);
        }
        // 继承Stub,也就是实现额IPet接口,并实现了IBinder接口
        public class PetBinder extends Stub
        {
            @Override
            public List<Pet> getPets(Person owner) throws RemoteException
            {
                // 返回Service内部的数据
                return pets.get(owner);
            }
        }
        @Override
        public void onCreate()
        {
            super.onCreate();
            petBinder = new PetBinder();
        }
        @Override
        public IBinder onBind(Intent arg0)
        {
            /* 返回catBinder对象
             * 在绑定本地Service的情况下,该catBinder对象会直接
             * 传给客户端的ServiceConnection对象
             * 的onServiceConnected方法的第二个参数;
             * 在绑定远程Service的情况下,只将catBinder对象的代理
             * 传给客户端的ServiceConnection对象
             * 的onServiceConnected方法的第二个参数;
             */
            return petBinder; //
        }
        @Override
        public void onDestroy()
        {
        }
    }

    在AndroidManifest.xml 配置此Service,则此Service已完成

      AndroidManifest.xml 

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="org.crazyit.service"
        android:versionCode="1"
        android:versionName="1.0">
        <uses-sdk
            android:minSdkVersion="10"
            android:targetSdkVersion="17" />
        <application android:icon="@drawable/ic_launcher" android:label="@string/app_name">
            <!-- 定义一个Service组件 -->
            <service android:name=".ComplexService" >
                <intent-filter>
                    <action android:name="org.crazyit.aidl.action.COMPLEX_SERVICE" />
                </intent-filter>
            </service>
        </application>
    </manifest> 

    调用端(客户端)

    在调用端需要引用服务端的 Person ,Pet两个Java文件,Person,Pet连个aidl文件和IPet.aidl文件。在写一个Service服务调用端程序即可

      ComplexClient.Java

    package org.crazyit.client;
    
    import java.util.List;
    
    import org.crazyit.service.IPet;
    import org.crazyit.service.Person;
    import org.crazyit.service.Pet;
    
    import android.app.Activity;
    import android.app.Service;
    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.ArrayAdapter;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ListView;
    
    /**
     * Description: <br/>
     * site: <a href="http://www.crazyit.org">crazyit.org</a> <br/>
     * Copyright (C), 2001-2012, Yeeku.H.Lee <br/>
     * This program is protected by copyright laws. <br/>
     * Program Name: <br/>
     * Date: 
     * @author Yeeku.H.Lee kongyeeku@163.com
     * @version 1.0
     */
    public class ComplexClient extends Activity
    {
        private IPet petService;
        private Button get;
        EditText personView;
        ListView showView;
        private ServiceConnection conn = new ServiceConnection()
        {
            @Override
            public void onServiceConnected(ComponentName name
                , IBinder service)
            {
                // 获取远程Service的onBind方法返回的对象的代理
                petService = IPet.Stub.asInterface(service);
            }
    
            @Override
            public void onServiceDisconnected(ComponentName name)
            {
                petService = null;
            }
        };
    
        @Override
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            personView = (EditText) findViewById(R.id.person);
            showView = (ListView) findViewById(R.id.show);
            get = (Button) findViewById(R.id.get);
            // 创建所需绑定的Service的Intent
            Intent intent = new Intent();
            intent.setAction("org.crazyit.aidl.action.COMPLEX_SERVICE");
            // 绑定远程Service
            bindService(intent, conn, Service.BIND_AUTO_CREATE);
            get.setOnClickListener(new OnClickListener()
            {
                @Override
                public void onClick(View arg0)
                {
                    try
                    {
                        String personName = personView.getText().toString();
                        // 调用远程Service的方法
                        List<Pet> pets = petService.getPets(new Person(1,
                            personName, personName)); //// 将程序返回的List包装成ArrayAdapter
                        ArrayAdapter<Pet> adapter = new ArrayAdapter<Pet>(
                            ComplexClient.this,
                            android.R.layout.simple_list_item_1, pets);
                        showView.setAdapter(adapter);
                    }
                    catch (RemoteException e)
                    {
                        e.printStackTrace();
                    }
                }
            });
        }
    
        @Override
        public void onDestroy()
        {
            super.onDestroy();
            // 解除绑定
            this.unbindService(conn);
        }
    }

     客户端的AndroidManifest.xml配置较简单

  • 相关阅读:
    面试技巧
    [CODEVS1116]四色问题
    [CODEVS1216]跳马问题
    [CODEVS1295]N皇后(位运算+搜索)
    [CODEVS1037]取数游戏
    [CODEVS1048]石子归并
    [NOIP2012]同余方程
    C++深入理解虚函数
    Attention Model
    faster-rcnn系列原理介绍及概念讲解
  • 原文地址:https://www.cnblogs.com/songyao/p/4142317.html
Copyright © 2011-2022 走看看