安卓进程之间的通讯

来源:互联网 发布:派克中性笔 知乎 编辑:程序博客网 时间:2024/06/11 05:50

安卓进程之间的通讯,需要用到aidl。先在服务端创建一个接口,里面包含方法。

// DataService.aidlpackage com.animee.aidl;// Declare any non-default types here with import statements//这里写了两个方法。interface DataService {    int getValues(int a);    String getInfo();}

写完之后就构建以下,会自己创建一个类。这里还需要用到服务。

package com.animee.aidl_server;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.os.RemoteException;import com.animee.aidl.DataService;public class AIDLService extends Service {    //调用自动生成的类。    DataService.Stub binder = new DataService.Stub() {        @Override        public int getValues(int a) throws RemoteException {            return a+34;        }    //这里就是刚才我们自己在接口里面写的方法。        @Override        public String getInfo() throws RemoteException {            return "天苍苍,野茫茫,一枝梨花压海棠!";        }    };    @Override    public IBinder onBind(Intent intent) {        // TODO: Return the communication channel to the service.        return  binder;    }}

//服务端的主函数里面什么都不需要写。接下来是客户端的东西,首先,把服务端的aidl文件全部复制过去,然后构建。

package com.animee.aidl_client;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.Toast;import com.animee.aidl.DataService;public class MainActivity extends AppCompatActivity {    private DataService dataService;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);    }    //绑定服务传的参数    ServiceConnection conn = new ServiceConnection() {        @Override        //获取aidl对象。        public void onServiceConnected(ComponentName name, IBinder service) {            dataService = DataService.Stub.asInterface(service);        }        @Override        public void onServiceDisconnected(ComponentName name) {        }    };    //这里进行绑定服务    public void bind(View view) {        Intent intent = new Intent("com.aidl.server");        intent.setPackage("com.animee.aidl_server");        boolean b = bindService(intent, conn, BIND_AUTO_CREATE);//        Log.i("tag11","成功没有啊?"+b);        Toast.makeText(this,"成功没有啊?"+b,Toast.LENGTH_LONG).show();    }        //获取数据    public void getdata(View view) throws RemoteException {        String info = dataService.getInfo();        int values = dataService.getValues(11);        Log.i("tag11","info=="+info+",values=="+values);        Toast.makeText(this,"info=="+info+",values=="+values,Toast.LENGTH_LONG).show();    }    @Override    protected void onDestroy() {        super.onDestroy();        unbindService(conn);    }}
原创粉丝点击