-1

我运行我的代码并旋转手机几次,然后转储内存并对其进行分析。

下面是我的代码:

private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
            LogUtils.e("111");
        }
    };
    private boolean mScanning = false;
    private BluetoothManager bm;
    private void scanLeDevice(final boolean enable) {
        LogUtils.e(enable);
        try {
            if (enable) {
                mScanning = true;
                if(bm.getAdapter()!=null)bm.getAdapter().startLeScan(mLeScanCallback);
            } else {
                mScanning = false;
                if(bm.getAdapter()!=null)bm.getAdapter().stopLeScan(mLeScanCallback);
            }
            invalidateOptionsMenu();
        }catch (Throwable e){

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        scanLeDevice(false);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initStage();
    }
    @Override
    protected void initStage() {
        bm = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
        scanLeDevice(true);
    }

java堆: java堆

4

1 回答 1

2

LeScanCallback 持有对 Activity 的引用。我在测试 Google 提供的 BluetoothLeGatt 示例时遇到了这个问题。我将扫描代码复制到我的应用程序中,突然发现大量泄漏发生。

我通过将扫描回调包装到一个静态类中来解决它,该类然后持有对活动的弱引用。就像谷歌在使用处理程序时推荐的一样。像这样:

private final BluetoothAdapter.LeScanCallback mLeScanCallback = new LeScanCallbackClass(this);

private static final class LeScanCallbackClass implements BluetoothAdapter.LeScanCallback {

    private String TAG = makeLogTag(LeScanCallbackClass.class.getName());
    private final WeakReference<TrackActivity> mAct;

    public LeScanCallbackClass(TrackActivity act) {
        mAct = new WeakReference<>(act);
    }

    @Override
    public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
        LOGI(TAG, String.format("BLE LeScan Result: %s", device.getAddress()));
        final TrackActivity act = mAct.get();
        act.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                        mLeDeviceListAdapter.addDevice(device);
                        mLeDeviceListAdapter.notifyDataSetChanged();
            }
        });
        act.sendNotification();
    }
}
于 2016-04-08T03:41:03.053 回答