android USB拔插检测

最近改bug,需要检测USB的插入和拔出的状态。查了一堆网上的东西,花里胡哨,还没有作用,要么就是不满足我的需求。

后面在源码中看到了谷歌的方法,记录一下。

        // 添加广播
        filter = new IntentFilter();
        filter.addAction(Intent.ACTION_BATTERY_CHANGED);
        activity.registerReceiver(mTetherChangeReceiver, filter);

 

     if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {// 判断USB插入拔出
                final int oldPlugType = mPlugType;
                mPlugType = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 1);
                final boolean plugged = mPlugType != 0;
                final boolean oldPlugged = oldPlugType != 0;
                if ((!plugged) && (oldPlugged != plugged)) {
                     //USB被拔出
                } else if (plugged) {
                    if (oldPlugged != plugged ) {
                      //USB插入
                    }
                }
            }

你可能感兴趣的:(安卓)