android - 如何在 Activity 之间切换时保持 GPS 打开,但在按下 "home"时关闭 GPS

标签 android gps location

我正在尝试找出使用 onResume 和 onPause 实现监听器到位置的最佳方法。 最好我不能在 onPause 上关闭它并在 onResume 上重新连接。但当我只想让 GPS 在应用程序运行期间保持打开状态时,我会不断地断开连接并重新连接。当按下 Home 键(或其他应用程序中断)时,可以关闭 GPS 以节省电池。

有什么想法吗?

谢谢。

最佳答案

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

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

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

只要这两个 Activity 都是您的,您就可以创建一个单例类来跟踪您的应用程序是否是前台应用程序。

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;
        }
    }
}

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

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();
    }
}

关于android - 如何在 Activity 之间切换时保持 GPS 打开,但在按下 "home"时关闭 GPS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15995311/

相关文章:

android - 状态栏上的通知图标显示为白框

尝试向 Android 中的类对象添加数据时出现 java.lang.NullPointerException

cordova - Dart的PhoneGap GeoLocation

Flutter Location 包不会返回 iOS 上的当前位置

iphone - 后台模式下的iOS区域监控

java - 扩展的 MultipartEntity 没有正确写出 Streams

java - Android如何在屏幕截图中捕获阴影

android - iOS/Android GPS 电量消耗?

iphone - GPS 位置在我的应用程序的 iphone 中打开/关闭

java - 无论我身在何处,我的应用程序都会返回相同的位置