开发者

How can I reduce power usage in a location-based Android application?

开发者 https://www.devze.com 2022-12-27 00:23 出处:网络
How can I reduce the power usage开发者_开发百科 in my application?What code can I use to implement this?There are a couple different ways to reduce the power used when trying to get location informati

How can I reduce the power usage开发者_开发百科 in my application? What code can I use to implement this?


There are a couple different ways to reduce the power used when trying to get location information.

  1. Use the last known location instead of trying to determine the current location.

    // 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);
    }
    
  2. Use a less expensive location provider. You can pick LocationManager.NETWORK_PROVIDER directly or specify the criteria you care about and let Android tell you which location provider to use.

    // 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...
    
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号