如何在活动之间切换时保持GPS开启,但在按下“主页”时关闭

时间:2013-04-14 03:00:00

标签: android gps location

我试图找出使用onResume和onPause实现Listener to location的最佳方法。 最好我不能把它关闭onPause并重新连接onResume。但是,当我想要的只是GPS在应用程序的持续时间内保持打开时,我一直在断开连接重新连接。当按下Home(或其他应用程序正在中断)时,可以关闭GPS以节省电池电量。

有什么想法吗?

感谢。

1 个答案:

答案 0 :(得分:2)

您的问题可以概括为“如何判断我的应用何时进入/退出前台?”我在两个不同的应用程序中成功使用了以下方法,这些应用程序需要能够辨别这一点。

更改活动时,您应该看到以下生命周期事件序列:

Activity A onPause()
Activity B onCreate()
Activity B onStart()
Activity B onResume()
Activity A onStop()

只要这两项活动都属于您,您就可以创建一个单一类来跟踪您的应用是否是前台应用。

public class ActivityTracker {

    private static ActivityTracker instance = new ActivityTracker();
    private boolean resumed;
    private boolean inForeground;

    private ActivityTracker() { /*no instantiation*/ }

    public static ActivityTracker getInstance() {
        return instance;
    }

    public void onActivityStarted() {
        if (!inForeground) {
            /* 
             * Started activities should be visible (though not always interact-able),
             * so you should be in the foreground here.
             *
             * Register your location listener here. 
             */
            inForeground = true;
        }
    }

    public void onActivityResumed() {
        resumed = true;
    }

    public void onActivityPaused() {
        resumed = false;
    }

    public void onActivityStopped() {
        if (!resumed) {
            /* If another one of your activities had taken the foreground, it would
             * have tripped this flag in onActivityResumed(). Since that is not the
             * case, your app is in the background.
             *
             * Unregister your location listener here.
             */
            inForeground = false;
        }
    }
}

现在创建一个与此跟踪器交互的基本活动。如果您的所有活动都扩展了此基本活动,则您的跟踪器将能够在您移动到前台或后台时告诉您。

public class BaseActivity extends Activity {
    private ActivityTracker activityTracker;

    public void onCreate(Bundle saved) {
        super.onCreate(saved);
        /* ... */
        activityTracker = ActivityTracker.getInstance();
    }

    public void onStart() {
        super.onStart();
        activityTracker.onActivityStarted();
    }

    public void onResume() {
        super.onResume();
        activityTracker.onActivityResumed();
    }

    public void onPause() {
        super.onPause();
        activityTracker.onActivityPaused();
    }

    public void onStop() {
        super.onStop();
        activityTracker.onActivityStopped();
    }
}