package com.pingyijinren.test; import android.content.Context; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.util.Log; import java.util.List; /** * Created by Administrator on 2016/5/19 0019. */ public class LocationUtil { public static Context context; private static LocationManager locationManager; private static Location location; private static LocationListener locationListener; public static String getLocation() { locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); String provider; String result=null; List<String> providerList = locationManager.getProviders(true); if (providerList.contains(LocationManager.GPS_PROVIDER)) { provider = LocationManager.GPS_PROVIDER; } else if (providerList.contains(LocationManager.NETWORK_PROVIDER)) { provider = LocationManager.NETWORK_PROVIDER; } else { Log.d("MainActivity","没有开启位置服务"); return null; } try{ location=locationManager.getLastKnownLocation(provider); if(location!=null){ result=location.getLatitude()+" "+location.getLongitude(); } locationListener=new LocationListener(){ @Override public void onStatusChanged(String provider,int status,Bundle extra){} @Override public void onProviderEnabled(String provider){} @Override public void onProviderDisabled(String provider){} @Override public void onLocationChanged(Location changedLocation){ location=changedLocation; } }; locationManager.requestLocationUpdates(provider,0,0,locationListener); } catch(SecurityException e){ e.printStackTrace(); } return result; } public static void onDestroy(){ if(locationManager!=null){ try{ locationManager.removeUpdates(locationListener); } catch(SecurityException e){ e.printStackTrace(); } } } }
时间: 2024-10-15 21:03:54