欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

android > 获取当前位置

程序员文章站 2022-03-18 20:17:34
...

HomeIndex.java

 

package basic.futao.ma;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import location_map.futao.ma.R;

public class HomeIndex extends Activity {
	/** Called when the activity is first created. */
	
	String TAG = "PhoneStatReceiver";
	Context Tcontext;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		Tcontext = HomeIndex.this;
		LocationManager loctionManager = (LocationManager) Tcontext
				.getSystemService(Context.LOCATION_SERVICE);

		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);// 高精度
		criteria.setAltitudeRequired(false);// 不要求海拔
		criteria.setBearingRequired(false);// 不要求方位
		criteria.setCostAllowed(true);// 允许有花费
		criteria.setPowerRequirement(Criteria.POWER_LOW);// 低功耗
		// 从可用的位置提供器中,匹配以上标准的最佳提供器
        String provider = loctionManager.getBestProvider(criteria, true);  
        Location location = null;
        try {
        	location = loctionManager.getLastKnownLocation(provider); 
		} catch (Exception e) {
			// TODO: handle exception
		}
         
        if(location != null){//如果获得有效坐标  
            // 获得最后一次变化的位置  
              
            Double x = location.getLatitude();// 纬度  
            Double y = location.getLongitude();// 经度  
            Log.d("PhoneStatReceiver", x + "_" + y);  

			// 根据坐标返回具体地址
			Geocoder geocoder;
			List<Address> addresses = null;
			String addressStr = "";// 最终地址
			geocoder = new Geocoder(Tcontext, Locale.getDefault());
			try {
				addresses = geocoder.getFromLocation(x, y, 1);
				if (!addresses.isEmpty()) {// 判断addresses是否为空//如果获得有效地理位置
					String address = addresses.get(0).getAddressLine(0);
					String city = addresses.get(0).getAddressLine(1);
					String country = addresses.get(0).getAddressLine(2);
					addressStr = country + "__" + city + "___" + address;
					Log.d(TAG, addressStr);
				}else{
					Log.d(TAG, "获取失败");
				}

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			Log.d(TAG, "获取失败");
		}
		
		


	}
}

 

 

 

然后是权限

 

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

 

 

 

相关标签: 定位