GPS已开启,但代码仍未执行。请参阅详细信息

时间:2016-08-09 03:24:29

标签: android android-studio gps locationmanager android-reactivelocation

我正在开发一个应用程序,我只想在启用GPS时执行一段代码。

我正在使用这段代码检查GPS:

isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

现在,我正在使用它:

if (isGPSEnabled) {
            gps_off.setVisibility(View.INVISIBLE);
            ReactiveLocationProvider locationProvider = new ReactiveLocationProvider(getBaseContext());
            locationProvider.getLastKnownLocation()
                    .subscribe(new Action1<Location>() {
                        @Override
                        public void call(Location location) {
                            currentLatDoubleA = location.getLatitude();
                            currentLngDoubleA = location.getLongitude();
                            Toast.makeText(getBaseContext(), "User's location retrieved", Toast.LENGTH_SHORT).show();
                        }
                    });
//        }
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    retrieveHRequest();
                }
            }, 2000);
        } else {
            gps_off.setVisibility(View.VISIBLE);
            Snackbar snackbar = Snackbar
                    .make(coordinatorLayout, "No location detected!", Snackbar.LENGTH_LONG)
                    .setAction("RETRY", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {

                            ifLocationAvailable();
                        }
                    });
            snackbar.setDuration(Snackbar.LENGTH_INDEFINITE);
            snackbar.show();
        }

问题是,即使在打开GPS之后,Snackbar仍然会弹出显示No location detected!消息,这意味着即使在GPS关闭时,应该执行的代码也会被执行在上。

另外需要注意的是,当我关闭它后重新打开应用程序时,GPS开启时应该执行的代码正在执行而没有任何问题。

这里出了什么问题?

请告诉我。

1 个答案:

答案 0 :(得分:0)

在您的应用程序中,您希望实现广播接收器以观察改变GPS的状态。然后,只有应用程序才能了解您的GPS状态变化。

此代码可以帮助您

 public class BootReceiver extends BroadcastReceiver  {

       @Override
    public void onReceive(Context context, Intent intent) {
        LocationManager locationManager = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            // gps enabled and do your action here        } else {
            // gps disabled and do you snack bar action
        }
    }
}
相关问题