• 使用AIDL将接口暴露给客户端(远程绑定Service)


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

    import jww.mediaprovidertest.ICat.Stub;
    import android.app.Service;
    import android.content.Intent;
    import android.os.IBinder;
    import android.os.RemoteException;

    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 Stub{

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

        @Override
        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];
          System.out.println("------"+rand);
          }
        }, 0 ,800);
      }

      @Override
      public IBinder onBind(Intent intent) {
        /*
        * 返回catBinder对象
        * 在绑定本地Service的情况下,该catBinder对象会直接
        * 传给客户端的ServiceConnection对象
        * 的onServiceConnected方法的第二个参数
        * 在绑定远程Service的情况下,只将catBinder对象的代理
        * 传给客户端的ServiceConnection对象
        * 的onServiceConnected方法的第二个参数
        */
        return catBinder;
      }

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

    }

  • 相关阅读:
    7个技巧,帮你完美搞定网页首图设计(必看)
    听说你想跳槽?ARM和PowerPC分析,你知道吗?(速进)
    C语言必学7大步骤!(必看)
    单片机电机必不可少的30条常识!你知道吗?(欢迎大家进行补充)
    单片机外围电路设计攻略(终结版)! 不看哭一年!
    3天”速成“嵌入式之后,我明白了六件事!!!
    前端就不需要掌握算法与数据结构?
    嵌入式软件必学知识总结!
    字节跳动2017客户端工程师实习生笔试题-第四题
    并查集
  • 原文地址:https://www.cnblogs.com/jiww/p/5604114.html
Copyright © 2020-2023  润新知