如何在基于位置的Android应用程序中降低功耗?

Nar*_*mha 3 android

如何减少应用程序的耗电量?我可以用什么代码来实现这个?

Tim*_*ger 8

在尝试获取位置信息时,有几种不同的方法可以降低功耗.

  1. 使用上一个已知位置而不是尝试确定当前位置.

    // Get a Location Manager
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    
    // Try to get the last GPS based location
    Location l = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    
    // Fall back to cell tower based location if no prior GPS location
    if (l == null) {
        l = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 使用较便宜的位置提供商.您可以直接选择LocationManager.NETWORK_PROVIDER或指定您关注的条件,让Android告诉您使用哪个位置提供商.

    // Select the criteria you care about
    Criteria c = new Criteria();
    c.setAccuracy(Criteria.ACCURACY_COARSE);
    c.setPowerRequirement(Criteria.POWER_LOW);
    
    // Let the system tell you what provider you should use for your criteria
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    String p = lm.getBestProvider(c, true);
    
    // Call other Location Manager functions using the above provider...
    
    Run Code Online (Sandbox Code Playgroud)