我正在尝试实现位置更新侦听器以检测android中的位置更改。我已实现以下代码。我通过Log“GPS Started”收到通知。但之后onLocationChanged()函数永远不会调用。我通过改变位置测试但它从未调用过。 请注意,GPS是有问题的。
public class locationActivity extends Activity implements LocationListener{
LocationManager lManager=null;
TextView _textview;
void initLocationService()
{
{
lManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria=new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
GpsStatus.Listener gpsListener=new GpsStatus.Listener() {
@Override
public void onGpsStatusChanged(int event) {
if(event==GpsStatus.GPS_EVENT_STOPPED)
{
Log.e("GPS Listener","GPS Stoped");
}
else if(event==GpsStatus.GPS_EVENT_STARTED)
{
Log.e("GPS Listener","GPS Started");
}
}
};
LocationRequest lrequest=new LocationRequest();
lManager.addGpsStatusListener(gpsListener);
}
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.e("GPS Listener","LocationChanged");
_textview.setText("LocationChanged"+count);
}
@Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
// TODO Auto-generated method stub
Log.e("GPS Listener","StatusChanged");
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Log.e("GPS Listener","ProvidedEnabled");
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Log.e("GPS Listener","ProviderDisabled");
}
enter code here
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.location_test);
_textview=(TextView)findViewById(R.id.textView1);
initLocationService();
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
lManager.removeUpdates(this);
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
lManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 400, 0,this);
}
}
答案 0 :(得分:0)
要获取位置更新,您需要致电requestLocationUpdates()
并为其指定LocationListener
。
通常情况下,您可以使用以下内容定义LocationManager和LocationListener
LocationManager locMgr = null;
LocationListener locListener = null;
locListener = new LocationListener() {
public void onLocationChanged(Location location) {
if (location != null) {
// Do something
}
}
public void onProviderDisabled(String provider) { }
public void onProviderEnabled(String provider) { }
public void onStatusChanged(String provider, int status, Bundle extras) { }
};
并使用以下调用在onResume()
中启用它:
locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER,
0, // min time in ms
0, // min distance in meters
locListener);
和onPause()
:
locMgr.removeUpdates(locListener);