用AIDL 实现service 主动发送消息给activity

题目详情

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

思路

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

效果图

用AIDL 实现service 主动发送消息给activity_第1张图片

代码

两个aidl文件如下:

IGetData.aidl

import com.qunar.yuzhiyun.IClientCallBack;
interface IGetData {
    void register(IClientCallBack callback);
    void startCreateData();
}

IClientCallBack.aidl

interface IClientCallBack {
    void update(in List 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 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 adapter;
    ArrayList 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 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 weakReference;

        UpDataHandler(Activity activity){
            weakReference=new WeakReference(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) 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(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);
    }
}

你可能感兴趣的:(service,AIDL)