码迷,mamicode.com
首页 > 其他好文 > 详细

确定位置的经纬度LocationUtil

时间:2016-05-19 19:05:39      阅读:621      评论:0      收藏:0      [点我收藏+]

标签:

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();
            }
        }
    }
}

 

确定位置的经纬度LocationUtil

标签:

原文地址:http://www.cnblogs.com/zqxLonely/p/5509688.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!