Почему мое приложение для Android не сканирует устройство Bluetooth?

  • В моем приложении Bluetooth я создал две кнопки: одну для получения сопряженных устройств, а другую для сканирования устройства Bluetooth. Когда я нажимаю кнопку сканирования, всплывающее сообщение показывает, что устройство не найдено, код всегда переходит в другую часть моего широковещательного приемника. Может кто-нибудь объяснить мне, что происходит * ** MainActivity.java **
package com.example.broadcast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
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.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

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

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final int REQUEST_ENABLE_BT = 2;

    private Button scanButton;
    private Button discoverButton;
    private MyBroadcast broadcast;
    private MyBroadcastdiscover broadcastdiscover;
    public BluetoothAdapter bluetoothAdapter;
    public Set<BluetoothDevice> pairedDevices;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        broadcast=new MyBroadcast();
        broadcastdiscover=new MyBroadcastdiscover();
         bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
         scanButton=(Button) findViewById(R.id.scan_btn);
         discoverButton=(Button) findViewById(R.id.discover_btn);
         scanButton.setOnClickListener(this);
        discoverButton.setOnClickListener(this);
        if (bluetoothAdapter == null) {
            // Device doesn't support Bluetooth
            Toast.makeText(getApplicationContext(),"Device doesn't support bluetooth", Toast.LENGTH_LONG).show();
        }
        if (!bluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }




    }

    @Override
    protected void onStart() {
        super.onStart();
        IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(broadcast, filter);
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(broadcast);
        unregisterReceiver(broadcastdiscover);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        unregisterReceiver(broadcast);
        unregisterReceiver(broadcastdiscover);
    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onClick(View v) {

        switch (v.getId())
        {
            case R.id.scan_btn:
            {
                pairedDevices = bluetoothAdapter.getBondedDevices();
                if (pairedDevices.size() > 0) {
                    // There are paired devices. Get the name and address of each paired device.
                    for (BluetoothDevice device : pairedDevices) {
                        String deviceName = device.getName();
                        String deviceHardwareAddress = device.getAddress(); // MAC address
                        ArrayList list = new ArrayList();
                        list.add(device.getName());
                        Toast.makeText(getApplicationContext(),deviceName,Toast.LENGTH_LONG).show();

                    }
                break;
                }
            }

            case R.id.discover_btn:
            {
                Toast.makeText(getApplicationContext(),"SCAN",Toast.LENGTH_LONG).show();
               /* Intent discoverableIntent =
                        new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 150);
                startActivity(discoverableIntent);*/

                if (bluetoothAdapter.isDiscovering()) {
                    bluetoothAdapter.cancelDiscovery();
                    checkBTPermission();
                    bluetoothAdapter.startDiscovery();
                    registerReceiver(broadcastdiscover,new IntentFilter(bluetoothAdapter.ACTION_DISCOVERY_STARTED));
                    registerReceiver(broadcastdiscover,new IntentFilter(bluetoothAdapter.ACTION_DISCOVERY_FINISHED));
                }

                if(!bluetoothAdapter.isDiscovering())
                {
                    bluetoothAdapter.startDiscovery();
                    registerReceiver(broadcastdiscover,new IntentFilter(bluetoothAdapter.ACTION_DISCOVERY_STARTED));
                    registerReceiver(broadcastdiscover,new IntentFilter(bluetoothAdapter.ACTION_DISCOVERY_FINISHED));
                }
                break;
            }
        }


    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void checkBTPermission() {
        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
            int permissionCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
            permissionCheck += this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
            if (permissionCheck != 0) {

                this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); //Any number
            }
        }else{
            Log.d("TAG", "checkBTPermissions: No need to check permissions. SDK version < LOLLIPOP.");
        }
    }
}

** MyBroadcastdiscover.java**

package com.example.broadcast;

import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import java.util.ArrayList;

import static android.content.ContentValues.TAG;

public class MyBroadcastdiscover extends BroadcastReceiver {
    public ArrayList<BluetoothDevice> mBTDevices=new ArrayList<>();
    @Override
    public void onReceive(Context context, Intent intent) {

        String action = intent.getAction();
       // Toast.makeText(context,action,Toast.LENGTH_LONG).show();

       if(action.equals(BluetoothDevice.ACTION_FOUND))
       {
            // Discovery has found a device. Get the BluetoothDevice
            // object and its info from the Intent.
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            String deviceName = device.getName();
            String deviceHardwareAddress = device.getAddress(); // MAC address
            Toast.makeText(context,deviceName,Toast.LENGTH_LONG).show();
           Log.d("TAG",deviceHardwareAddress);


        }
        else {

            Toast.makeText(context,"NO DEVICE YET FOuND",Toast.LENGTH_LONG).show();
            Log.d("TAG","DEVICE NOT FOUND");
        }



    }
}

**AndroidManifest.xml**

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.broadcast">
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

    <!-- If your app targets Android 9 or lower, you can declare
         ACCESS_COARSE_LOCATION instead. -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_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/Theme.Broadcast">
        <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>

** Activitymain.xml **

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.119" />

    <Button
        android:id="@+id/scan_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="108dp"
        android:text="@string/scanDevice"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <Button
        android:id="@+id/discover_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="92dp"
        android:text="@string/scanningdevice"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/scan_btn" />

</androidx.constraintlayout.widget.ConstraintLayout>

person Kathiravan    schedule 27.02.2021    source источник


Ответы (1)


Вы должны объявить службу внутри приложения в Manifest.xml следующим образом:

<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/Theme.Broadcast">
...
        <receiver android:name="com.example.broadcast.MyBroadcastdiscover" >
            <intent-filter>
                <action android:name="android.bluetooth.device.action.ACTION_FOUND" />
            </intent-filter>
        </receiver>

</application>
person dmastra    schedule 27.02.2021
comment
Спасибо, но я не смог просканировать устройство даже после объявления об обслуживании, ни одно найденное устройство не приходит само по себе. Застрял в этом в течение длительного времени, пожалуйста, помогите мне. - person Kathiravan; 28.02.2021