初识Android之(二)- 实现Service AIDL小Demo

IDE

JDK1.7.0_80
Android Studio 2.0
Android 5.1-API22

什么是AIDL?

AIDL是 Android Interface definition language的缩写,一看就明白,它是一种android内部进程通信接口的描述语言,通过它我们可以定义进程间的通信接口
IPC:Inter Process Communication :内部进程通信

AIDL参数介绍

不需要import的类型:

Java基本数据类型  String、List、Map、CharSequence

需要import的类型

其他全部类型,包括同包下的类

AIDL使用

: a) 新建服务端工程IntentService,创建ICat.aidl文件,定义接口

IntentService工程下的ICat.aidl

// ICat.aidl
package com.example.ubuntu.intentservice;

// Declare any non-default types here with import statements
interface ICat {
    String getColor();
    double getWeight();
}

: b) 实现IDE自动生成的ICat.java,注意编译一下

: c) 创建远程Service文件AidlService,并返回实现ICat.Stub类的对象

IntentService工程下的AndroidManifest.xml

<service
    android:name=".AidlService"
    android:enabled="true"
    android:exported="true">
    <intent-filter>
        <action android:name="com.example.ubuntu.intentservice.aidl.action.AIDL_SERVICE" />
    </intent-filter>
</service>

IntentService工程下的MainActivity.java

Button aidl = (Button)findViewById(R.id.aidl);
final Intent intent6 = new Intent();
intent6.setAction("com.example.ubuntu.intentservice.aidl.action.AIDL_SERVICE");
intent6.setPackage(this.getPackageName());
System.out.println("---Aidl---"+this.getPackageName());
aidl.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        startService(intent6);
    }
});

IntentService工程下的AidlService.java

package com.example.ubuntu.intentservice;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import java.util.Timer;
import java.util.TimerTask;

public class AidlService extends Service
{

    private CatBinder catBinder;

    Timer timer = new Timer();

    String[] colors = new String[]
            {
                    "红色","黄色","黑色"
            };
    double[] weights = new double[]
            {
                    2.3,3.1,1.58
            };

    private String color;
    private double weight;

    //继承Stub,也就实现了ICat接口,并实现了IBinder接口
    public class CatBinder extends ICat.Stub
    {

        @Override
        public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException
        {

        }

        @Override
        public String getColor() throws RemoteException
        {
            return color;
        }

        @Override
        public double getWeight() throws RemoteException
        {
            return weight;
        }
    }

    public AidlService()
    {
    }

    @Override
    public void onCreate()
    {
        super.onCreate();
        catBinder = new CatBinder();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                //随机地改变Service组件内color,weight属性的值
                int rand = (int)(Math.random() * 3 );
                color = colors[rand];
                weight = weights[rand];
                System.out.println("---Aidl---"+rand);
            }
        },0,800);

        Log.d("---AidlService---","start");
    }


    @Override
    public IBinder onBind(Intent intent)
    {
            /*返回catBinder对象
            * 本地Service的onBind()会直接把IBinder对象本身
            * 传给客户端的ServiceConnection对象的onServiceConnected方法的第二个参数
            * 远程Service的onBind()会直接吧IBinder对象代理
            * 传给客户端的ServiceConnection对象的onServiceConnected方法的第二个参数
            * */
            return catBinder;
    }

    @Override
    public void onDestroy()
    {
        timer.cancel();
    }
}

: d) 新建客户端工程AidlClient,复制第1步中的ICat.aidl文件到远端客户端应用中

注意一下几点:

  • 在新的AidlClient工程中新建一个包,包名为“com.example.ubuntu.intentservice”这个包名必须和之前服务端工程中的ICat.aidl文件所在的包名一致;

  • 再次编译一下,生成ICat.java文件;

: e) 在客户端中成功调用到远程Service

AidlClient工程下的MainActivity.java

package com.example.ubuntu.aidlclient;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.example.ubuntu.intentservice.ICat;

public class MainActivity extends AppCompatActivity {
    public static final String TAG = "---AidlClient---";
    private ICat catService;
    private Button get;
    EditText color,weight;

    //定义一个ServiceConnection对象
    private ServiceConnection conn = new ServiceConnection()
    {
        //当该Activity与Service连接成功时回调该方法
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder)
        {
            Log.d(TAG , "Service Connected");
            //获取远程Service的OnBind方法所返回的对象的代理
            catService = ICat.Stub.asInterface(iBinder);
        }

        //当该Activity与Service断开连接时回调该方法
        @Override
        public void onServiceDisconnected(ComponentName componentName)
        {
            Log.d(TAG , "Service DisConnected");
            catService = null;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        get = (Button)findViewById(R.id.get);
        color = (EditText)findViewById(R.id.color);
        weight = (EditText)findViewById(R.id.weight);

        //创建所需绑定的Service的Intent
        final Intent intent = new Intent();
        intent.setAction("com.example.ubuntu.intentservice.aidl.action.AIDL_SERVICE");
//        intent.setPackage(this.getPackageName());
        intent.setPackage("com.example.ubuntu.intentservice");
        System.out.println("---Aidl---"+this.getPackageName());
        //绑定远程Service
        bindService(intent,conn, Service.BIND_AUTO_CREATE);
        get.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                try
                {
                    //获取并显示远程Service的状态
                    color.setText(catService.getColor());
                    weight.setText(catService.getWeight()+" ");
                }catch (RemoteException e)
                {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        this.unbindService(conn);
    }

}

注意:

  • 首先启动IntentService开启Service ,再运行客户端程序
  • 绑定远程Service之前,intent需要注明包名
    即intent.setPackage(“com.example.ubuntu.intentservice”);

AidlClient

查阅文档

猜你喜欢

转载自blog.csdn.net/sage_wang/article/details/51982416