如何获取 Android GPS 位置
Posted
技术标签:
【中文标题】如何获取 Android GPS 位置【英文标题】:How to get Android GPS location 【发布时间】:2013-05-06 02:15:03 【问题描述】:干杯,我正在尝试通过 android 获取当前的 GPS 位置。我也关注了this Tutorial 和Vogellas article。虽然它不起作用。使用 LocationManager.NETWORK_PROVIDER 时,无论我站在哪里,我总是得到纬度 51 度和经度度 9 度。使用 LocationManager.GPS_PROVIDER 时,我什么也得不到。
虽然使用 GMaps 时一切正常:S 不知道为什么。如何像 GMaps 一样获取当前 GPS 位置?
这是我的代码:
package com.example.gpslocation;
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.util.Log;
import android.view.Menu;
public class GPS_Location extends Activity implements LocationListener
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps__location);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
@Override
public boolean onCreateOptionsMenu(Menu menu)
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.gps__location, menu);
return true;
@Override
public void onLocationChanged(Location location)
// TODO Auto-generated method stub
int latitude = (int) (location.getLatitude());
int longitude = (int) (location.getLongitude());
Log.i("Geo_Location", "Latitude: " + latitude + ", Longitude: " + longitude);
@Override
public void onProviderDisabled(String provider)
// TODO Auto-generated method stub
@Override
public void onProviderEnabled(String provider)
// TODO Auto-generated method stub
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
// TODO Auto-generated method stub
【问题讨论】:
为了获得更高级别和更简单的 GPS 位置,您可以使用这个库:github.com/delight-im/Android-SimpleLocation 检查***.com/questions/1513485/… 【参考方案1】:这是你的问题:
int latitude = (int) (location.getLatitude());
int longitude = (int) (location.getLongitude());
纬度和经度是double
-值,因为它们以度为单位表示位置。
通过将它们转换为int
,您将丢弃逗号后面的所有内容,这会产生很大的不同。见"Decimal Degrees - Wiki"
【讨论】:
已经认为这很愚蠢。你已经证明了它;P Ty【参考方案2】:试试看:
public LatLng getLocation()
// Get the location manager
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(bestProvider);
Double lat,lon;
try
lat = location.getLatitude ();
lon = location.getLongitude ();
return new LatLng(lat, lon);
catch (NullPointerException e)
e.printStackTrace();
return null;
【讨论】:
感谢您的回答,尽管我已经尝试过您上面的代码,只是将自己的代码剪切为最简单的解决方案来向您展示问题;P 无论如何谢谢【参考方案3】:这段代码有一个问题:
int latitude = (int) (location.getLatitude());
int longitude = (int) (location.getLongitude());
您可以将int
更改为double
double latitude = location.getLatitude();
double longitude = location.getLongitude();
【讨论】:
【参考方案4】:最初的问题是通过将lat
和lon
更改为double 来解决的。
我想用Location location = locationManager.getLastKnownLocation(bestProvider);
向解决方案添加评论
它可以在其他应用程序为此进行侦听时找出最后一个已知位置。例如,如果自设备启动后没有应用程序这样做,代码将返回零(我最近花了一些时间来解决这个问题)。
另外,当locationManager.removeUpdates(this);
不需要时停止收听是一个好习惯
此外,即使拥有manifest
中的权限,当在设备上的 Android 设置中启用位置服务时,该代码仍然有效。
【讨论】:
【参考方案5】:摘录:-
try
cnt++;scnt++;now=System.currentTimeMillis();r=rand.nextInt(6);r++;
loc=lm.getLastKnownLocation(best);
if(loc!=null)lat=loc.getLatitude();lng=loc.getLongitude();
Thread.sleep(100);
handler.sendMessage(handler.obtainMessage());
catch (InterruptedException e)
Toast.makeText(this, "Error="+e.toString(), Toast.LENGTH_LONG).show();
正如您在上面看到的,一个线程与用户界面活动的主线程一起运行,该线程持续显示 GPS 纬度、经度以及当前时间和随机掷骰子。
如果您好奇,请查看完整代码: GPS Location with a randomized dice throw & current time in separate thread
【讨论】:
【参考方案6】:为这个项目工作了一天。它可能对你有用。 我压缩并组合了网络和 GPS。 MainActivity.java中直接即插即用 (显示结果有一些DIY功能)
///////////////////////////////////
////////// LOCATION PACK //////////
//
// locationManager: (LocationManager) for getting LOCATION_SERVICE
// osLocation: (Location) getting location data via standard method
// dataLocation: class type storage locztion data
// x,y: (Double) Longtitude, Latitude
// location: (dataLocation) variable contain absolute location info. Autoupdate after run locationStart();
// AutoLocation: class help getting provider info
// tmLocation: (Timer) for running update location over time
// LocationStart(int interval): start getting location data with setting interval time cycle in milisecond
// LocationStart(): LocationStart(500)
// LocationStop(): stop getting location data
//
// EX:
// LocationStart(); cycleF(new Runnable() public void run()bodyM.text("LOCATION \nLatitude: " + location.y+ "\nLongitude: " + location.x).show();,500);
//
LocationManager locationManager;
Location osLocation;
public class dataLocation double x,y;
dataLocation location=new dataLocation();
public class AutoLocation extends Activity implements LocationListener
@Override public void onLocationChanged(Location p1)
@Override public void onStatusChanged(String p1, int p2, Bundle p3)
@Override public void onProviderEnabled(String p1)
@Override public void onProviderDisabled(String p1)
public Location getLocation(String provider)
if (locationManager.isProviderEnabled(provider))
locationManager.requestLocationUpdates(provider,0,0,this);
if (locationManager != null)
osLocation = locationManager.getLastKnownLocation(provider);
return osLocation;
return null;
Timer tmLocation=new Timer();
public void LocationStart(int interval)
locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
final AutoLocation autoLocation = new AutoLocation();
tmLocation=cycleF(new Runnable() public void run()
Location nwLocation = autoLocation.getLocation(LocationManager.NETWORK_PROVIDER);
if (nwLocation != null)
location.y = nwLocation.getLatitude();
location.x = nwLocation.getLongitude();
else
//bodym.text("NETWORK_LOCATION is loading...").show();
Location gpsLocation = autoLocation.getLocation(LocationManager.GPS_PROVIDER);
if (gpsLocation != null)
location.y = gpsLocation.getLatitude();
location.x = gpsLocation.getLongitude();
else
//bodym.text("GPS_LOCATION is loading...").show();
, interval);
public void LocationStart()LocationStart(500);;
public void LocationStop()stopCycleF(tmLocation);
//////////
///END//// LOCATION PACK //////////
//////////
/////////////////////////////
////////// RUNTIME //////////
//
// Need library:
// import java.util.*;
//
// delayF(r,d): execute runnable r after d millisecond
// Halt by execute the return: final Runnable rn=delayF(...); (new Handler()).post(rn);
// cycleF(r,i): execute r repeatedly with i millisecond each cycle
// stopCycleF(t): halt execute cycleF via the Timer return of cycleF
//
// EX:
// delayF(new Runnable()public void run() sig("Hi"); ,2000);
// final Runnable rn=delayF(new Runnable()public void run() sig("Hi"); ,3000);
// delayF(new Runnable()public void run() (new Handler()).post(rn);sig("Hello"); ,1000);
// final Timer tm=cycleF(new Runnable() public void run() sig("Neverend"); , 1000);
// delayF(new Runnable()public void run() stopCycleF(tm);sig("Ended"); ,7000);
//
public static Runnable delayF(final Runnable r, long delay)
final Handler h = new Handler();
h.postDelayed(r, delay);
return new Runnable()
@Override
public void run()h.removeCallbacks(r);
;
public static Timer cycleF(final Runnable r, long interval)
final Timer t=new Timer();
final Handler h = new Handler();
t.scheduleAtFixedRate(new TimerTask()
public void run() h.post(r);
, interval, interval);
return t;
public void stopCycleF(Timer t)t.cancel();t.purge();
public boolean serviceRunning(Class<?> serviceClass)
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE))
if (serviceClass.getName().equals(service.service.getClassName()))
return true;
return false;
//////////
///END//// RUNTIME //////////
//////////
【讨论】:
以上是关于如何获取 Android GPS 位置的主要内容,如果未能解决你的问题,请参考以下文章
Android:如何使用 GPS 提供程序获取离线当前位置?
如何使用 Xamarin 在 Android 中同步获取 GPS 位置更新?
如何在 Android 中使用 gps 获取当前位置(街道、城市等)