2016-05-22 2 views
1

Я пытаюсь перечислить все доступные устройства поблизости в ListView.Android BluetoothDevice.Action_found широковещательная передача никогда не принималась

Мой манифест содержит разрешения для BLUETOOTH, BLUETOOTH_ADMIN и ACCESS_COARSE_LOCATION.

Моя проблема ACTION_DISCOVERY_STARTED и ACTION_DISCOVERY_FINISHED получены, но ACTION_FOUND нет. У меня есть мои Bluetooth-устройства для обнаружения Bluetooth, и устройство Bluetooth на моем телефоне может обнаружить его, но мое приложение не может. То же самое относится ко всем устройствам поблизости.

private BluetoothAdapter mBluetoothAdapter; 
private ArrayList<String> mDeviceList; 
private ListView mListView; 
private ProgressDialog progressDialog; 

private static final int REQUEST_ENABLE_BT = 1; 

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

    //list to hold all devices found 
    mDeviceList = new ArrayList<>(); 

    //list to display all devices found 
    mListView = (ListView) findViewById(R.id.availItems); 
    mListView.setAdapter(new ArrayAdapter<>(this, 
      android.R.layout.simple_list_item_1, mDeviceList)); 

    //local bluetooth device 
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 

    // If the adapter is null, then Bluetooth is not supported 
    if (mBluetoothAdapter == null) { 
     Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show(); 
    }else if(!mBluetoothAdapter.isEnabled()){ 
     Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
     startActivityForResult(enableIntent, REQUEST_ENABLE_BT); 
    } 

    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); 

    if (pairedDevices.size() > 0) { 
     for (BluetoothDevice device : pairedDevices) { 
      mDeviceList.add(device.getName() + "\n" + device.getAddress()); 
     } 
    } 

    progressDialog = new ProgressDialog(this); 
    progressDialog.setMessage("Scanning..."); 
    progressDialog.setTitle("Looking for devices..."); 
    progressDialog.setCancelable(false); 
    progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() { 
     @Override 
     public void onClick(DialogInterface dialog, int which) { 
      dialog.dismiss(); 
     } 
    }); 

    Button findButton = (Button) findViewById(R.id.findButton); 
    findButton.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      IntentFilter filter = new IntentFilter(); 

      filter.addAction(BluetoothDevice.ACTION_FOUND); 
      filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED); 
      filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); 

      registerReceiver(mReceiver, filter); 
      mBluetoothAdapter.startDiscovery(); 
     } 
    }); 
} 

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

     if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) { 
      progressDialog.show(); 
     }else if (BluetoothDevice.ACTION_FOUND.equals(action) && mBluetoothAdapter.isDiscovering()) { 
      BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
      mDeviceList.add(device.getName() + "\n" + device.getAddress()); 
     }else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { 
      progressDialog.dismiss(); 
     } 
    } 
}; 

@Override 
protected void onResume() { 
    super.onResume(); 
    registerReceiver(mReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND)); 
} 

@Override 
public void onPause() { 
    if (mBluetoothAdapter != null) { 
     if (mBluetoothAdapter.isDiscovering()) { 
      mBluetoothAdapter.cancelDiscovery(); 
     } 
    } 

    super.onPause(); 
} 

@Override 
public void onDestroy() { 
    unregisterReceiver(mReceiver); 
    mListView = null; 
    mBluetoothAdapter = null; 
    mDeviceList = null; 

    super.onDestroy(); 
} 
+0

У меня такая же проблема прямо сейчас! Вы это исправили? –

+0

Нет, я не понял, все другие связанные проблемы, которые я нашел, имели решения, которые тоже не работали для меня. – Aaron

ответ

-2

Как я сказал мой собственный вопрос:

https://stackoverflow.com/posts/comments/63810282?noredirect=1

Проблема здесь в том, что разрешение должно было быть предоставлено во время выполнения, а не только в манифесте, так как ACCESS_COARSE_LOCATION или ACCESS_FINE_LOCATION сгруппированы в группе DANGEROUS permissions.

Для этого попробуйте следующее:

  1. Запрос FINE_LOCATION (или приблизительное местонахождение) разрешение во время выполнения, так как я работал с AppCompat, я использовал метод ActivityCompat, но этот метод может быть вызван из деятельности subclassess :

    ActivityCompat.requestPermissions(this, new String[{Manifest.permission.ACCESS_FINE_LOCATION},MY_PERMISSION_REQUEST_CONSTANT); 
    
  2. Реализация onRequestPermissionsResult метод:

    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { 
        switch (requestCode) { 
         case MY_PERMISSION_REQUEST_CONSTANT: { 
          // If request is cancelled, the result arrays are empty. 
          if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 
           //permission granted! 
          } 
          return; 
         } 
        } 
    } 
    
+0

Пожалуйста, не оставляйте ссылки только на ответы на другие вопросы о переполнении стека. Вместо этого, голос/флаг, чтобы закрыть как дубликат, или, если вопрос не является дубликатом, * адаптируйте ответ на этот конкретный вопрос. * –

+0

Извините, я никогда не делал этого раньше, я пытаюсь найти свой старый вопрос на флаг, но я его не нашел .. вы можете мне помочь? –

+0

Независимо от благодарности за направление, разрешение на запуск было всем необходимым. ура – Aaron

Смежные вопросы