无法在Android 6.1中发现蓝牙设备

时间:2016-09-23 21:34:41

标签: java android android-studio bluetooth bluetooth-lowenergy

我用这个代码,这个在我的旧手机中运行[android 4.0] 但是当我使用相同的Android 6.1代码集时,它的功能不正常,由于某些原因在较新的Android版本中,它无法发现附近的蓝牙设备。我假设它是因为他们在android 6.0之后改变了一些安全权限,有人可以告诉我我该怎么做才能使这个代码在新旧设备上运行以发现附近的蓝牙设备?我已经给出了以下权限也在android manifest" android.permission.ACCESS_FINE_LOCATION"," android.permission.BLUETOOTH"," android.permission.BLUETOOTH_ADMIN" " android.permission.INTERNET对"另外我怀疑我是否应该使用蓝牙乐,因为这个代码被更新的Android版本丢弃了? 代码的部分如下所示

BluetoothAdapter adapter;
Button bton;    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_insidelogin);
    ......
    ......

    adapter = BluetoothAdapter.getDefaultAdapter();

    ......
    ......

    bton=(Button)findViewById(R.id.bton);
    bton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

    int z=1;
    if (!adapter.isEnabled()) {
          z = 0;
          scan.setText("TURN BLUETOOTH ON FIRST");
            }

          if(z==1){

                IntentFilter filter = new IntentFilter();
                filter.addAction(BluetoothDevice.ACTION_FOUND);
                filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
                                                        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
                registerReceiver(mReceiver, filter);
                adapter.startDiscovery();

            }



        }
    });     
}

然后在OnReceive的Broadcast Reciever中,我有以下代码

String action = intent.getAction();
        if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
       //discovery starts, we can show progress dialog or perform other task                 
        }

        else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action))                    
           {
            scan.setText("scan FinN");
            if(z==1) {
                adapter.startDiscovery();
            }

        } else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            //bluetooth device found
            BluetoothDevice device = (BluetoothDevice)          
            intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            String s = device.getName();
            Toast.makeText(getApplicationContext(),
            device.getAddress()+"  "+device.getName(),                 
            Toast.LENGTH_SHORT).show();

        }
    }
};

0 个答案:

没有答案