开发者

How to tell if an Android device will be able to provide a location?

I'm writing a geo app and it all works nicely, but I'm considering how it'll work on devices that don't have GPS or 3G, and the wifi may be off or not provide location info.

Is my best bet to just request a location update (or use the last known) and assume there is a way to get the location (whether GPS or network) or does the framework include a way to see what's available, and avoid the geo-lookup delay?

I figure on a device with no GPS my app should provide a UI for the user to specify the location, AND remember it in the sharedprefs so they don't have to keep re-entering it (I'm thinking devices like Google TV, and tablets).

I'd a开发者_开发百科ppreciate suggestions on how to handle the process of acquiring location in the context of various devices that have different levels of geo-awareness, and how to handle that.


You can invoke LocationManager.getAllProviders() to retrieve all location providers, or invoke LocationManager.getProviders(true) to retrieve active location providers.

boolean hasActiveLocationProvider = false;
LocationManager locationManager = Context.getSystemService(Context.LOCATION_SERVICE);
List<String> providers = locationManager.getProviders(true);
for (String providerName:providers) {
  if (providerName.equals(LocationManager.GPS_PROVIDER) 
      || providerName.equals(LocationManager.NETWORK_PROVIDER)) {
    hasActiveLocationProvider = true;
  }
}

http://developer.android.com/reference/android/location/LocationManager.html


Extending aleung's and Ollie's answer this is what worked best for me. There may be a few more gaps to fill.

private boolean hasActiveLocationProvider(Context context) {
    LocationManager locationManager = (LocationManager) context
            .getSystemService(Context.LOCATION_SERVICE);
    List<String> providers = locationManager.getProviders(true);
    for (String providerName : providers) {
        if (providerName.equals(LocationManager.GPS_PROVIDER)) {
            return true;
        }
        if (providerName.equals(LocationManager.NETWORK_PROVIDER)) {
            ConnectivityManager cm = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            boolean isConnected = cm.getActiveNetworkInfo() != null
                && cm.getActiveNetworkInfo().isConnectedOrConnecting();
            if (isConnected) {
                return true;
            }
        }
    }
    return false;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜