【问题标题】:BluetoothChat synchronized onResume Activity lifecycle method, why?BluetoothChat 同步 onResume Activity 生命周期方法,为什么?
【发布时间】:2012-01-06 09:23:11
【问题描述】:

我现在正在研究蓝牙 Android API,我遇到了 BluetoothChat 示例。 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();
        }
    }
}

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

提前谢谢你!

【问题讨论】:

  • 我也很想知道这个问题的答案...

标签: bluetooth synchronized onresume


【解决方案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
        }
    }
}

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

【讨论】:

    猜你喜欢
    • 2015-05-13
    • 1970-01-01
    • 1970-01-01
    • 2012-07-21
    • 1970-01-01
    • 2016-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多