【发布时间】:2021-12-18 13:13:25
【问题描述】:
我正在制作一个应该连接到 Arduino HC-06 模块的 Android 应用程序。
我查看了Android Documentation 并尝试让它与提供的代码一起使用。
但是,当我尝试在三星 A32 5G 上运行代码时,所有视图都无法加载(空白屏幕),连接未建立,我从 Logcat 获得以下输出:
2021-11-04 10:25:32.798 15490-15546/com.example.carremote D/StrictMode: StrictMode policy violation: android.os.strictmode.LeakedClosableViolation: A resource was acquired at attached stack trace but never released.
我查看了该消息,对我来说这似乎是由以下代码引起的:
@Override
public void run()
{
try
{
while (true)
{
BS = BSS.accept();
Log.println(Log.INFO,TAG, "[*] Looking for Connection");
if(BS != null)
{
x = new EstablishedBTConnection(BS);
Log.println(Log.INFO, TAG, "[*] Connection established!");
x.manageConnection(1);
BSS.close();
break;
}
}
} catch (IOException e)
{
e.printStackTrace();
Log.println(Log.INFO, TAG, "[*] Connection failed!");
}
}
具体由:
BS = BSS.accept();
我不知道为什么这会给我这个消息或为什么连接失败。
如果您需要任何其他代码,我可以提供它们,并且如果这个问题是重复的(我无法找到任何类似的问题),只需用链接写评论,我会删除它。
任何帮助表示赞赏,在此先感谢!
编辑:
这是请求的其余代码:
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButtonFunctions(); //Functions to manage the Buttons
bluetoothFunctionality.run(); //Starts the Bluetooth thread
}
蓝牙线程的构造函数,直接取自 Android 文档。
public BluetoothFunctionality() throws IOException
{
// Use a temporary object that is later assigned to mmServerSocket
// because mmServerSocket is final.
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code.
tmp = BA.listenUsingRfcommWithServiceRecord(name, UUID);
} catch (IOException e) {
Log.e(TAG, "Socket's listen() method failed", e);
}
BSS = tmp;
}
EstablishedBTConnection的代码:
public class EstablishedBTConnection
{
private BluetoothSocket BS;
public EstablishedBTConnection(BluetoothSocket BS)
{
this.BS = BS;
}
public int manageConnection(int action)
{
if(action == 1)
{
try
{
BS.getOutputStream().write(50);
} catch (IOException e)
{
e.printStackTrace();
}
}
return 0;
}
}
【问题讨论】:
-
也分享你的另一段代码。
-
您从哪里执行 Runnable?在线程内部还是直接调用 run()?
-
@cincy_anddeveloper 我添加了您要求的代码,我从 onCreate() 调用运行。
-
@Danish 我已经添加了我的 onCreate() 函数,你还需要其他代码 sn-ps 吗?
标签: java android android-studio error-handling bluetooth