简体   繁体   English

为什么我的 Android 应用程序没有扫描蓝牙设备?

[英]Why my Android App is not scanning Bluetooth device?

  • In my Bluetooth App I have created two buttons one for getting paired devices and the other to scan the Bluetooth device.在我的蓝牙应用程序中,我创建了两个按钮,一个用于获取配对设备,另一个用于扫描蓝牙设备。 When I click the scan button Toast message shows no device found, the code always goes to else part in my broadcast receiver.当我单击扫描按钮 Toast 消息显示未找到设备时,代码总是转到我的广播接收器中的 else 部分。 Can someone explain to me what's happening* ** MainActivity.java **有人可以向我解释发生了什么* ** 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** ** 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** ** 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** ** 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>

You must declare the service inside aplication in Manifest.xml like this:您必须像这样在 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM