您的位置:首页 > 移动开发 > Android开发

android GPS DEMO

2011-03-11 10:49 225 查看
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

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: