我尝试扫描新设备无法扫描Marshmallow OS上的设备,但它在棒棒糖操作系统中工作正常

时间:2017-01-12 06:57:42

标签: android bluetooth

public class search_Bluetooth extends AppCompatActivity implements   View.OnClickListener {
      SharedPreferences devices;
      Button btnScanDevice;
      private BluetoothAdapter b_adapter;
      protected static final int DISCOVERY_REQUEST = 1;
      private BluetoothDevice remoteDevice;
      BroadcastReceiver bluetoothState = new BroadcastReceiver() {
          @Override
          public void onReceive(Context context, Intent intent) {
                String stateExtra = BluetoothAdapter.EXTRA_STATE;
                int state = intent.getIntExtra(stateExtra,-1);
              switch(state)
              {
                  case(BluetoothAdapter.STATE_TURNING_ON): {
                      Toast.makeText(getApplicationContext(), "Turning On Bluetooth..!", Toast.LENGTH_LONG).show();
                      break;
                  }
                  case(BluetoothAdapter.STATE_ON):{
                              Toast.makeText(getApplicationContext(), "Bluetooth is On..!", Toast.LENGTH_LONG).show();
                              break;
                   }
              }
          }
      };
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search__bluetooth);
    setTitle("");
    btnScanDevice = (Button)findViewById(R.id.scan_devices);
    btnScanDevice.setOnClickListener(this);
}

@Override
public void onClick(View view) {
    switch (view.getId()) {

        case R.id.scan_devices:
               b_adapter = BluetoothAdapter.getDefaultAdapter();
               String scanModeChanged = BluetoothAdapter.ACTION_SCAN_MODE_CHANGED;
               String beDiscoverable = BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE;

                IntentFilter filter  = new IntentFilter(scanModeChanged);
                registerReceiver(bluetoothState,filter);

                startActivityForResult(new Intent(beDiscoverable),DISCOVERY_REQUEST);

                break;


        }
}
@Override
protected void onActivityResult(int request_code,int result_code,Intent data)
{
    if(request_code==DISCOVERY_REQUEST)
    {
        Toast.makeText(getApplicationContext(),"Discovering in Progress..!",Toast.LENGTH_LONG).show();

        findDevices();
    }
    else
    {
        Toast.makeText(getApplicationContext(),"Discovering in Progress Device Not Found..!",Toast.LENGTH_LONG).show();
    }
}

private void findDevices() {

    String lastUsedRemoteDevice = getLastUsedRemoteDevices();
    if(lastUsedRemoteDevice != null)
    {
        Toast.makeText(getApplicationContext(),"Checking for known paired devices..!"+lastUsedRemoteDevice,Toast.LENGTH_LONG).show();
        Set<BluetoothDevice> pairedDevices = b_adapter.getBondedDevices();
            for(BluetoothDevice pairedDevice : pairedDevices)
            {
                if(pairedDevice.getAddress().equals(lastUsedRemoteDevice))
                {
                    Toast.makeText(getApplicationContext(),"Found devices..!"+pairedDevice.getName()+"@"+lastUsedRemoteDevice,Toast.LENGTH_LONG).show();
                    remoteDevice = pairedDevice;
                }
            }
    }
    if(remoteDevice == null) {
        Toast.makeText(getApplicationContext(), "Starting Discovery For Remote devices..!", Toast.LENGTH_LONG).show();
        if (b_adapter.startDiscovery()) {
            Toast.makeText(getApplicationContext(), "Discovery Therad Started Scaning For devices..!", Toast.LENGTH_LONG).show();
            registerReceiver(discoveryResult, new IntentFilter(BluetoothDevice.ACTION_FOUND));
        }

    }

}
BroadcastReceiver discoveryResult =new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
            String remoteDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
            BluetoothDevice remoteDevice;
            remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            Toast.makeText(getApplicationContext(),"Discoverable..!"+remoteDeviceName,Toast.LENGTH_LONG).show();
            Log.d("Discoverd Divices","============>"+remoteDeviceName);
    }
};

private String getLastUsedRemoteDevices() {
    devices = getPreferences(MODE_PRIVATE);
    String result = devices.getString("LAST REMOTE DEVICE ADDRESS",null);
    Log.d("Result","================>"+result);
    return result;
} }

无法呼叫&#39; BroadcastReceiver discoveryResult = new BroadcastReceiver()&#39;没有得到这个功能的任何回应。该应用程序进入if(remoteDevice == null)条件,但无法调用&#39; BroadcastReceiver discoveryResult = new BroadcastReceiver()。

2 个答案:

答案 0 :(得分:0)

在您的活动onCreate()方法中注册广播:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_layout);
    your_activity_context.registerReceiver(discoveryResult, new IntentFilter(your_bluetooth_intentfilter));
    ..
    ...
    ....
  }

不要忘记在活动周期取消注册/注册:

@Override
protected void onResume() {
    super.onResume();
    your_activity_context.registerReceiver(discoveryResult, new IntentFilter(your_bluetooth_intentfilter));

}

@Override
protected void onPause() {
    super.onPause();
    your_activity_context.unregisterReceiver(discoveryResult);

}

答案 1 :(得分:0)

我在我的代码中添加了以下代码片段,它适用于marshmallow感谢您的答案。

  if(remoteDevice == null) {
       // Toast.makeText(getApplicationContext(), "Starting Discovery For Remote devices..!", Toast.LENGTH_LONG).show();
        int MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 1;
        ActivityCompat.requestPermissions(this, new String[]{ACCESS_COARSE_LOCATION},MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION);
        if (b_adapter.startDiscovery()) {

                 registerReceiver(discoveryResult, new IntentFilter(BluetoothDevice.ACTION_FOUND));
             }
        else{
            Toast.makeText(getApplicationContext(), "Problem With Discovering Devices..!", Toast.LENGTH_LONG).show();
        }

    }