Android Studio实现跨进程调用Service (AILD Service)

AIDL(Android Interface Definition Language)是Android接口定义语言的意思,它可以用于让某个Service与多个应用程序组件之间进行跨进程通信,从而可以实现多个应用程序共享同一个Service的功能。

言归正传,今天的主题是远程Service建立AIDL进行通信,通过一个小demo来展示AIDL在Android studio中的实现:

1. 搭建了一个简单的Service框架,仅包括startService(intent),框架在后面代码中展示出来

2. 然后建立AIDL,通过点击建立AIDL文件,如图

建立好之后,出现AIDL文件如图

但是此时并没有AIDL的java文件产生,其实android studio也是带有自动生成的,只不过需要确认一些信息后才能生成。此时,我们可以在目录 build-->generated-->source-->aidl-->test-->debug下面发现还没有任何文件

此时,打开AndroidManifest.xml,确认package的值,如我这个

                                           

关键性的一步,确认aidl文件所在的包名和AndroidMainifest.xml的package名是否一致。如果一致,点击 Build-->Make Project,生成相应的java文件。如果不一致,则改aidl的包名,改成一致,再点击生成,生成效果如图。

则此时就可以在程序中通过AIDL调用远程Service的方法,实现AIDL与远程Service进行通信,代码展示如下。

该示例布局很简单 就一个按钮两个文本框,当用户单击该按钮时将会访问远程Service的数据,两个文本框用于显示获得数据

创建AIDL文件
package com.example.administrator.myapplication;

interface Icat {
    String getColor();
    double getWeight();
}


 
  
将接口暴露给客户端
package com.example.administrator.myapplication.aidl.service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;

import com.example.administrator.myapplication.Icat;

import java.util.Timer;
import java.util.TimerTask;
/*Android Studio开发环境建立aidl文件,怎么生成相应的java文件?
先在main目录下新建一个文件夹,命名为aidl,再在该目录下新建一个包,
包名跟AndroidManifest中的package同名,然后在该包下创建aidl文件,
创建完之后在build/generated/source/aidl/debug下就可以见到自动生成的java文件

/src/main/aidl/packageName/***.aidl后需要rebuild project
* */
public class AidlService extends Service {
   private CatBinder catBinder;
    Timer timer = new Timer();
    String[] colors = new String[]{
            "红色","黄色","黑色"
    };
    double[] weights = new double[]{
           2.3,2.2,3.4
    };
    private String color;
    private double weight;
    public AidlService() {
    }
    //继承stub,也就实现了Icat接口,并实现了IBinder接口
    public class CatBinder extends Icat.Stub {
        public String getColor() throws RemoteException{
            return color;
        }
        public double getWeight() throws RemoteException{
            return weight;
        }
    }

    @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];
            }
        },0,800);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return catBinder;
    }

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

客服端访问AIDLService

package com.example.administrator.myapplication.aidl.service;

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.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.administrator.myapplication.Icat;
import com.example.administrator.myapplication.mainActivity.R;

public class AidlClient extends ActionBarActivity {
    private Icat catService;
    private Button getBtn;
    private TextView color,weight;
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //获取远程Service的onBinder方法返回的对象的代理
            catService = Icat.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            catService =null;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_aidl_client_layout);
        getBtn = (Button) findViewById(R.id.aidl_btn);
        color = (TextView) findViewById(R.id.color_txt);
        weight = (TextView) findViewById(R.id.weight_txt);
        //创建所需绑定的Service的Intent
        Intent intent = new Intent();
        intent.setAction("com.example.administrator.myapplication.AIDL_SERVICE");
        //绑定远程Service
        bindService(intent,conn, Service.BIND_AUTO_CREATE);
        getBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    color.setText(catService.getColor());
                    weight.setText(catService.getWeight()+"");
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //解除绑定
        this.unbindService(conn);
    }
}


 
  





你可能感兴趣的:(Android基础知识)