【问题标题】:Battery drains even with app off screen, could it be Location Services doing it?即使应用程序关闭屏幕,电池也会耗尽,这可能是位置服务在做的吗?
【发布时间】:2012-10-01 06:14:15
【问题描述】:

我运行我的应用程序,该应用程序使用 GPS 和蓝牙,然后点击返回按钮使其离开屏幕。我通过 LogCat 验证了应用程序的 onDestroy 被调用。 OnDestroy 删除位置侦听器并关闭我的应用程序的蓝牙服务。 8 小时后我查看手机,电池电量已消耗了一半,我的应用程序负责根据手机的电池使用屏幕。如果我使用手机的设置菜单强制停止应用程序,则不会发生这种情况。所以我的问题是:除了移除监听器来阻止定位服务消耗电力之外,我还需要做更多的事情吗?这是我唯一能想到的,当应用程序应该处于休眠状态时,电池电量会消耗到那种程度。

这是我的 onStart(),我打开位置相关的东西和蓝牙:

@Override
public void onStart() {
    super.onStart();

    if(D_GEN) Log.d(TAG, "MainActivity onStart, adding location listeners");

    // If BT is not on, request that it be enabled.
    // setupBluetooth() will then be called during onActivityResult
    if (!mBluetoothAdapter.isEnabled()) {
        Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        // Otherwise, setup the Bluetooth session
    } else {
        if (mBluetoothService == null) 
            setupBluetooth();
    }
    // Define listeners that respond to location updates
    mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, GPS_UPDATE_INTERVAL, 0, this);    
    mLocationManager.addGpsStatusListener(this);
    mLocationManager.addNmeaListener(this);

}

这是我的 onDestroy() 我删除它们的地方:

public void onDestroy() {
    super.onDestroy();
    if(D_GEN) Log.d(TAG, "MainActivity onDestroy, removing update listeners");
    // Remove the location updates
    if(mLocationManager != null) {
        mLocationManager.removeUpdates(this); 
        mLocationManager.removeGpsStatusListener(this);
        mLocationManager.removeNmeaListener(this);
    }
    if(D_GEN) Log.d(TAG, "MainActivity onDestroy, finished removing update listeners");
    if(D_GEN) Log.d(TAG, "MainActivity onDestroy, stopping Bluetooth");
    stopBluetooth();
    if(D_GEN) Log.d(TAG, "MainActivity onDestroy finished");
}

【问题讨论】:

    标签: android


    【解决方案1】:

    您在 OnStart 上添加 GPS 侦听器和蓝牙,并在 onDestroy() 上删除它们。如果您的活动进入停止状态(因为您启动了另一个活动),然后返回到进行初始化的活动,而没有调用 onDestroy,这可能会导致多次调用侦听器和蓝牙初始化而没有先停止它们。

    但是,我相信这不会导致 GPS 出现问题,因为您只在活动中定义了一次侦听器,并且我希望 GPS 侦听器添加例程来测试并避免添加两次相同的侦听器。此外,如果在您退出应用程序后 GPS 正在运行,您应该会在手机顶部状态栏中看到 GPS 图标。

    你没有显示蓝牙的代码,所以你可能有问题。

    也许将您的初始化代码移动到 onResume() 并将停止代码移动到 onPause() 将解决问题,否则您需要进行测试以避免两次连续初始化而没有停止。

    祝你好运。

    【讨论】:

    • 我查看了应用程序运行时和调用 onDestroy() 后的状态图标,并且 GPS 图标在运行时出现并在调用 onDestroy() 后消失。检查的好提示。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-10
    • 2011-07-04
    • 1970-01-01
    • 2013-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多