我现在正在研究蓝牙 Android API,并且遇到了 BluetoothChat 示例。http://developer.android.com/resources/samples/BluetoothChat/index.html http://developer.android.com/resources/samples/BluetoothChat/index.html
它包含许多错误,首先一个简单的事实是它使用 API 11,但清单并不强制使用这个最低 API。
其他有趣的事情是在 Activity 生命周期方法上使用同步关键字,例如 onResume:
@Override
public synchronized void onResume() {
super.onResume();
if(D) Log.e(TAG, "+ ON RESUME +");
// Performing this check in onResume() covers the case in which BT was
// not enabled during onStart(), so we were paused to enable it...
// onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
if (mChatService != null) {
// Only if the state is STATE_NONE, do we know that we haven't started already
if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
// Start the Bluetooth chat services
mChatService.start();
}
}
}
为什么在那里使用这个关键字?有没有任何合理的解释,或者只是编写代码的人不知道 onResume 将始终由同一线程调用?或者我错过了什么?
先感谢您!
这似乎是一个很老的问题,但我认为可能是这样:
我的猜测是它想要小心“对话框”返回的时间。 BluetoothChat 示例使用对话框(以及类似覆盖对话框的活动)来启用蓝牙、启用发现和启动配对/连接。
我不确定这一点,但我怀疑存在一个错误,其中不同的线程返回到主 Activity 并导致了如何处理的混乱onResume
.
他们可能应该做的是synchronize
对象上的块并使用标志来确定状态。这样,意图、状态和功能就更加清晰——并且应用程序知道它应该做什么onResume
;
也许是这样的:
//class fields
private Object myLockObj = new Object();
private boolean isPausedForPairing = false;
public void onResume()
{
super.onResume();
synchronized (myLockObj)
{
if (isPausedForPairing)
{
//handle a "pairing" onResume
}
}
}
然而,由于它是一个示例应用程序,他们可能决定使用更简单的东西。示例应用程序并不总是遵循约定,因为其想法是演示示例所需的特定代码。有时遵循约定可能会添加大量“分散注意力”的代码。不过,您是否同意这一点取决于您。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)