Android Studio startDiscovery()不从通知面板点击蓝牙按钮就不能启动并立即结束

ijnw1ujt  于 2022-11-25  发布在  Android
关注(0)|答案(1)|浏览(85)

在android 12 api 31我运行这个应用程序,它不能正常工作,我想找到附近设备的名称,但蓝牙设备没有启动,直到我点击蓝牙按钮,从通知面板和日志中,它显示发现开始,并给出了另一个日志,显示发现完成,而不搜索设备.

package com.aditya.bluetoothfinder;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
ListView listView;
TextView statusTextView;
Button searchButton;
BluetoothAdapter bluetoothAdapter;//The BluetoothAdapter is required for any and all Bluetooth activity

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

    listView = findViewById(R.id.listView);
    statusTextView = findViewById(R.id.statusTextView);
    searchButton = findViewById(R.id.searchButton);

    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}

public void searchClicked(View view) {
    if (bluetoothSupported()) {
        openBluetooth();
    } else {
        statusTextView.setText("Bluetooth Not Supported");
    }
}

//This function will check that the bluetooth is supported on the device or not
public boolean bluetoothSupported() {
    return getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH);
}

//This function opens the bluetooth
public void openBluetooth() {
    if (!bluetoothAdapter.isEnabled()) {
        Intent enableBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
            requestThePermissons();
        } else {
            startActivityForResult(enableBluetoothIntent, 1);
        }
    } else {
        searchBluetoothDevices();
    }
}

//This function request the permission
private void requestThePermissons() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { //if we don't have any permission
        requestPermissionLauncher.launch(Manifest.permission.BLUETOOTH_CONNECT);
    } else { //if we already have permissionn of bluetooth connect
        searchBluetoothDevices();

    }
}

//This is a callback which give us the information that the user gave us the permission or not
private final ActivityResultLauncher<String> requestPermissionLauncher = registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
    if (isGranted) {
        // Permission is granted. Continue the action or workflow in your
        searchBluetoothDevices();
    } else { //If user declined the permission request
        Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
    }
});

//This is the function for searching bluetooth devices
public void searchBluetoothDevices() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
        Toast.makeText(this, "Unable to locate bluetooth device", Toast.LENGTH_SHORT).show();
        requestPermissions(new String[]{Manifest.permission.BLUETOOTH_SCAN},1);
    } else {
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(receiver, filter);

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "Unable to locate", Toast.LENGTH_SHORT).show();
        }
bluetoothAdapter.startDiscovery();
        statusTextView.setText("Searching...");
        searchButton.setEnabled(false);
    }
}

当我调用bluetoothAdapter.startDiscovery();
它显示D/蓝牙适配器:启动发现():呼叫者:com.aditya.蓝牙finder
但不显示日志发现已开始,直到我单击通知面板中的蓝牙按钮,然后它给出另一个日志发现已完成

//This function give us the details of the bluetooth device if found
BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            Log.i("this", "Device Found");
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                requestThePermissons();
                Toast.makeText(MainActivity.this, "Unable to find", Toast.LENGTH_SHORT).show();
            } else {
                String deviceName = device.getName();
                String deviceHardwareAddress = device.getAddress(); // MAC address
                String text = (String) statusTextView.getText();
                statusTextView.setText(text + "\n" +deviceName + "\n" + deviceHardwareAddress);

            }
        } else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
            Log.i("this", "Discovery Finished");

            statusTextView.setText("Finished");
            searchButton.setEnabled(true);
        } else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
            Log.i("this", "Discovery started");
            Toast.makeText(MainActivity.this, "Started", Toast.LENGTH_SHORT).show();
        }
    }
};
}

在AndroidManifest.xml中使用的权限

<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-feature android:name="android.hardware.bluetooth" android:required="true"/>
5w9g7ksd

5w9g7ksd1#

您还必须获得用户的定位权限,并且用户必须打开定位服务才能查看其他蓝牙设备。

相关问题