用户打开GPS并恢复应用程序后,我的谷歌地图不起作用

时间:2016-08-07 11:57:53

标签: android google-maps gps onresume

我在Android应用程序中集成了谷歌地图一切正常但是当应用程序检测到移动设备的GPS没有启用时,它会给出一个启用GPS的对话框,当用户这样做并返回应用程序时,地图停止反应并变为蓝色(可能在海洋中聚焦),当我摇动设备时,地图变为活动状态并关注用户当前位置。

我想在肖像模式下运行此应用程序,因此摇动选项将不会非常有用。所以任何人都可以帮我解释代码并告诉我哪里错了。 我在onResume,onRestart上尝试了各种链接和方法,但没有任何帮助。

这是我的代码我在onCreate,onResume和onRestart中调用此setupmapifneeded函数,但没有任何帮助。

private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.

    if (mapFragment == null) {
        // Try to obtain the map from the SupportMapFragment.

        mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap googleMap) {
                mMap = googleMap;

                if (ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    return;
                }
                mMap.setMyLocationEnabled(true);


                // creating GPS Class object

                gps = new GPSTracker(MainActivity.this);

                mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(gps.getLatitude(), gps.getLongitude()), 15.0f));



                googleMap.addMarker(new MarkerOptions()
                        .position(new LatLng(26.89209, 75.82759))
                        .title("FUN N FOOD"));

                // check if GPS location can get
                if (gps.canGetLocation()) {
                    Log.d("Your Location", "latitude:" + gps.getLatitude() + ", longitude: " + gps.getLongitude());
                    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(gps.getLatitude(), gps.getLongitude()), 15.0f));
                } else {


                    gpsDialog = new MaterialDialog.Builder(MainActivity.this)
                            .titleColor(getResources().getColor(R.color.grey))
                            .title("GPS Settings")
                            .content("GPS is not enabled. Do you want to go to settings menu?")
                            .positiveText("Settings")
                            .negativeText("Cancel")
                            .positiveColorRes(R.color.grey)
                            .negativeColorRes(R.color.grey)
                            .onPositive(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                                    gpsDialog.dismiss();
                                }
                            })
                            .onNegative(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    gpsDialog.dismiss();
                                }
                            })
                            .show();
                    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(gps.getLatitude(), gps.getLongitude()), 14.0f));

                }
            }
        });

    }
}

这是我的activity.main

<fragment
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

这是我的其他方法

@Override
public void onPause() {

    if (mAdView != null) {
        mAdView.pause();
    }
    super.onPause();

}

@Override
public void onResume() {


    super.onResume();

    if (mAdView != null) {
        mAdView.resume();
    }

    if (mapFragment == null) {
        setUpMapIfNeeded();
    }

}

@Override
protected void onRestart() {
    super.onRestart();

    if (mapFragment == null) {
        setUpMapIfNeeded();
    }
}

@Override
public void onDestroy() {
    if (mAdView != null) {
        mAdView.destroy();
    }
    super.onDestroy();
}

任何人都可以建议...... 在此先感谢

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

我发现了一个非常简单的方法,首先忽略onResume部分,主要活动(融合位置提供程序Api)中集成了this

然后在我的启动画面中,我调出了一种方法,帮助我在OLA应用程序中启用gps,当启动转到下一个活动时,它开始关注用户的当前位置而没有任何问题。 / p>

我们可以像这样做gps: 创建一个功能

private GoogleApiClient mGoogleApiClient;

private void automaticGps() {


    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API).addConnectionCallbacks(Splash.this)
                .addOnConnectionFailedListener(Splash.this).build();
        mGoogleApiClient.connect();
        LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(30 * 1000);
        locationRequest.setFastestInterval(5 * 1000);
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(locationRequest);

        // **************************
        builder.setAlwaysShow(true); // this is the key ingredient
        // **************************

        PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi
                .checkLocationSettings(mGoogleApiClient, builder.build());
        result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
            @Override
            public void onResult(LocationSettingsResult result) {
                final Status status = result.getStatus();
                final LocationSettingsStates state = result
                        .getLocationSettingsStates();
                switch (status.getStatusCode()) {
                    case LocationSettingsStatusCodes.SUCCESS:
                        // All location settings are satisfied. The client can
                        // initialize location
                        // requests here.

                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        // Location settings are not satisfied. But could be
                        // fixed by showing the user
                        // a dialog.
                        try {
                            // Show the dialog by calling
                            // startResolutionForResult(),
                            // and check the result in onActivityResult().
                            status.startResolutionForResult(Splash.this, 1000);
                        } catch (IntentSender.SendIntentException e) {
                            // Ignore the error.
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        // Location settings are not satisfied. However, we have
                        // no way to fix the
                        // settings so we won't show the dialog.
                        break;
                }
            }
        });
    }
}

覆盖方法:

    @Override
public void onConnected(@Nullable Bundle bundle) {
    Intent i = new Intent(Splash.this,MainActivity.class);
    startActivity(i);
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

并实施:

public class Splash extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener

在onCreate中调用此函数

if(!gps.canGetLocation) {
                automaticGps();
                //iv.startAnimation(an2);
            }
            else {
                //iv.startAnimation(an2);
                finish();
                Intent i = new Intent(Splash.this,MainActivity.class);
                startActivity(i);
            }

记住:

1)使用android.Manifest.permission.ACCESS_FINE_LOCATION而不是Manifest.permission.ACCESS_FINE_LOCATION

2)从onPause()中删除这些行:

if (mGoogleApiClient != null) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }