【问题标题】:Request location permission in fragment在片段中请求位置权限
【发布时间】:2019-09-10 18:22:44
【问题描述】:

我想在片段中请求精细和粗略的位置来获取设备的位置。当我打开片段时,它会请求许可,但应用程序会先关闭。当我授予权限并重新打开应用程序时,它可以工作,但我希望应用程序之前不要关闭。我希望有人知道我做错了什么.. 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));

    }

}

【问题讨论】:

  • 您应该只调用一次requestPermissions 方法并在传递给它的字符串数组中请求多个权限
  • 你可以按照@RahulKhurana 所说的去做,或者只是从包含片段的活动中正常请求权限

标签: android permissions fragment


【解决方案1】:

试试这个:

        // 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);

【讨论】:

    【解决方案2】:

    您必须在活动中覆盖此方法,如果授予权限,则只需向网络或 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;
        }
    }}
    

    【讨论】:

    • 所以如果我启动应用程序,它会在不打开片段的情况下请求授权?
    • 是的,您必须请求活动的许可
    • 但是当我切换到这个片段时,没有办法只打开权限请求......因为我希望用户可以在不授予权限的情况下使用应用程序的其他片段
    • 那么未经许可您无法在片段中获取位置
    • 可能的方法是,当在 onRequestPermissionsResult 中授予权限时,您是否可以从活动中调用片段方法
    【解决方案3】:

    请更换此部分

     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");
            }
    

    【讨论】:

    • 替换它,但应用程序在没有这部分的情况下也会关闭
    猜你喜欢
    • 2018-05-30
    • 1970-01-01
    • 2016-12-06
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 2018-12-21
    • 2017-09-13
    相关资源
    最近更新 更多