BluetoothChat同步onResume Activity生命周期方法,为什么?

XMi*_*ght 5 bluetooth synchronized onresume

我正在研究蓝牙Android API,我遇到了蓝牙的例子. http://developer.android.com/resources/samples/BluetoothChat/index.html

它包含许多错误,首先是它使用API​​ 11的简单事实,但清单并不强制使用此最小API.

其他有趣的事情是在Activity生命周期方法上使用synchronized关键字,比如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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么在这里使用这个关键字?是否有任何合理的解释,或者只是编写代码的人不知道onResume将始终由同一个线程调用?或者我想念什么?

先感谢您!

pjc*_*jco 1

这似乎是一个很老的问题,但我认为可能是这样:

我的猜测是它想要小心“对话框”返回的时间。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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然而,由于它是一个示例应用程序,他们可能决定使用更简单的东西。示例应用程序并不总是遵循约定,因为其想法是演示示例所需的特定代码。有时遵循约定可能会添加大量“分散注意力”的代码。不过,您是否同意这一点取决于您。