Java -> 上下文,预期表达式?

Java -> Context, Expression expected?

我正在尝试通过 Java 和 Android Studio 学习和制作 Android 应用程序。我的 Java 程度是两年前的几个小时的 youtube 学习和大学基础课程。但是我确实知道如何编码。我精通 Python.

我希望使用这个蓝牙库 (https://github.com/akexorcist/Android-BluetoothSPPLibrary),这样我就可以在 phone 和支持蓝牙的 ESP32 微控制器之间进行简单的通信。

在我的项目中,我创建了一个按钮,我将使用它来测试这个库。

*snip*
        //my button
        Button btn = findViewById(R.id.myBtn); //use R.id for the button id
        btn.setOnClickListener(new View.OnClickListener() { //button listener
            @Override
            public void onClick(View v) {
                //add whatever code here
                Log.e("my app", "log msg test"); //outputs to logcat window
                BluetoothSPP bt = new BluetoothSPP(Context);

                if(!bt.isBluetoothAvailable()) {
                    Log.e("my app", "bluetooth is not available");
                } else {
                    Log.e("my app", "bluetooth is available");
                }

            }
*snip*

我卡在了:

BluetoothSPP bt = new BluetoothSPP(Context);

上下文给我一个错误,说是预期的表达式。我查看了 Java 中的 Context 并了解为什么会这样。但是,我不知道如何实现它,更不用说这里的正确上下文了。

如果您的代码位于继承自 Activity class

的 class 中

即class 主要Activity 扩展Activity

你可以尝试这样传递:

BluetoothSPP bt = new BluetoothSPP(MainActivity.this);

(因为Activity正在实施上下文)

如果它位于视图 class 或片段之类的内容中,您应该尝试这样的操作:

BluetoothSPP bt = new BluetoothSPP(getContext());

如果是为了activity

BluetoothSPP bt = new BluetoothSPP(MainActivity.this);
or
BluetoothSPP bt = new BluetoothSPP(this);
or
BluetoothSPP bt = new BluetoothSPP(getApplicationContext());

如果是片段

BluetoothSPP bt = new BluetoothSPP(getActivty());