Android 获取手机当前所在的经纬度

manifest中要加的permission:




activity_main.xml



    
    
    


MainActivity.java

package com.example.location;

import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.widget.EditText;

public class MainActivity extends Activity {

	LocationManager lm;
	EditText et;
	LocationListener ll = new LocationListener(){
		public void onLocationChanged(Location location){
			updateView(location);
		}

		@Override
		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub
			updateView(null);
		}

		@Override
		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub
			Location l = lm.getLastKnownLocation(provider);
			updateView(l);
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
			
		}
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		et = (EditText)findViewById(R.id.et);
		lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		String bestProvider = lm.getBestProvider(getCriteria(), true);
		Location l = lm.getLastKnownLocation(bestProvider);
		updateView(l);
		lm.requestLocationUpdates(bestProvider, 5000, 8, ll);
	}

	private Criteria getCriteria() {
		// TODO Auto-generated method stub
		Criteria c = new Criteria();
		c.setAccuracy(Criteria.ACCURACY_COARSE);
		c.setSpeedRequired(false);
		c.setCostAllowed(false);
		c.setBearingRequired(false);
		c.setAltitudeRequired(false);
		c.setPowerRequirement(Criteria.POWER_LOW);
		return c;
	}
	public void updateView(Location newLocation)
	{
		if(newLocation !=null){
			et.setText("您现在的位置是\n纬度:");
			et.append(String.valueOf(newLocation.getLatitude()));
			et.append("\n经度:");
			et.append(String.valueOf(newLocation.getLongitude()));
		}
		else{
			et.getEditableText().clear();
		}
	}
}


你可能感兴趣的:(Android)