微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法发现 BLE 设备

如何解决无法发现 BLE 设备

我有 2 部安卓手机。我从下面的代码中发现两者都支持 BLE。但手机无法相互搜索。我是否也必须在其他手机中添加额外的代码?目前,我正在 1 部手机上运行代码并打开另一部手机上的蓝牙图标。

从 OnCreate 开始,我正在使用蓝牙的运行时权限。然后调用 scanBLE() 方法。在那个ble被扫描。 1 Adapter 从基础适配器扩展而来,命名为 LeDevicelistadapter

代码
AndroidManifest.xml:

adb connect arc

BTScanActivity.java:

 <uses-permission android:name="android.permission.BLUetoOTH" />
        <uses-permission android:name="android.permission.BLUetoOTH_ADMIN" />
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
    <uses-permission-sdk-23 android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission-sdk-23 android:name="android.permission.ACCESS_COARSE_LOCATION"/>
        <uses-feature android:name="android.hardware.bluetooth_le" android:required="false"/>

activity_b_t_scan.xml:

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class BTScanActivity extends ListActivity {
    private BluetoothLeScanner bluetoothLeScanner;
    private Handler handler;
    private boolean mScanning;
    private LeDevicelistadapter mLeDevicelistadapter;
    int REQUEST_ENABLE_BT = 1;
    BluetoothManager bluetoothManager;
    BluetoothAdapter bluetoothAdapter;
    static final int REQUEST = 112;
    // Stops scanning after 10 seconds.
    private static final long SCAN_PERIOD = 10000;

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_b_t_scan);
        if (Build.VERSION.SDK_INT >= 23) {
            String[] PERMISSIONS = {Manifest.permission.BLUetoOTH,Manifest.permission.BLUetoOTH_ADMIN,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_BACKGROUND_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION};
            if (!hasPermissions(this,PERMISSIONS)) {
                ActivityCompat.requestPermissions((Activity) this,PERMISSIONS,REQUEST );
                //imagePath.setText("SDK>23,has no permission");
                Toast.makeText(this,"SDK greater than 23,has no permission",Toast.LENGTH_LONG).show();
                scanLe();

            } else {
                //do here
                //imagePath.setText("SDK>23,"SDK lesser than 23,Toast.LENGTH_LONG).show();
                scanLe();

            }
        } else {
            //do here
            //imagePath.setText("SDK<23");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Toast.makeText(this,"The app was  allowed to read your store.",Toast.LENGTH_LONG).show();
                scanLe();
            }

        }

    }
    private static boolean hasPermissions(Context context,String... permissions) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(context,permission) != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }
        return true;
    }
    @Override
    public void onRequestPermissionsResult(int requestCode,@NonNull String[] permissions,@NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode,permissions,grantResults);
        switch (requestCode) {
            case REQUEST: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //do here
                    Toast.makeText(this,Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(this,"The app was not allowed to read your store.",Toast.LENGTH_LONG).show();
                }
            }
        }
    }
    private void scanLe()
    {
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUetoOTH_LE)) {
            Toast.makeText(this,"ble_not_supported",Toast.LENGTH_SHORT).show();
            finish();
        }
        else{
            Toast.makeText(this,"ble_supported",Toast.LENGTH_SHORT).show();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                bluetoothManager = (BluetoothManager) getSystemService(Context.BLUetoOTH_SERVICE);
                bluetoothAdapter = bluetoothManager.getAdapter();
                if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
                    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBtIntent,REQUEST_ENABLE_BT);
                }
                //bluetoothLeScanner = BluetoothAdapter.getDefaultAdapter().getBluetoothLeScanner();
                handler = new Handler();
                mLeDevicelistadapter = new LeDevicelistadapter(this);
                setlistadapter(mLeDevicelistadapter);
                scanLeDevice(true);
            }
        }
    }
    private void scanLeDevice(final boolean enable) {
        if (enable) {
            // Stops scanning after a pre-defined scan period.
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mScanning = false;
                    bluetoothAdapter.stopLeScan(mLeScanCallback);
                    //invalidateOptionsMenu();
                }
            },SCAN_PERIOD);
            mScanning = true;
            bluetoothAdapter.startLeScan(mLeScanCallback);
        } else {
            mScanning = false;
            bluetoothAdapter.stopLeScan(mLeScanCallback);
        }
        //invalidateOptionsMenu();
    }
    // Device scan callback.
    private BluetoothAdapter.LeScanCallback mLeScanCallback =
            new BluetoothAdapter.LeScanCallback() {
                @Override
                public void onLeScan(final BluetoothDevice device,int RSSi,byte[] scanRecord) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //Toast.makeText(this,"adding device",Toast.LENGTH_LONG).show();
                            mLeDevicelistadapter.addDevice(device);
                            mLeDevicelistadapter.notifyDataSetChanged();
                        }
                    });
                }
            };
    static class ViewHolder {
        TextView deviceName;
        TextView deviceAddress;
        public ViewHolder(View view) {
            deviceName = (TextView)view.findViewById(R.id.device_name);
            deviceAddress = (TextView) view.findViewById(R.id.device_address);
        }
    }
    // Adapter for holding devices found through scanning.
    private class LeDevicelistadapter extends BaseAdapter {
        private ArrayList<BluetoothDevice> mLeDevices;
        //private LayoutInflater mInflator;
        private Context context;
        public LeDevicelistadapter(Context context/*,ArrayList<BluetoothDevice> items*/) {
            super();
            this.mLeDevices = new ArrayList<BluetoothDevice>();
            this.context = context;
            //mInflator = BTScanActivity.this.getLayoutInflater();
        }
        public void addDevice(BluetoothDevice device) {
            if(!mLeDevices.contains(device)) {
                mLeDevices.add(device);
            }
        }
        public BluetoothDevice getDevice(int position) {
            return mLeDevices.get(position);
        }
        public void clear() {
            mLeDevices.clear();
        }
        @Override
        public int getCount() {
            return mLeDevices.size();
        }
        @Override
        public Object getItem(int i) {
            return mLeDevices.get(i);
        }
        @Override
        public long getItemId(int i) {
            return i;
        }
        @Override
        public View getView(int i,View view,ViewGroup viewGroup) {
            ViewHolder viewHolder;
            // General ListView optimization code.
            if (view == null) {
                view = LayoutInflater.from(context).inflate(R.layout.listitem_device,viewGroup,false);
                viewHolder = new ViewHolder(view);
                /*viewHolder.deviceAddress = (TextView) view.findViewById(R.id.device_address);
                viewHolder.deviceName = (TextView) view.findViewById(R.id.device_name);*/
                view.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) view.getTag();
            }

            BluetoothDevice device = mLeDevices.get(i);
            final String deviceName = device.getName();
            if (deviceName != null && deviceName.length() > 0)
                viewHolder.deviceName.setText(deviceName);
            else
                viewHolder.deviceName.setText("R.string.unkNown_device");
            viewHolder.deviceAddress.setText(device.getAddress());
            return view;
        }
    }
}

listitem_device.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".BTScanActivity">

    <ListView android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>
    <TextView android:id="@android:id/empty"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#FF0000"
        android:text="No data"/>

</LinearLayout>

我已经阅读了来自 stackoverflow 的用户评论。现在我正在另一部手机上做蓝牙广告。然后我还是无法通过蓝牙发现手机。我使用的代码如下。

代码
MainActivity.java:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <TextView android:id="@+id/device_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="24dp"/>
    <TextView android:id="@+id/device_address"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="12dp"/>
</LinearLayout>

我做错了什么?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。