检查是否使用 Android 应用程序启用了蓝牙 [英] Check if bluetooth is enabled using an Android application

查看:23
本文介绍了检查是否使用 Android 应用程序启用了蓝牙的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查是否在使用 Android 应用程序的设备中启用了蓝牙.我使用了 .isEnabled 方法.但是有一个错误.我发现(通过注释行)错误出在 .isEnabled 方法中.你能帮我解决这个问题吗?

I want to check if bluetooth is enabled in a device using an Android application. I used the .isEnabled method. But there is an error. I found out (by commenting lines) that the error is in .isEnabled method. Can you pls help me to figure this out?

final BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();

submitButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        String status = "Bluetooth";

        if(bluetooth != null) {
            if (bluetooth.isEnabled()) {
                String mydeviceaddress = bluetooth.getAddress();
                String mydevicename = bluetooth.getName();
                status = ("Address "+ mydeviceaddress + " Name" + mydevicename);
                Toast.makeText(getApplicationContext(), "" + status + "", Toast.LENGTH_LONG).show();
            } else {
                status = ("Bluetooth not enabled");
                Toast.makeText(getApplicationContext(), "" + status + "", Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(getApplicationContext(), "" + status + "", Toast.LENGTH_LONG).show();
        }
    }
}

推荐答案

这对我来说效果最好:

/**
 * Check for Bluetooth.
 *
 * @return true if Bluetooth is available.
 */
public boolean isBluetoothAvailable() {
    final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    return bluetoothAdapter != null 
        && bluetoothAdapter.isEnabled() 
        && bluetoothAdapter.getState() == BluetoothAdapter.STATE_ON;
}

这篇关于检查是否使用 Android 应用程序启用了蓝牙的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆