Android 如何在活动之间切换时保持GPS打开,但在“何时”时保持GPS关闭;“家”;受压
我正试图找出使用onResume和onPause实现侦听器到位置的最佳方法。 我能做的最好的事情是在暂停时将其关闭,在恢复时重新连接。但是,当我只想让GPS在应用程序运行期间保持打开状态时,我会继续断开连接。当按下Home(主页)按钮(或其他应用程序正在中断)时,可以关闭GPS以节省电池 有什么想法吗Android 如何在活动之间切换时保持GPS打开,但在“何时”时保持GPS关闭;“家”;受压,android,gps,location,Android,Gps,Location,我正试图找出使用onResume和onPause实现侦听器到位置的最佳方法。 我能做的最好的事情是在暂停时将其关闭,在恢复时重新连接。但是,当我只想让GPS在应用程序运行期间保持打开状态时,我会继续断开连接。当按下Home(主页)按钮(或其他应用程序正在中断)时,可以关闭GPS以节省电池 有什么想法吗 谢谢。您的问题可以概括为“我如何判断我的应用程序何时移入/移出前台?”我已经在两个不同的应用程序中成功地使用了以下方法,这两个应用程序都需要识别这一点 更改活动时,您应该看到以下生命周期事件序列:
谢谢。您的问题可以概括为“我如何判断我的应用程序何时移入/移出前台?”我已经在两个不同的应用程序中成功地使用了以下方法,这两个应用程序都需要识别这一点 更改活动时,您应该看到以下生命周期事件序列:
Activity A onPause()
Activity B onCreate()
Activity B onStart()
Activity B onResume()
Activity A onStop()
只要这两个活动都是您的,您就可以创建一个singleton类来跟踪您的应用程序是否是前台应用程序
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();
}
}
只有主活动开始位置侦听器?非常优雅的解决方案!我原以为API可以解决这个问题,但如果没有它,我可以认为您的解决方案是正确的方法。我会测试它,如果它有效,我会把你的答案标记为“接受”。谢谢。你不应该在BaseActivity中的onStart()、onResume()、onPause()和onStop()中都有super(onStart)等吗?再次感谢。这很好地解决了我的问题。它只要求我将“公共”改为“受保护”,以便支持继承。感谢您随机指出需要添加的内容。