2017-09-06 1 views
0

Je suis nouveau dans le développement d'applications Android. J'essaye de programmer une application qui peut découvrir des dispositifs bluetooth et les montre dans une liste. J'utilise un BroadcastReceiver pour ajouter les périphériques détectés à la liste, mais depuis que j'ai ajouté le BroadcastReceiver, l'application continue à se bloquer au démarrage.Android: Bluetooth App se bloque au démarrage

J'ai testé l'application sur un OnePlus 3 (Android 7.1.1) et un Huawei P8 Lite (Android 6).

Mon code: MainActivity.java

package com.example.jeroen.testbluetooth; 

import android.bluetooth.BluetoothAdapter; 
import android.bluetooth.BluetoothDevice; 
import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.content.IntentFilter; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.ArrayAdapter; 
import android.widget.ListView; 

import java.util.ArrayList; 
import java.util.Set; 

public class MainActivity extends AppCompatActivity { 

    private final static int REQUEST_ENABLE_BT = 1; // static variable for intent to start BT, must be locally declared 
    private final ArrayAdapter<String> btArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1); 
    private ListView listView = (ListView) findViewById(R.id.ListView); // findViewById(int id), id must match with id of view in layout file 

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


    // callback function must have view parameter 
    public void BtnConnectToDevice(View view) { 

     // check if BT is supported 
     BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // get bluetooth adapter of this device 
     if (mBluetoothAdapter == null) { 
      // Device does not support Bluetooth 
      // app shuts down 
      // TODO show message for user 
      finishAndRemoveTask(); 
     } 

     // check if BT is enabled, if not turn on 
     // startActivityForResult returns result of request (successful or cancelled) 
     if (!mBluetoothAdapter.isEnabled()) { 
      Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); // create Intent to enable bluetooth 
      startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); // TODO no result in the moment 
     } 

     // get all paired devices as set (set = unsorted array/list) 
     Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); 

     // add names and addresses of paired devices to array 
     if (pairedDevices.size() > 0) { 
      // There are paired devices. Get the name and address of each paired device. 
      // for loop every element of pairedDevices is passed and temporary copied into "device" 
      for (BluetoothDevice device : pairedDevices) { 
       String deviceName = device.getName(); 
       String deviceHardwareAddress = device.getAddress(); // MAC address 

       // add items to adapter 
       btArrayAdapter.add(deviceName + "\n" 
         + deviceHardwareAddress); 
      } 
     } 

     // if scanning already running, stop 
     if (mBluetoothAdapter.isDiscovering()) { 
      mBluetoothAdapter.cancelDiscovery(); 
     } 

     // search for devices 
     mBluetoothAdapter.startDiscovery(); 

     // Register the broadcast receiver 
     IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
     registerReceiver(mReceiver, filter); 

     // TODO do something with the list 

     // show array in listView 
     // connect btArrayAdapter to ListView 
     // ListView listView = (ListView) findViewById(R.id.ListView); // findViewById(int id), id must match with id of view in layout file 
//  listView.setAdapter(btArrayAdapter); 

    } 


    @Override 
    protected void onDestroy() { 
     // Don't forget to unregister the ACTION_FOUND receiver. 
     unregisterReceiver(mReceiver); 

     // super.onDestroy(); 
    } 



    private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 
     public void onReceive(Context context, Intent intent) { 
      String action = intent.getAction(); 
      if (BluetoothDevice.ACTION_FOUND.equals(action)) { 
       // A Bluetooth device was found 
       // Getting device information from the intent 
       BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 

       // add newly discovered devices to list 
       String deviceName = device.getName(); 
       String deviceHardwareAddress = device.getAddress(); // MAC address 

       // add items to adapter 
       btArrayAdapter.add(deviceName + "\n" 
         + deviceHardwareAddress); 
      } 
     } 
    }; 

} 

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?> 
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     xmlns:app="http://schemas.android.com/apk/res-auto" 
     xmlns:tools="http://schemas.android.com/tools" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     tools:context="com.example.jeroen.testbluetooth.MainActivity"> 

     <Button 
      android:id="@+id/BtnConnectToDevice" 
      android:layout_width="144dp" 
      android:layout_height="48dp" 
      android:layout_marginLeft="120dp" 
      android:layout_marginStart="120dp" 
      android:layout_marginTop="16dp" 
      android:elevation="0dp" 
      android:onClick="BtnConnectToDevice" 
      android:text="Connect" 
      app:layout_constraintLeft_toLeftOf="parent" 
      app:layout_constraintTop_toTopOf="parent" /> 

     <ListView 
      android:id="@+id/ListView" 
      android:layout_width="368dp" 
      android:layout_height="437dp" 
      android:layout_marginBottom="10dp" 
      app:layout_constraintBottom_toBottomOf="parent" 
      app:layout_constraintLeft_toLeftOf="parent" 
      app:layout_constraintRight_toRightOf="parent" /> 

</android.support.constraint.ConstraintLayout> 

AndroidManifest.xml:

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

    // permissions 
    <uses-permission android:name="android.permission.BLUETOOTH" /> // Allows applications to connect to paired bluetooth devices 
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> // Allows applications to discover and pair bluetooth devices 
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/> 
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> 
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> 

    <application 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:roundIcon="@mipmap/ic_launcher_round" 
     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> 

</manifest> 

Lorsque je supprime le BroadcastReceiver l'application commence très bien , mais sans cela, je ne peux pas scanner les appareils.

J'apprécierais que quelqu'un puisse m'aider. Si vous avez besoin d'informations supplémentaires, n'hésitez pas à demander.

Sincères salutations,

Jeroen

+1

Veuillez coller les journaux de plantage. – Godather

Répondre

0

Voici mon code de travail pour rechercher les appareils

mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
    mBluetoothAdapter.startDiscovery(); 
    mReceiver = new BroadcastReceiver() { 
    public void onReceive(Context context, Intent intent) { 
    String action = intent.getAction(); 

    //Finding devices 
    if (BluetoothDevice.ACTION_FOUND.equals(action)) 
    { 
    // Get the BluetoothDevice object from the Intent 
    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 


//Here you get scan device info 
String DeviveName=device.getName(); 


    } 
    else { 

    if (mainActivity!=null)mainActivity.status.setText("Status:No device found"); 
    } 
    } 
    }; 

    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
    registerReceiver(mReceiver, filter); 
+0

Nous vous remercions de votre aide. Cela a fonctionné sur Android 6 au moins. –

+0

Vérifiez la permission avant ce code –

+0

Je l'ai fait. J'ai ajouté des autorisations suivantes: BLUETOOTH, BLUETOOTH_ADMIN, ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION –

0

MainActivity.java

public class MainActivity extends AppCompatActivity { 
     private final static int REQUEST_ENABLE_BT = 1; // static variable for intent to start BT, must be locally declared 
     private ArrayAdapter<String> btArrayAdapter ; 
     private ListView listView ; // findViewById(int id), id must match with id of view in layout file 

     @Override 
     protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activimain); 
      if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) 
      ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION}, 1); 

      listView = (ListView) findViewById(R.id.ListView); 
      btArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1); 

     } 


// callback function must have view parameter 
     public void BtnConnectToDevice(View view) { 

    // check if BT is supported 
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // get bluetooth adapter of this device 
    if (mBluetoothAdapter == null) { 
     // Device does not support Bluetooth 
     // app shuts down 
     // TODO show message for user 
     finishAndRemoveTask(); 
    } 

    // check if BT is enabled, if not turn on 
    // startActivityForResult returns result of request (successful or cancelled) 
    if (!mBluetoothAdapter.isEnabled()) { 
     Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); // create Intent to enable bluetooth 
     startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); // TODO no result in the moment 
    } 

    // get all paired devices as set (set = unsorted array/list) 
    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); 

    // add names and addresses of paired devices to array 
    if (pairedDevices.size() > 0) { 
     // There are paired devices. Get the name and address of each paired device. 
     // for loop every element of pairedDevices is passed and temporary copied into "device" 
     for (BluetoothDevice device : pairedDevices) { 
      String deviceName = device.getName(); 
      String deviceHardwareAddress = device.getAddress(); // MAC address 

      // add items to adapter 
      btArrayAdapter.add(deviceName + "\n" 
        + deviceHardwareAddress); 
     } 
    } 

    // if scanning already running, stop 
    if (mBluetoothAdapter.isDiscovering()) { 
     mBluetoothAdapter.cancelDiscovery(); 
    } 

    // search for devices 
    mBluetoothAdapter.startDiscovery(); 

    // Register the broadcast receiver 
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
    registerReceiver(mReceiver, filter); 

    // TODO do something with the list 

    // show array in listView 
    // connect btArrayAdapter to ListView 
    //ListView listView = (ListView) findViewById(R.id.ListView); // findViewById(int id), id must match with id of view in layout file 
    listView.setAdapter(btArrayAdapter); 

} 

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

@Override 
protected void onDestroy() { 
    // Don't forget to unregister the ACTION_FOUND receiver. 
    unregisterReceiver(mReceiver); 

    super.onDestroy(); 
} 



public BroadcastReceiver mReceiver = new BroadcastReceiver() { 
    public void onReceive(Context context, Intent intent) { 
     String action = intent.getAction(); 
     if (BluetoothDevice.ACTION_FOUND.equals(action)) { 
      // A Bluetooth device was found 
      // Getting device information from the intent 
      BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 

      // add newly discovered devices to list 
      String deviceName = device.getName(); 
      String deviceHardwareAddress = device.getAddress(); // MAC address 

      // add items to adapter 
      btArrayAdapter.add(deviceName + "\n" 
        + deviceHardwareAddress); 
     } 
    } 
}; 

} 

manifest.xml

 <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" /> 

     <permission android:name="android.permission.BLUETOOTH" android:label="BLUETOOTH" /> 
     <permission android:name="android.permission.BLUETOOTH_ADMIN" /> 
     <permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
     <permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 
+0

Merci, cela a fonctionné. Au moins sur Android 6. Je l'ai essayé sur Android 7 aussi, mais ils semblent changer l'API. Ça ne marchera pas. Quelque chose avec startLeScan(). Je vais essayer cela suivant. –