Android 深入研究LBS(基于位置的服务)

Android 深入研究LBS(基于位置的服务)
package com.example.lbs;
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.TextView;


public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager lm;
String serviceName = Context.LOCATION_SERVICE;
lm = (LocationManager) getSystemService(serviceName);//获取系统的服务, 
Criteria cri = new Criteria();//创建一个criteria对象 
cri.setAccuracy(Criteria.ACCURACY_FINE);
cri.setAltitudeRequired(false);//设置不需要获取海拔方向数据 
cri.setBearingRequired(false);
cri.setCostAllowed(true);//设置允许产生资费 
cri.setPowerRequirement(Criteria.POWER_LOW);//要求低耗电 
String provider = lm.getBestProvider(cri, true);
Location lo = lm.getLastKnownLocation(provider);
updateWithNewLocation(lo);//第一次获得设备的位置 
final LocationListener ll = new LocationListener() {

@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub

}

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

@Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
updateWithNewLocation(arg0);
}
};
lm.requestLocationUpdates(provider, 2000, 10, ll);//监听数据
}


private void updateWithNewLocation(Location location){
String latLongString;
TextView myLocationText;
myLocationText = (TextView) findViewById(R.id.myLocation);
if(location!=null){
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "纬度:"+lat+"经度"+lng;
}else{
latLongString = "failed";
}
myLocationText.setText("当前坐标位置是:"+latLongString);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

同时注意在manifest中添加<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />    
若有问题请留言,若转载请注明出处。

你可能感兴趣的:(android,LBS)