package com.gps;
import android.app.Activity;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Gps extends Activity implements LocationListener {
private LocationManager lm;
private Button btn;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L,1.0f, this);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Log.d("===============", "gps not opened");
} else {
Location bestLoc = getBestLocation(lm);
if(bestLoc == null){
Log.d("=============", "gps opened, but can not get gps location");
}else {
Log.d("=====getLatitude=======", String.valueOf(bestLoc.getLatitude()));
Log.d("======getLongitude======", String.valueOf(bestLoc.getLongitude()));
}
}
}
private Location getBestLocation(LocationManager locationManager) {
Location gpsLoc = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location networkLoc = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location bestLoc = null;
if (gpsLoc != null && networkLoc != null) {
// if gps loc is more than 5 min older than network loc
bestLoc = networkLoc.getTime() - 5 * 60 * 1000 > gpsLoc
.getTime() ? networkLoc : gpsLoc;
} else if (gpsLoc != null) {
bestLoc = gpsLoc;
} else if (networkLoc != null) {
bestLoc = networkLoc;
}
return bestLoc;
}
});
}
@Override
public void onLocationChanged(Location paramLocation) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String paramString) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String paramString) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String paramString, int paramInt,
Bundle paramBundle) {
// TODO Auto-generated method stub
}
}
android GPS DEMO
最新推荐文章于 2024-02-12 22:01:05 发布