不打开位置不显示 android 中的当前位置

without turn on location not showing current location in android

您好,我在下面的代码中将当前位置设置为我的 application.If 它是通过手动打开位置显示当前位置的。

如果我没有打开它,它在我的地图上什么也没有显示。

但是我想显示开启定位的权限,已经写了代码,但是不行。

任何人都可以帮助解决这个问题。

MapsActivity.java:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
        private static final int LOCATION_REQUESTOR = 101;
        @Bind(R.id.back)
        TextView mBack;
        @Bind(R.id.location)
        TextView mLocation;
        @Bind(R.id.toolBar)
        Toolbar mToolBar;
        @Bind(R.id.map_address)
        TextView mMapAddress;
        @Bind(R.id.latitude)
        EditText mLatitude;
        @Bind(R.id.longitude)
        EditText mLongitude;
        @Bind(R.id.setLocation)
        Button mSetLocation;
        private Location mLastLocation;
        private GoogleMap mMap;
        Marker mCurrLocationMarker;

        private GoogleApiClient mGoogleApiClient;
        private LocationRequest mLocationRequest;
        private SharedPreferences mPref;
        private SolarBLEPacket mSolarController = new SolarBLEPacket();

        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_maps);

            ButterKnife.bind(this);
            mPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
            final SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
            mapFragment.getMapAsync(this);

        }

        protected synchronized void buildGoogleApiClient() {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
            mGoogleApiClient.connect();
        }

        @Override
        public void onConnected(@Nullable Bundle bundle) {
            mLocationRequest = new LocationRequest();
            mLocationRequest.setInterval(1000);
            mLocationRequest.setFastestInterval(1000);
            mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
            }
        }

        @Override
        public void onConnectionSuspended(int i) {
        }

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

        @Override
        public void onLocationChanged(Location location) {

            mLastLocation = location;
            if (mCurrLocationMarker != null) {
                mCurrLocationMarker.remove();
            }

            LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.position(latLng);
            markerOptions.title("Current Position");
            markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
            mCurrLocationMarker = mMap.addMarker(markerOptions);

            //move map camera
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));

            mLongitude.setText(latLng.longitude + "");
            mLatitude.setText(latLng.latitude + "");

        }

        @Override
        public void onMapReady(GoogleMap googleMap)
        {
            mMap=googleMap;
            mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

            //Initialize Google Play Services
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) {
                    //Location Permission already granted
                    buildGoogleApiClient();
                    mMap.setMyLocationEnabled(true);
                } else {
                    //Request Location Permission
                    checkLocationPermission();
                }
            }
            else {
                buildGoogleApiClient();
                mMap.setMyLocationEnabled(true);
            }
        }
        public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
        public boolean checkLocationPermission() {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {

                // Should we show an explanation?
                if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)) {

                    // Show an explanation to the user *asynchronously* -- don't block
                    // this thread waiting for the user's response! After the user
                    // sees the explanation, try again to request the permission.
                    new AlertDialog.Builder(this)
                            .setTitle(R.string.title_location_permission)
                            .setMessage(R.string.text_location_permission)
                            .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    //Prompt the user once explanation has been shown
                                    ActivityCompat.requestPermissions(MapsActivity.this,
                                            new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                            MY_PERMISSIONS_REQUEST_LOCATION);
                                }
                            })
                            .create()
                            .show();


                } else {
                    // No explanation needed, we can request the permission.
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                            MY_PERMISSIONS_REQUEST_LOCATION);
                }
                return false;
            } else {
                return true;
            }
        }

        @Override
        public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
            switch (requestCode) {
                case MY_PERMISSIONS_REQUEST_LOCATION: {
                    // If request is cancelled, the result arrays are empty.
                    if (grantResults.length > 0
                            && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                        // permission was granted, yay! Do the
                        // location-related task you need to do.
                        if (ContextCompat.checkSelfPermission(this,
                                Manifest.permission.ACCESS_FINE_LOCATION)
                                == PackageManager.PERMISSION_GRANTED) {

                            //Request location updates:
                            //.requestLocationUpdates(provider, 400, 1, this);
                        }

                    } else {

                        // permission denied, boo! Disable the
                        // functionality that depends on this permission.

                    }
                    return;
                }

            }
        }
        @OnClick(R.id.setLocation)
        public void onClick() {
            Intent intent = new Intent();
            String longtitude = mLongitude.getText().toString();
            if (!TextUtils.isEmpty(longtitude)) {
                intent.putExtra(Constants.LONGITUDE, longtitude);
            } else {
                Toast.makeText(this, R.string.please_enter_longitude, Toast.LENGTH_SHORT).show();
                return;
            }
            String latitude = mLatitude.getText().toString();
            if (!TextUtils.isEmpty(latitude)) {
                intent.putExtra(Constants.LATITUDE, latitude);
            } else {
                Toast.makeText(this, R.string.please_enter_latitude, Toast.LENGTH_SHORT).show();
                return;
            }
            String latCommand = mSolarController.generatePacket("lat " +latitude,"00");
            String longitudeCmd = mSolarController.generatePacket("lon "+longtitude,"00");
            mPref.edit().putString(Constants.LAT_COMMAND,latCommand).commit();
            mPref.edit().putString(Constants.LONG_COMMAND,longitudeCmd).commit();
            mPref.edit().putString(Constants.LAST_LATITUDE,latitude).commit();
            mPref.edit().putString(Constants.LAST_LONGITUDE,latitude).commit();
            setResult(RESULT_OK, intent);
            finish();
        }
        @OnClick({R.id.back, R.id.location})
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.back:
                    setResult(RESULT_OK, new Intent());
                    finish();
                    break;
                case R.id.location:
                    Intent intent = new Intent();
                    String longtitude = mLongitude.getText().toString();
                    if (!TextUtils.isEmpty(longtitude)) {
                        intent.putExtra(Constants.LONGITUDE, longtitude);
                    } else {
                        Toast.makeText(this, R.string.please_enter_longitude, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    String latitude = mLatitude.getText().toString();
                    if (!TextUtils.isEmpty(latitude)) {
                        intent.putExtra(Constants.LATITUDE, latitude);
                    } else {
                        Toast.makeText(this, R.string.please_enter_latitude, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    Float lat = Float.parseFloat(latitude);
                    if (lat > 90 || lat < -90) {
                        Toast.makeText(this, R.string.longitude_alert, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    float lan = Float.parseFloat(longtitude);
                    if (lan > 180 || lan < -180) {
                        Toast.makeText(this, R.string.latitude_alert, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    String latCommand = mSolarController.generatePacket("lat "+latitude,"00");
                    String longitudeCmd = mSolarController.generatePacket("long "+longtitude,"00");
                    mPref.edit().putString(Constants.LAT_COMMAND,latCommand).commit();
                    mPref.edit().putString(Constants.LONG_COMMAND,longitudeCmd).commit();
                    mPref.edit().putString(Constants.LAST_LATITUDE,latitude).commit();
                    mPref.edit().putString(Constants.LAST_LONGITUDE,latitude).commit();
                    setResult(RESULT_OK, intent);
                    finish();
                    break;
            }
        }
    }

您只是在检查权限,您需要检查设备是否启用了位置。

LocationManager lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;

try {
    gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {}

try {
    network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {}

if(!gps_enabled && !network_enabled) {
    // notify user
    AlertDialog.Builder dialog = new AlertDialog.Builder(context);
    dialog.setMessage(context.getResources().getString(R.string.gps_network_not_enabled));
    dialog.setPositiveButton(context.getResources().getString(R.string.open_location_settings), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                // TODO Auto-generated method stub
                Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                context.startActivity(myIntent);
                //get gps
            }
        });
    dialog.setNegativeButton(context.getString(R.string.Cancel), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                // TODO Auto-generated method stub

            }
        });
    dialog.show();      
}