片段中请求位置权限

时间:2019-09-10 09:11:09

标签: android permissions fragment

我想在一个片段中请求精细和粗糙的位置,以获取设备的位置。当我打开片段时,它要求获得许可,但该应用程序之前已关闭。当我授予许可并重新打开应用程序时,它可以工作,但是我希望该应用程序之前不要关闭。我希望任何人都知道我做错了..thx



import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.core.content.ContextCompat;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;


public class Location extends Fragment implements LocationListener, OnMapReadyCallback {

    View view;

    TextView textView_Longitude, textView_Latitute, textView_Altitute, textView_Speed;
    ImageView imageView_center_map;

    SupportMapFragment mapFragment;
    private GoogleMap mMap;

    android.location.Location location;

    private LocationListener locationListener = null;
    private LocationManager locationManager = null;

    private final long MIN_TIME = 1000;
    private final long MIN_DIST = 5;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_location, container, false);

        textView_Latitute = (TextView) view.findViewById(R.id.textView_Latitude);
        textView_Longitude = (TextView) view.findViewById(R.id.textView_Longitude);
        textView_Altitute = (TextView) view.findViewById(R.id.textView_Altitude);
        textView_Speed = (TextView) view.findViewById(R.id.textView_Speed);
        imageView_center_map = (ImageView) view.findViewById(R.id.imageView_center_map);

        mapFragment = (SupportMapFragment) this.getChildFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);

        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PackageManager.PERMISSION_GRANTED);
            requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PackageManager.PERMISSION_GRANTED);
        }

        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME, MIN_DIST, (LocationListener) this);
        } else {
            textView_Longitude.setText("no GPS Signal");
            textView_Latitute.setText("no GPS Signal");
        }

        location = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER);
        onLocationChanged(location);

        imageView_center_map.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LatLng latLng_current_position = new LatLng(location.getLatitude(), location.getLongitude());
                mMap.addMarker(new MarkerOptions().position(latLng_current_position).title("You are here"));
                float zoomLevel = 15;
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng_current_position, zoomLevel));
            }
        });

        return view;
    }

    @Override
    public void onLocationChanged(android.location.Location location) {
        double latitute = location.getLatitude();
        double longitute = location.getLongitude();
        double altitute = Math.round(location.getAltitude());
        String string_latitute = String.valueOf(latitute);
        String string_longitute = String.valueOf(longitute);
        String string_altitute = String.valueOf(altitute);
        textView_Latitute.setText("Latitute: " + string_latitute);
        textView_Longitude.setText("Longitute: " + string_longitute);
        textView_Altitute.setText("Altitute: " + string_altitute + "m");
        float speed_in_kmh = (float) ((location.getSpeed() * 3600) / 1000);
        String string_speed = String.valueOf(speed_in_kmh);
        textView_Speed.setText("Speed: " + string_speed + "km/h");
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }


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

        LatLng latLng_current_position = new LatLng(location.getLatitude(), location.getLongitude());
        mMap.addMarker(new MarkerOptions().position(latLng_current_position).title("You are here"));
        float zoomLevel = 15;
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng_current_position, zoomLevel));

    }

}

3 个答案:

答案 0 :(得分:0)

尝试一下:

        // Change these two lines
        // --------------------------------------------
//        requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PackageManager.PERMISSION_GRANTED);
//        requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PackageManager.PERMISSION_GRANTED);

        // to this one
        requestPermissions(new String[]{
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
        }, PackageManager.PERMISSION_GRANTED);

答案 1 :(得分:0)

您必须在活动中覆盖此方法,并且如果授予了权限,则只需要向网络或gps提供者请求位置。

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

        } else {
            // permission denied

        }
        return;
    }
}}

答案 2 :(得分:0)

请替换此部分

 if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME, MIN_DIST, (LocationListener) this);
        } else {
            textView_Longitude.setText("no GPS Signal");
            textView_Latitute.setText("no GPS Signal");
        }