1

我正在开发一个为多种目的维护连接的应用程序,例如发布接收位置更新。根据 android 的做事方式和其他答案的建议,我没有覆盖在屏幕旋转时破坏和重新创建应用程序的默认 android 行为,并且在这方面做得很好。

我保持与 onRetainNonConfigurationInstance 方法的连接。问题是我想在用户按下 Home 时关闭连接,应用程序被最小化或由于其他原因失去焦点但不是在屏幕旋转时 - 因此我不能在 onPause、onStop 或 OnDestroy 中执行此操作一些检查,因为它们在配置更改时被一个接一个地调用。就像现在一样,我使用 isFinishing() 来检查应用程序是否正在关闭 - 但是用户按下 Home 的情况并不需要 isFinishing() == true (这是有道理的)。

我想到的一个解决方案是检查应用程序是否在处理连接更新的线程中具有焦点,如果一段时间没有焦点就关闭它 - 但我觉得必须有一些更好的方法来做到这一点?

在此先感谢您的时间。

(在阅读发布的答案后,编辑以清除有关活动生命周期和 onRetainNonConfigurationInstance 的内容)

4

3 回答 3

1

我终于在 Activity 中找到了 onUserLeaveHint() 的钩子方法,它至少对于我目前看到的情况来说是我想要的。也就是说,由于配置更改,连接在重新启动期间保持打开状态,但在用户按下主页或返回时关闭。因此,我最终得到的解决方案类似于下面的代码。与问题无关的所有内容都已被剪断,名称已被简化。

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (m_connection == null) {
        Connection connection = (Connection) getLastNonConfigurationInstance(); // Try to get a saved version of the connection
        if (connection != null) {
            m_connection = connection;
        }
        else {
            m_connection = new Connection(); // Else create a new one
        }
    }
}

@Override
protected void onStart() {
    super.onStart();
    // The activity is about to become visible, connect.
    if (!m_connection.isConnected())
        m_connection.connect();
}

@Override
protected void onResume() {
    super.onResume();
    // The activity has become visible (it is now "resumed").
    m_bUserLeaving = false;
}

@Override
protected void onStop() {
    super.onStop();
    // The activity is no longer visible (it is now "stopped").
    if (m_bUserLeaving && m_connection.isConnected()){ // Disconnect if we stopped because the user left
        m_connection.disconnect();
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    if (isFinishing() && m_connection.isConnected()) { // Often means that the user pressed back
        m_connection.disconnect();
    }
}

@Override
public Object onRetainNonConfigurationInstance() {
    // If we get the chance, keep our connection for later use
    return m_connection;
}

@Override
protected void onUserLeaveHint() {
    m_bUserLeaving = true;
}
于 2011-07-13T14:36:00.090 回答
0

根据我的说法,您应该处理设备旋转并保留在旋转完成后您想要维持的所有值/操作。
对于主页按钮按下,用于onPause()停止网络活动并onResume()重新启动它

于 2011-07-12T10:14:05.647 回答
0

您应该查看这篇文章以更好地了解活动生命周期及其回调。无需实现一些复杂的机制或覆盖 HOME 按钮单击。您只需在 onPause() 或 onStop() 活动回调中发布您想要在关闭应用程序时运行的所有代码。您可以在上面的链接中找到它们之间的区别。希望这可以帮助。

于 2011-07-12T10:15:58.733 回答