我有以下非常简单的类,用于查找最后一个已知的用户坐标,然后打印其中一个.但是我将loc作为null变量.应用程序未将数据读取到loc变量中.
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.Toast;
public class Navigation extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/* Use the LocationManager class to obtain GPS locations */
try
{
LocationManager mlocManager =
(LocationManager) getSystemService(Context.LOCATION_SERVICE);
Toast.makeText(getBaseContext(),
"Provider Enable Status : " + mlocManager.isProviderEnabled(
mlocManager.getProvider("gps").getName()),
Toast.LENGTH_LONG).show();
Location loc = mlocManager.getLastKnownLocation("gps");
Toast.makeText( getApplicationContext(), "" +
loc.getLatitude(), Toast.LENGTH_LONG).show();
Toast.makeText( getApplicationContext(), "" + loc,
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage() +
e.toString(), Toast.LENGTH_LONG).show();
}
}
}
我在代码中添加了以下监听器:
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( mlocManager.getProvider("gps").getName(), 0, 0, mlocListener);
在oncreate函数中.和以下作为课程
public class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location loc) {
Toast.makeText( getApplicationContext(),
"Hi, location changed. :)", Toast.LENGTH_LONG).show();
try {
loc.getLatitude();
loc.getLongitude();
String Text = "My current location is: " +
" Latitude = " + loc.getLatitude() +
" Longitude = " + loc.getLongitude();
Toast.makeText(getApplicationContext(),
Text, Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(),
e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
在运行窗口之后,请执行以下操作:
在Eclipse中转到DDMS并设置纬度/经度,然后单击发送.
仍然不会在函数中触发任何Toast命令.
解决方法:
好了,您可以执行null检查,这绝对是解决此问题的好方法.另一个技巧是在您的onResume()调用活动中,您请求通过以下方式更新位置:
@Override
protected void onResume() {
// TODO Auto-generated method stub
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10f,this);
super.onResume();
}
对于您的mlocManager,请确保将其创建为实例变量(类级别),而不是局部变量(在onCreate中,在方法中未定义).
这肯定会获取位置更新,并且不会抛出空指针.另外,请确保您对GPS配置的模拟器进行了地理定位.使用DDMS的“仿真器控制”弹出按钮来执行此操作.在启动活动之前,先修正一些经度和纬度值.
希望这可以帮助!