package com.mapLoacation;
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
Location location;
LocationManager locationmanager;
String provider;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String context=Context.LOCATION_SERVICE;
locationmanager = (LocationManager) getSystemService(context);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = locationmanager.getBestProvider(criteria,true);
location = locationmanager.getLastKnownLocation(provider);
updateWithNewLocation(location);
locationmanager.requestLocationUpdates(provider, 1000, 10, locationlistner);
}
private void updateWithNewLocation(Location location) {
String latLongString;
TextView myLocationText;
myLocationText = (TextView) findViewById(R.id.myLocationText);
if(location!=null){
double lat=location.getLatitude();
double lng = location.getLongitude();
latLongString="Lat:"+lat+"\nLongitude:"+lng;
}else{
latLongString="Locaton no found !";
}
myLocationText.setText(latLongString);
}
LocationListener locationlistner = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
};
}
清单文件加入权限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<use-permission android:name="android.permission.INTERNET"/>
布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/myLocationText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>
运行效果: