应用程序没有找到任何蓝牙设备

时间:2016-12-28 11:56:54

标签: android bluetooth

嘿伙计们我正在研究应该连接到蓝牙设备的应用程序。但是目前我正在努力解决它在我的应用程序中找不到任何蓝牙设备的问题,但是在蓝牙设置中它找到了一些。 (我的设备运行android 6.x)

我的代码:

public class MainActivity extends AppCompatActivity {

private ProgressDialog progressDialogBluetoothDiscovery;
private ListView bluetoothDevices;
private ArrayList<String> bluetoothNearbyDevices;
private BluetoothAdapter mBluetoothAdapter;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    ActionBar actionBar = getSupportActionBar();

    bluetoothDevices = (ListView) findViewById(R.id.bluetoothDevicesList);
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    IntentFilter filter = new IntentFilter();
    filter.addAction(BluetoothDevice.ACTION_FOUND);
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
    registerReceiver(bluetoothBroadcast, filter);

    bluetoothNearbyDevices = new ArrayList<>();

    final FloatingActionButton searchDevices = (FloatingActionButton) findViewById(R.id.search_devices);
    searchDevices.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            searchDevices();
        }
    });
}

@Override
public void onDestroy() {
    super.onDestroy();
    unregisterReceiver(bluetoothBroadcast);
}

private void searchDevices() {
    if (mBluetoothAdapter == null) {
        Toast.makeText(MainActivity.this, getResources().getString(R.string.bluetooth_not_supported), Toast.LENGTH_LONG).show();
        return;
    } else {
        if (!mBluetoothAdapter.isEnabled()) {
            Snackbar.make(findViewById(R.id.coordinatorLayout), getResources().getString(R.string.bluetooth_not_enabled), Snackbar.LENGTH_LONG).setAction(getResources().getString(R.string.activate_bluetooth), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBtIntent, MainActivity.CONTEXT_INCLUDE_CODE);

                }
            }).show();
        } else {
            scanForDevices();
        }
    }
}

private void scanForDevices() {
    mBluetoothAdapter.startDiscovery();
}

private final BroadcastReceiver bluetoothBroadcast = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
            if (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1) == BluetoothAdapter.STATE_ON) {
                scanForDevices();
            }
        } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
            progressDialogBluetoothDiscovery = ProgressDialog.show(MainActivity.this, getResources().getString(R.string.bluetooth_discovery_title), getResources().getString(R.string.bluetooth_discovery_message), true);
        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
            progressDialogBluetoothDiscovery.dismiss();
            ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, bluetoothNearbyDevices);
            bluetoothDevices.setAdapter(arrayAdapter);
        } else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            String deviceName = device.getName();
            String deviceHardwareAddress = device.getAddress(); // MAC address
            Toast.makeText(MainActivity.this, deviceName, Toast.LENGTH_LONG).show();
            bluetoothNearbyDevices.add(deviceName);
        }

    }

    };
}

我的清单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.package">

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
</manifest>

那么你有什么想法为什么它在我的应用程序中找不到任何设备?

1 个答案:

答案 0 :(得分:0)

你在运行什么版本的Android?如果是Android 6.x,我相信您需要为清单添加ACCESS_COURSE_LOCATION权限。

以下是运行时权限如何工作Android 6.0 Marshmallow,即:

&GT; API级别23

例如:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
    switch (ContextCompat.checkSelfPermission(getBaseContext(), Manifest.permission.ACCESS_COARSE_LOCATION)) {
        case PackageManager.PERMISSION_DENIED:
            ((TextView) new AlertDialog.Builder(this)
                    .setTitle("Runtime Permissions up ahead")
                    .setMessage("To find nearby bluetooth devices please click Allow on the runtime permissions popup." )
                    .setNeutralButton("Okay", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (ContextCompat.checkSelfPermission(getBaseContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                                ActivityCompat.requestPermissions(DeviceListActivity.this,
                                        new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                                        REQUEST_ACCESS_COARSE_LOCATION);
                            }
                        }
                    })
                    .show()
                    .findViewById(android.R.id.message))
                    .setMovementMethod(LinkMovementMethod.getInstance());       
            break;
        case PackageManager.PERMISSION_GRANTED:
            break;
    }
}
相关问题