使用 GPS 获取用户的当前位置
Posted
技术标签:
【中文标题】使用 GPS 获取用户的当前位置【英文标题】:Get user's current location using GPS 【发布时间】:2013-06-25 06:08:00 【问题描述】:我是安卓新手。 我目前正在开发一个 android 项目,我需要。 但是我的代码不能正常工作。
java代码
package com.example.checkinapp;
import android.app.Activity;
import android.content.Context;
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
TextView textlat;
TextView textlong;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textlat = (TextView)findViewById(R.id.textlat);
textlong = (TextView)findViewById(R.id.textlong);
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new mylocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
class mylocationlistener implements LocationListener
@Override
public void onLocationChanged(Location location)
if(location!=null)
double lat = location.getLatitude();
double lng = location.getLongitude();
textlat.setText(Double.toString(lat));
textlong.setText(Double.toString(lng));
@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
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_
android:layout_
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textlat"
android:layout_
android:layout_
android:layout_alignParentTop="true"
android:layout_marginTop="16dp"
android:text=""
android:ems="10">
</TextView>
<TextView
android:id="@+id/textlong"
android:layout_
android:layout_
android:layout_marginTop="25dp"
android:text=""
android:ems="10">
</TextView>
</RelativeLayout>
AndroidMainfest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.checkinapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.checkinapp.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
我正在尝试将用户的纬度和经度显示到文本视图。 但我没有得到结果。 谢谢。
【问题讨论】:
有什么问题?您是否正在调用 onLocationChanged() 方法?设备 GPS 是否开启?你能不能试着靠近窗户或离开办公室看看你是否能抓住 GPS 卫星.. 考虑使用 Google Play 服务位置 API,它们可以更好地调整以节省电池电量。 它现在正在工作。感谢您的回复。 【参考方案1】:使用此类在您的应用中获取当前位置,这对我来说非常有用
/**
* Gps location tracker class
* to get users location and other information related to location
*/
public class GpsLocationTracker extends Service implements LocationListener
/**
* context of calling class
*/
private Context mContext;
/**
* flag for gps status
*/
private boolean isGpsEnabled = false;
/**
* flag for network status
*/
private boolean isNetworkEnabled = false;
/**
* flag for gps
*/
private boolean canGetLocation = false;
/**
* location
*/
private Location mLocation;
/**
* latitude
*/
private double mLatitude;
/**
* longitude
*/
private double mLongitude;
/**
* min distance change to get location update
*/
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATE = 10;
/**
* min time for location update
* 60000 = 1min
*/
private static final long MIN_TIME_FOR_UPDATE = 60000;
/**
* location manager
*/
private LocationManager mLocationManager;
/**
* @param mContext constructor of the class
*/
public GpsLocationTracker(Context mContext)
this.mContext = mContext;
getLocation();
/**
* @return location
*/
public Location getLocation()
try
mLocationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
/*getting status of the gps*/
isGpsEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
/*getting status of network provider*/
isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGpsEnabled && !isNetworkEnabled)
/*no location provider enabled*/
else
this.canGetLocation = true;
/*getting location from network provider*/
if (isNetworkEnabled)
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_FOR_UPDATE, MIN_DISTANCE_CHANGE_FOR_UPDATE, this);
if (mLocationManager != null)
mLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (mLocation != null)
mLatitude = mLocation.getLatitude();
mLongitude = mLocation.getLongitude();
/*if gps is enabled then get location using gps*/
if (isGpsEnabled)
if (mLocation == null)
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_FOR_UPDATE, MIN_DISTANCE_CHANGE_FOR_UPDATE, this);
if (mLocationManager != null)
mLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (mLocation != null)
mLatitude = mLocation.getLatitude();
mLongitude = mLocation.getLongitude();
catch (Exception e)
e.printStackTrace();
return mLocation;
/**
* call this function to stop using gps in your application
*/
public void stopUsingGps()
if (mLocationManager != null)
mLocationManager.removeUpdates(GpsLocationTracker.this);
/**
* @return latitude
* <p/>
* function to get latitude
*/
public double getLatitude()
if (mLocation != null)
mLatitude = mLocation.getLatitude();
return mLatitude;
/**
* @return longitude
* function to get longitude
*/
public double getLongitude()
if (mLocation != null)
mLongitude = mLocation.getLongitude();
return mLongitude;
/**
* @return to check gps or wifi is enabled or not
*/
public boolean canGetLocation()
return this.canGetLocation;
/**
* function to prompt user to open
* settings to enable gps
*/
public void showSettingsAlert()
AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(new ContextThemeWrapper(mContext, R.style.AppTheme));
mAlertDialog.setTitle("Gps Disabled");
mAlertDialog.setMessage("gps is not enabled . do you want to enable ?");
mAlertDialog.setPositiveButton("settings", new OnClickListener()
public void onClick(DialogInterface dialog, int which)
// TODO Auto-generated method stub
Intent mIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(mIntent);
);
mAlertDialog.setNegativeButton("cancle", new OnClickListener()
public void onClick(DialogInterface dialog, int which)
// TODO Auto-generated method stub
dialog.cancel();
);
final AlertDialog mcreateDialog = mAlertDialog.create();
mcreateDialog.show();
@Override
public IBinder onBind(Intent arg0)
// TODO Auto-generated method stub
return null;
public void onLocationChanged(Location location)
// TODO Auto-generated method stub
public void onProviderDisabled(String provider)
// TODO Auto-generated method stub
public void onProviderEnabled(String provider)
// TODO Auto-generated method stub
public void onStatusChanged(String provider, int status, Bundle extras)
// TODO Auto-generated method stub
&以这种方式使用它
GpsLocationTracker mGpsLocationTracker = new GpsLocationTracker(YourActivity.this);
/**
* Set GPS Location fetched address
*/
if (mGpsLocationTracker.canGetLocation())
latitude = mGpsLocationTracker.getLatitude();
longitude = mGpsLocationTracker.getLongitude();
Log.i(TAG, String.format("latitude: %s", latitude));
Log.i(TAG, String.format("longitude: %s", longitude));
else
mGpsLocationTracker.showSettingsAlert();
& 别忘了在 Manifest.xml 中设置权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
【讨论】:
我不明白为什么GpsLocationTracker
必须是Service。因为它既没有与startService()
也没有与bindService()
一起使用。
如果指定了 ACCESS_FINE_LOCATION,则 ACCESS_COARSE_LOCATION 是多余的。从文档中: 注意:如果您同时使用 NETWORK_PROVIDER 和 GPS_PROVIDER,那么您只需要请求 - ACCESS_FINE_LOCATION 权限,因为它包括两个提供者的权限。 - (ACCESS_COARSE_LOCATION 的权限仅包括 NETWORK_PROVIDER 的权限。)【参考方案2】:
LocationManager manager = (LocationManager) this .getSystemService(Context.LOCATION_SERVICE);
Location loc = manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Toast.makeText( getApplicationContext(),"My current location is: " + "Latitud =" +
loc.getLatitude() + "Longitud = " + loc.getLongitude(),Toast.LENGTH_SHORT).show();
【讨论】:
这是最简单的答案。我们可以添加错误检查等来改进,但这个答案应该会得到更多的支持。【参考方案3】:试试这个,
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria,
true);
Location location = locationManager
.getLastKnownLocation(provider);
if (location != null)
onLocationChanged(location);
// updates location 30seconds once
locationManager
.requestLocationUpdates(provider, 30000, 0, this);
【讨论】:
【参考方案4】:改用commonsware库..它比其他代码稳定得多...你只需要从这里下载库
https://github.com/commonsguy/downloads/blob/master/CWAC-LocationPoller.jar
这是代码
public class LocationReceiver extends BroadcastReceiver
@Override
public void onReceive(Context context, Intent intent)
Log.i(getClass().getSimpleName(), "Received intent for " + intent.getComponent().flattenToShortString());
try
Bundle b=intent.getExtras();
LocationPollerResult locationResult = new LocationPollerResult(b);
Location loc=locationResult.getLocation();
String msg;
if (loc==null)
loc=locationResult.getLastKnownLocation();
if (loc==null)
msg=locationResult.getError();
else
msg="TIMEOUT, lastKnown="+loc.toString();
else
msg=loc.toString();
if (msg==null)
msg="Invalid broadcast received!";
Log.i(getClass().getSimpleName(), "received location: " + msg);
catch (Exception e)
Log.e(getClass().getName(), e.getMessage());
【讨论】:
【参考方案5】:这是获取用户位置的两种方法
如果您使用 NETWORK_PROVIDER,它可以在室内和室外工作,但准确度要低得多。如果您使用 GPS_PROVIDER,它只适用于户外,并且准确度很好。
字符串 locationProvider = LocationManager.NETWORK_PROVIDER;
字符串 locationProvider = LocationManager.GPS_PROVIDER;
以及清单中所需的权限
【讨论】:
以上是关于使用 GPS 获取用户的当前位置的主要内容,如果未能解决你的问题,请参考以下文章