Android中使用aidl进行跨进程通信(server和activity)交互【转】

来源:赵克立 分类: Android 标签:无发布时间:2018-05-08 16:10:22浏览:741
版权声明:
本文为博主学习过程中整理发布,如有侵权请告知
温馨提示:
技术类文章有它的时效性,请留意文章更新时间以及软件的版本
更新时间:
2018-05-08 16:49:06

题目详情

1、实现一个activity和一个service,它们在不同的进程 
2、service每隔3-5秒钟产生10条数据(10个数字,每个数字随即为1-100),然后发送给activity 
3、并且activity用listview显示这些数据

思路

实现两个aidl接口,一个用于通知service产生数据,一个用于 service 通知activity更新数据

效果图

这里写图片描述

代码

两个aidl文件如下:

IGetData.aidl

import com.ank.wx.IClientCallBack;
// Declare any non-default types here with import statements
interface IGetData {
    /**
     * Demonstrates some basic types that you can use as parameters
     * and return values in AIDL.
     */
    void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
            double aDouble, String aString);
        void register(IClientCallBack callback);
        void startCreateData();
}

IClientCallBack.aidl

// Declare any non-default types here with import statements
interface IClientCallBack {
    /**
     * Demonstrates some basic types that you can use as parameters
     * and return values in AIDL.
     */
    void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
            double aDouble, String aString);
     void update(in List<String> arrayList);
}

DataSourceService.java

public class DataSourceService extends Service {
    volatile boolean needToRun;    public DataSourceService() {
    }    @Override
    public IBinder onBind(Intent intent) {        return  binder;
    }    @Override
    public boolean onUnbind(Intent intent) {
        needToRun=false;        return super.onUnbind(intent);
    }
    IGetData.Stub binder=new IGetData.Stub() {
        IClientCallBack callBack;        @Override
        public void register(IClientCallBack callback) throws RemoteException {            this.callBack=callback;
        }        @Override
        public void startCreateData() throws RemoteException {
            needToRun=true;            final ArrayList<String> arrayList=new ArrayList<>();
            Thread thread=new Thread(new Runnable() {                @Override
                public void run() {                    int interval;                    while (needToRun){
                        arrayList.clear();
                        interval=3+  (int)(Math.random()*3);
                        Log.i("time",""+interval);                        try {
                            Thread.sleep(interval*1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }                        for(int i=0;i<10;i++){
                            Random random=new Random();
                            arrayList.add((int)(random.nextInt(100))+"");
                        }                        if (callBack!=null)                            try {                                //数据推送到客户端(Activity)
                                callBack.update(arrayList);
                            } catch (RemoteException e) {
                                e.printStackTrace();
                            }
                    }
                }
            });
            thread.start();
        }
    };
}

MainActivity.java

public class MainActivity extends AppCompatActivity {
    ListView lvNumber;
    IGetData iGetData;
    ArrayAdapter<String> adapter;
    ArrayList<String> stringList;
    Intent intent;
    ServiceConnection connection=new ServiceConnection() {        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            iGetData=IGetData.Stub.asInterface(service);            try {
                iGetData.register(new IClientCallBack.Stub(){                    @Override
                    public void update(List<String> arrayList) throws RemoteException {
                        Message message=new Message();
                        message.obj=arrayList;
                        handler.sendMessage(message);
                    }
                });
                iGetData.startCreateData();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };
    Handler handler=new  UpDataHandler(MainActivity.this);    static class UpDataHandler extends Handler{
        WeakReference<Activity> weakReference;
        UpDataHandler(Activity activity){
            weakReference=new WeakReference<Activity>(activity);
        }        @Override
        public void handleMessage(Message msg) {            super.handleMessage(msg);
            MainActivity activity= (MainActivity) weakReference.get();            if(activity!=null) {
                activity.stringList.clear();
                activity.stringList.addAll((ArrayList<String>) msg.obj);
                activity.adapter.notifyDataSetChanged();
            }
        }
    }    @Override
    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lvNumber= (ListView) findViewById(R.id.lvNumber);
        stringList=new ArrayList<>();
        stringList.add("1");
        stringList.add("2");
        stringList.add("3");
        adapter=new ArrayAdapter<String>(this,R.layout.support_simple_spinner_dropdown_item,stringList);
        lvNumber.setAdapter(adapter);
        intent=new Intent(MainActivity.this,DataSourceService.class);
        bindService(intent,connection, Context.BIND_AUTO_CREATE);
    }    @Override
    protected void onPause() {        super.onPause();
        unbindService(connection);
        stopService(intent);
    }
}



微信号:kelicom QQ群:215861553 紧急求助须知
留下一点心意, :)
点击更换验证码
留言