gpt4 book ai didi

Java -> 上下文,需要表达式吗?

转载 作者:行者123 更新时间:2023-12-02 01:29:15 27 4
gpt4 key购买 nike

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

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

在我的项目中,我创建了一个按钮,用于测试该库。

*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 类继承的类中

即MainActivity 类扩展了 Activity

你可以尝试这样传递:

BluetoothSPP bt = new BluetoothSPP(MainActivity.this);

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

如果它位于 View 类或 fragment 之类的内容中,您应该尝试这样的操作:

BluetoothSPP bt = new BluetoothSPP(getContext());

关于Java -> 上下文,需要表达式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56387039/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com