java.lang.ClassCastException: android.os.BinderProxy cannot be cast 解决方法

问题简介:

在Application中绑定Service时出现 "ClassCastException"。

问题还原:

Application中的部分代码:

    @Override
    public void onCreate() {
        super.onCreate();
        bindService(new Intent(this, Service.class), conn, Service.BIND_AUTO_CREATE);
    }
    /**
     * 与服务的连接
     */
    private ServiceConnection conn = new ServiceConnection() {
      
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            if (service!=null) {
                // 获取Binder
                binder = ((Service.MyBinder) service);
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

 

展示的这些代码就差不多可以讲解了,错误的出现指向下面的这句:

binder = ((Service.MyBinder) service)

 

懵逼中...我这是正常转换啊,怎么就报错了呢!!!

然后就开始漫长的百度过程...n久之后,找到了。

原来OnCreate()方法会执行多次,这两次调用的进程有些问题,所以会出现"ClassCastException"这个错误!

既然找到了,那就上解决的方法吧:

首先要增加两个方法:

   /**
     * 判断该进程是否是app进程
     * @return
     */
    public boolean isAppProcess() {
        String processName = getProcessName();
        if (processName == null || !processName.equalsIgnoreCase(this.getPackageName())) {
            return false;
        }else {
            return true;
        }
    }

    /**
     * 获取运行该方法的进程的进程名
     * @return 进程名称
     */
    public String getProcessName() {
        int processId = android.os.Process.myPid();
        String processName = null;
        ActivityManager manager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        Iterator iterator = manager.getRunningAppProcesses().iterator();
        while (iterator.hasNext()) {
            ActivityManager.RunningAppProcessInfo processInfo = (ActivityManager.RunningAppProcessInfo) (iterator.next());
            try {
                if (processInfo.pid == processId) {
                    processName = processInfo.processName;
                    return processName;
                }
            } catch (Exception e) {
//                LogD(e.getMessage())
            }
        }
        return processName;
    }

然后在Application中的OnCreate()方法中使用就可以了:

  @Override
  public void onCreate() {
      super.onCreate();
      if (isAppProcess()) {
          bindService(new Intent(getApplicationContext(), Service.class), conn, Service.BIND_AUTO_CREATE);
      }
  }

 

弄完这些,异常就不会再出现了,呼...点个赞吧,xiongdei!

 

你可能感兴趣的:(Android,-,Exception)