【发布时间】:2012-12-16 18:28:33
【问题描述】:
我是安卓新手。所以如果我的问题很简单,请道歉并帮助我。
我正在开发一个 Android 应用程序,我尝试在其中仅使用 GPS 服务 获取用户位置(因为我正在开发一个需要在 Android 设备上运行的应用程序,即使 没有互联网)。
我的代码如下:
我的活动:
public class MyView extends Activity implements OnClickListener, Runnable
{
LocationManager itsLocationManager;
LocationListener itsLocationListener;
@Override
protected void onCreate(Bundle savedInstanceState)
{
itsLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
itsLocationListener = new MyLocationListener(this, itsLocationManager);
getLocationAndSendMessage();
}
private void getLocationAndSendMessage()
{
try
{
itsLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, itsLocationListener);
}
catch (Exception theException)
{
theException.printStackTrace();
ToastMsgUtil.showErrorMessage("Problem in retrieving your current location! Please try again.", this);
}
}
MyLocationListener.java:
public class MyLocationListener implements LocationListener
{
Context itsContext;
LocationManager itsLocationManager;
public MyLocationListener(Context theContext, LocationManager theLocationManager)
{
itsContext = theContext;
itsLocationManager = theLocationManager;
}
@Override
public void onLocationChanged(final Location theLocation)
{
//My Location processing code
itsLocationManager.removeUpdates(SafemateLocationListener.this);
}
}
AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
如上所述,我只需要通过 GPS 获取位置(因为用户手机中没有互联网)。
- 在调试时,我发现我在使用 LocationManager.GPS_PROVIDER 时在 onLocationChanged 方法中没有收到任何位置更新。
- 但是,当我尝试使用 LocationManager.NETWORK_PROVIDER 时,我会收到位置更新。
谁能说出我在上面的代码中做错了什么?我错过了什么吗?
请帮忙。谢谢。
【问题讨论】:
-
在博客、stackoverflow、android 开发指南中有很多示例。新位置将到达您的 onLocationChanged 方法。您的 getLocationAndSendMessage 方法只是注册您的位置侦听器。而且您不需要在 Activity 类中实现 Runnable
-
@Kamal 如果您发现任何解决方案,请发布它
标签: android locationmanager android-location locationlistener