在我的应用程序中,当用户启用或禁用GPS时,我有一个GpsStatus.Listener来接收事件。如果全球定位系统在我启动应用程序之前,一切都很好。在这种情况下,每次打开或关闭全球定位系统时,我都会收到一个已启动或一个停住。
问题是,如果全球定位系统关闭,而应用程序启动。在这种情况下,如果我打开或关闭GPS,我就不会收到任何事件。
有人能给我解释一下吗?
这是我的代码:
public class GPSTracker implements android.location.GpsStatus.Listener {
private final Context context;
private final LocationListener locListener;
private LocationManager locationManager;
private boolean isGPSEnabled = false;
public GPSTracker(Context context, LocationListener locListener) {
this.context = context;
this.locListener = locListener;
setupGPS();
}
private void setupGPS() {
locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
locationManager.addGpsStatusListener(this);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(!isGPSEnabled) {
Toast.makeText(getContext(), "GPS disabled", Toast.LENGTH_SHORT).show();
} else {
locationManager.removeUpdates(locListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME, MIN_DISTANCE, locListener);
}
}
@Override
public void onGpsStatusChanged(int event) {
Log.e("onGpsStatusChanged", event+"");
switch(event) {
case GpsStatus.GPS_EVENT_STARTED:
Log.e("onGpsStatusChanged", "GPS_EVENT_STARTED");
break;
case GpsStatus.GPS_EVENT_STOPPED:
Log.e("onGpsStatusChanged", "GPS_EVENT_STOPPED");
break;
}
}所以,我的logcat输出是(如果GPS在启动的话):
输出全球定位系统关闭:没有。
发布于 2013-08-15 18:30:31
那么,LocationListener已经被提供了:
onProviderDisabled(),onProviderEnabled()和onStatusChanged()正是为了这个目的。
GpsStatus.Listener提供有关全球定位系统服务内部工作的信息。它不能用于告诉状态pf全球定位系统提供者。
LocationListener提供有关供应商的信息。当您向位置提供程序注册LocationListener时,onProviderEnabled()/onProviderDisabled()就会相应地被调用,并且您的应用程序总是可以知道何时启动或关闭全球定位系统。
试试这个:
public class test extends Activity implements LocationListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,10,this);
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
if(LocationManager.GPS_PROVIDER.equals(s)){
Toast.makeText(this,"GPS on",Toast.LENGTH_SHORT).show();
}
}
@Override
public void onProviderDisabled(String s) {
if(LocationManager.GPS_PROVIDER.equals(s)){
Toast.makeText(this,"GPS off",Toast.LENGTH_SHORT).show();
}
}
}https://stackoverflow.com/questions/18259039
复制相似问题