How to Scan other Bluetooth devices in android Studio

Diese Seite verwendet Cookies. Durch die Nutzung unserer Seite erklären Sie sich damit einverstanden, dass wir Cookies setzen. Weitere Informationen

  • How to Scan other Bluetooth devices in android Studio

    Hello everybody,

    I am not completely new to Android development, but for a few days now I have been trying to develop a Bluetooth app that can scan more devices like in my mobile phone but through my app. All tutorials that I have found so far do not work at all.
    I am already posting my code from the android studio. I can list paired devices, but the scan cannot.

    If someone has a good experience with Bluetooth here, I ask them for help. I thank you in advance

    Java-Quellcode

    1. package cm.rulan.distcovid.ui.home;
    2. import android.app.AlertDialog;
    3. import android.app.ProgressDialog;
    4. import android.bluetooth.BluetoothAdapter;
    5. import android.bluetooth.BluetoothDevice;
    6. import android.content.BroadcastReceiver;
    7. import android.content.Context;
    8. import android.content.DialogInterface;
    9. import android.content.Intent;
    10. import android.content.IntentFilter;
    11. import android.content.pm.PackageManager;
    12. import android.os.Bundle;
    13. import android.os.Handler;
    14. import android.util.Log;
    15. import android.view.LayoutInflater;
    16. import android.view.View;
    17. import android.view.ViewGroup;
    18. import android.widget.ArrayAdapter;
    19. import android.widget.Button;
    20. import android.widget.ListView;
    21. import android.widget.TextView;
    22. import android.widget.Toast;
    23. import androidx.annotation.NonNull;
    24. import androidx.annotation.Nullable;
    25. import androidx.fragment.app.Fragment;
    26. import androidx.lifecycle.Observer;
    27. import androidx.lifecycle.ViewModelProvider;
    28. import java.util.ArrayList;
    29. import java.util.Set;
    30. import cm.rulan.distcovid.R;
    31. public class HomeFragment extends Fragment {
    32. private static final String TAG = "Home";
    33. private static final int REQUEST_ENABLE_BT = 1;
    34. private static final int REQUEST_DISCOVERABLE_BT = 0;
    35. Set<BluetoothDevice> pairedDevices;
    36. private HomeViewModel homeViewModel;
    37. private BluetoothAdapter bluethoothadapter;
    38. private Button btnpairedDev, btnscan;
    39. private ListView pairedDev;
    40. private ArrayList list;
    41. private ArrayList btdevnew;
    42. private TextView tview;
    43. private ProgressDialog mProgressDlg;
    44. IntentFilter filter ;
    45. BroadcastReceiver mReceiver ;
    46. public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    47. homeViewModel = new ViewModelProvider(this).get(HomeViewModel.class);
    48. View root = inflater.inflate(R.layout.fragment_home, container, false);
    49. homeViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
    50. @Override
    51. public void onChanged(@Nullable String s) {
    52. //textView.setText(s);
    53. }
    54. });
    55. pairedDev = root.findViewById(R.id.listView);
    56. list = new ArrayList<>();
    57. btdevnew = new ArrayList<>();
    58. tview = root.findViewById(R.id.textView);
    59. btnpairedDev = root.findViewById(R.id.list);
    60. btnscan = root.findViewById(R.id.scanBT);
    61. mProgressDlg = new ProgressDialog(getContext());
    62. mReceiver = new BroadcastReceiver() {
    63. @Override
    64. public void onReceive(Context context, Intent intent) {
    65. String action = intent.getAction();
    66. switch (action) {
    67. case BluetoothAdapter.ACTION_DISCOVERY_STARTED:
    68. mProgressDlg = new ProgressDialog(getContext());
    69. mProgressDlg.setTitle(getContext().getString(R.string.searchForNewBluetoothDevices_titel));
    70. mProgressDlg.setMessage(getContext().getString(R.string.searchForNewBluetoothDevices_msg));
    71. mProgressDlg.setIndeterminate(true);
    72. mProgressDlg.show();
    73. break;
    74. case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
    75. mProgressDlg.cancel();
    76. //activity.setFoundLabel();
    77. break;
    78. case BluetoothDevice.ACTION_FOUND:
    79. BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
    80. final ArrayAdapter mNewDevicesArrayAdapter = new ArrayAdapter<String>(getContext(), R.layout.device_adapter_view);
    81. mNewDevicesArrayAdapter.add(device);
    82. pairedDev.setAdapter(mNewDevicesArrayAdapter);
    83. Log.d(TAG, "device" +device);
    84. break;
    85. }
    86. }
    87. };
    88. bluethoothadapter = BluetoothAdapter.getDefaultAdapter();
    89. if (bluethoothadapter == null) {
    90. // Device doesn't support Bluetooth
    91. AlertDialog.Builder dialbuild = new AlertDialog.Builder(getContext());
    92. dialbuild.setTitle("Nicht Kompatibel")
    93. .setMessage("Your phone does not support Bluetooth")
    94. .setPositiveButton("Exit", new DialogInterface.OnClickListener() {
    95. public void onClick(DialogInterface dialog, int which) {
    96. System.exit(0);
    97. }
    98. })
    99. .setIcon(android.R.drawable.ic_dialog_alert)
    100. .show();
    101. }
    102. if (!bluethoothadapter.isEnabled()) {
    103. Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    104. startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    105. } else {
    106. Toast.makeText(this.getContext(), "Bluetooth is already On", Toast.LENGTH_SHORT).show();
    107. }
    108. if (!getContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
    109. Toast.makeText(getContext(), R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
    110. getActivity().finish();
    111. }
    112. return root;
    113. }
    114. @Override
    115. public void onPause() {
    116. if (bluethoothadapter != null) {
    117. if (bluethoothadapter.isDiscovering()) {
    118. bluethoothadapter.cancelDiscovery();
    119. }
    120. }
    121. super.onPause();
    122. }
    123. @Override
    124. public void onActivityResult(int requestCode, int resultCode, Intent data)
    125. {
    126. super.onActivityResult(requestCode, resultCode, data);
    127. if (requestCode == REQUEST_ENABLE_BT)
    128. {
    129. if (resultCode == 0)
    130. {
    131. // If the resultCode is 0, the user selected "No" when prompt to
    132. // allow the app to enable bluetooth.
    133. // You may want to display a dialog explaining what would happen if
    134. // the user doesn't enable bluetooth.
    135. Toast.makeText(getContext(), "The user decided to deny bluetooth access", Toast.LENGTH_LONG).show();
    136. }
    137. else
    138. Log.i(TAG, "User allowed bluetooth access!");
    139. }
    140. }
    141. @Override
    142. public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    143. super.onViewCreated(view, savedInstanceState);
    144. //listPairedDevices();
    145. btnpairedDev.setOnClickListener(new View.OnClickListener() {
    146. @Override
    147. public void onClick(View v) {
    148. listPairedDevices();
    149. }
    150. });
    151. btnscan.setOnClickListener(new View.OnClickListener() {
    152. @Override
    153. public void onClick(View v) {
    154. ScanBluetoothDevices();
    155. //scanLeDevice(true);
    156. }
    157. });
    158. }
    159. public void listPairedDevices() {
    160. pairedDevices = bluethoothadapter.getBondedDevices();
    161. if (pairedDevices.size() > 0) {
    162. // Es gibt gekoppelte Geräte. Gib den name und adresse
    163. // von jedem gekoppelten Gerät.
    164. for (BluetoothDevice device : pairedDevices) {
    165. String deviceName = device.getName(); // device Name
    166. String deviceHardwareAddress = device.getAddress(); // MAC address
    167. list.add(deviceName + "\t" + "\t" + deviceHardwareAddress);
    168. Log.d("Device Name: ", "deviceName " + deviceName);
    169. Log.d("Device Hardwareaddr: ", "deviceHardwareAdresse " + deviceHardwareAddress);
    170. Toast.makeText(this.getContext(), "Showing Paired Devices", Toast.LENGTH_SHORT).show();
    171. final ArrayAdapter adapter = new ArrayAdapter(this.getContext(), android.R.layout.simple_list_item_1, list);
    172. pairedDev.setAdapter(adapter);
    173. }
    174. }
    175. }
    176. private void ScanBluetoothDevices() {
    177. // If we're already discovering, stop it
    178. if (bluethoothadapter.isDiscovering()) {
    179. bluethoothadapter.cancelDiscovery();
    180. } else {
    181. // Request discover from BluetoothAdapter
    182. // Create a BroadcastReceiver for ACTION_FOUND.
    183. //discovery starts, we can show progress dialog or perform
    184. //other tasks
    185. filter = new IntentFilter();
    186. filter.addAction(BluetoothDevice.ACTION_FOUND);
    187. filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    188. filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    189. this.getActivity().registerReceiver(mReceiver, filter);
    190. bluethoothadapter.startDiscovery();
    191. }
    192. }
    193. }
    194. After the execution of the program, by pressing the scan button we have this output:
    195. D / ViewRootImpl @ ef507c7 [MainActivity]: ViewPostIme pointer 0
    196. D / ViewRootImpl @ ef507c7 [MainActivity]: ViewPostIme pointer 1
    197. D / BluetoothAdapter: startDiscovery
    198. W / libEGL: EGLNativeWindowType 0x78f6244250 disconnect failed
    199. D / ViewRootImpl @ eb5ee08 [Toast]: dispatchDetachedFromWindow
    200. D / InputTransport: Input channel destroyed: 'b8fe85f', fd = 73s
    201. it says startdiscovery after there is nothing
    Alles anzeigen

    Dieser Beitrag wurde bereits 1 mal editiert, zuletzt von las ()