Nam*_*los 3 gps android listener
在我的应用程序中,我有一个GpsStatus.Listener,用于在用户启用或禁用GPS时接收事件.如果在启动应用程序之前启用GPS,一切正常.在这种情况下,每次打开或关闭GPS时,我都会收到GPS_EVENT_STARTED或GPS_EVENT_STOPPED.
问题是如果应用程序启动时GPS已关闭.在这种情况下,如果我打开或关闭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;
}
}
Run Code Online (Sandbox Code Playgroud)
所以,我的logcat输出是(如果GPS在启动时打开):
GPS关机输出:没有.
好吧,LocationListener已经提供:
onProviderDisabled(),onProviderEnabled()并onStatusChanged()出于这样的目的.
GpsStatus.Listener提供有关GPS服务内部运作的信息.它不能用于告知GPS提供商的状态.
LocationListener提供有关提供商的信息 当您LocationListener向位置提供商注册时,会相应地调用onProviderEnabled()/ onProviderDisabled(),并且您的应用程序始终可以告知GPS何时打开或关闭.
试试这个:
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)