Android - ClassCastException - BluetoothManager 无法转换为 android.bluetooth.BluetoothAdapter 错误

Android - ClassCastException - BluetoothManager cannot be cast to android.bluetooth.BluetoothAdapter Error

我现在写的一些 BluetoothAdapter 代码有问题。我正在尝试确定导致此问题的确切原因:

04-27 08:27:35.749    7802-7802/com.engineering.yellow E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.engineering.yellow, PID: 7802
java.lang.ClassCastException: android.bluetooth.BluetoothManager cannot be cast to android.bluetooth.BluetoothAdapter
        at com.engineering.yellow.fragment.SetDevicesFragment.isNotConnected(SetDevicesFragment.java:190)
        at com.engineering.yellow.bluetooth.BluetoothConnectionTask.onPostExecute(BluetoothConnectionTask.java:117)
        at com.engineering.yellow.bluetooth.BluetoothConnectionTask.onPostExecute(BluetoothConnectionTask.java:22)
        at android.os.AsyncTask.finish(AsyncTask.java:632)
        at android.os.AsyncTask.access0(AsyncTask.java:177)
        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5579)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
        at dalvik.system.NativeStart.main(Native Method)

这是我目前使用的代码:

@Override
public void isConnected() {
    Log.d(Constants.TAG, "Connected device");
    mNumDevicesConnected++;
    if (mNumDevicesConnected == mNumDevicesSelected) {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
        mBluetoothManager.startReading(getActivity());
        getActivity().setResult(Activity.RESULT_OK);
        getActivity().finish();
    }
}

@Override
public void isNotConnected() {
   BluetoothAdapter blutoothAdapter;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        appcontext = getActivity().getApplicationContext();
        Log.i("SetDevicesFragment", "Context Val:" + appcontext);
        appcontext = getActivity().getApplicationContext();
        blutoothAdapter = (BluetoothAdapter) appcontext.getSystemService(Context.BLUETOOTH_SERVICE);
    } else {
        blutoothAdapter = BluetoothAdapter.getDefaultAdapter();
    }

    Log.i("SetDevicesFragment", "SetDevicesFragment-BluetoothConnection-MACAddress: " + blutoothAdapter.getAddress());

    if (mProgressDialog != null) {
        mProgressDialog.dismiss();
    }

    //We check to make sure we still have activity access, in case the user attempted to go back
    //before we show the dialog.
    if (getActivity() != null) {
        AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), android.R.style.Theme_Holo_Dialog));
        builder.setTitle(R.string.device_connection_error_title).setMessage(R.string.device_connection_error_message)
                .setPositiveButton(R.string.auto_shutdown_dialog_session_ended_positive_button, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        AlertDialog alertDialog = builder.create();
        breakExistingConnections();
        alertDialog.show();
    }
}

这是导致此 ClassCastException 的代码行:

blutoothAdapter = (BluetoothAdapter) appcontext.getSystemService(Context.BLUETOOTH_SERVICE);

是什么导致了这个问题?任何帮助将不胜感激。

如异常所说 Context.getSystemService(Context.BLUETOOTH_SERVICE) returns BluetoothManager 而不是 BluetoothAdapter

要获取适配器,请使用 BluetoothManager.getAdapter()

我将在此处引用 official documentation

To get a BluetoothAdapter representing the local Bluetooth adapter, when running on JELLY_BEAN_MR1 and below, call the static getDefaultAdapter() method; when running on JELLY_BEAN_MR2 and higher, retrieve it through getSystemService(String) with BLUETOOTH_SERVICE.

appcontext.getSystemService(Context.BLUETOOTH_SERVICE) returns BluetoothManager 类型的对象。您正在尝试将此对象声明或 cast 改为 BluetoothAdapter,这(在本例中)是不可能的,因此会出现错误。不过幸运的是,你可以从经理那里得到适配器。

要修复,只需更改此:

blutoothAdapter = (BluetoothAdapter) appcontext.getSystemService(Context.BLUETOOTH_SERVICE);

对此:

blutoothAdapter = ((BluetoothManager) appcontext.getSystemService(Context.BLUETOOTH_SERVICE)).getAdapter();

final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);

mbluetoothAdpt = bluetoothManager.getAdapter();