【问题标题】:How to Allow app to access device's location如何允许应用访问设备的位置
【发布时间】:2018-01-06 13:47:37
【问题描述】:

我创建了可以访问您的位置的程序,为此我需要允许访问我的位置。我知道要应用的权限以及如何处理该权限,但我无法在我的主程序中完成。每次我尝试添加权限时它都没有读取 requestPermission() ,为了让它读取我已经添加了 @RequiresApi(api = Build.VERSION_CODES.M) 这个.谁能告诉我如何在我的代码中添加它。

我有两个类:1) NetwrokProviderActivity,我在其中调用我的 2) 类 ApplocationService。在这里我分享我的代码。请帮我解决这个问题

我需要的权限

if (ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.INTERNET
        },10);
        return;

    }
 @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    switch (requestCode)
    {
        case 10:
                if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                {
                    configureButton();
                    return;
                }
    }
}

我需要在其中添加此权限的ApplocationClass

public AppLocationService(Context context) {
    this.context = context;
    getLocation();
}

public Location getLocation() {
    try {
        locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);

        isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

        isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isNetworkEnabled) {

        } else {
            this.canGetLocation = true;

            if (isNetworkEnabled) {

                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                    if (location != null) {

                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }

            }

            if(isGPSEnabled) {

                if(location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);


                    if(locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

                        if(location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return location;
}

NetwrokprovideActivity

AppLocationService appLocationService;
Button btnNetworkProvider;
TextView txtLati;
TextView txtLongi;
TextView txtAddress;
TextView txtCity;
TextView txtState;
TextView txtCountry;
TextView txtPostalCode;
protected Context context=this;
Location location;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;


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


    txtLati= (TextView) findViewById(R.id.txt_Latitude);
    txtLongi= (TextView) findViewById(R.id.txt_Longitude);
    txtAddress= (TextView) findViewById(R.id.txt_NetAddress);
    txtCity= (TextView) findViewById(R.id.txt_NetCity);
    txtState= (TextView) findViewById(R.id.txt_NetState);
    txtCountry= (TextView) findViewById(R.id.txt_NetCountry);
    txtPostalCode= (TextView) findViewById(R.id.txt_NetPostalCode);

    appLocationService = new AppLocationService(NetworkProviderActivity.this);


    btnNetworkProvider = (Button) findViewById(R.id.btn_Location_NetworkProvider);
    btnNetworkProvider.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {

            Location nwLocation = appLocationService
                    .getLocation();

            if (nwLocation != null) {
                double latitude = nwLocation.getLatitude();
                double longitude = nwLocation.getLongitude();

                List<Address> addresses;
                Geocoder geocoder=new Geocoder(context, Locale.getDefault());

                txtLati.setText("Latitude: "+latitude);
                txtLongi.setText("Longitude: "+ longitude);

                try {
                    addresses = geocoder.getFromLocation(latitude, longitude, 1);
                    if (addresses != null && addresses.size() > 0) {
                        String address = addresses.get(0).getAddressLine(0);
                        String city = addresses.get(0).getLocality();
                        String state = addresses.get(0).getAdminArea();
                        String country = addresses.get(0).getCountryName();
                        String postalCode = addresses.get(0).getPostalCode();
                        String knownName = addresses.get(0).getFeatureName();

                        Log.e(TAG,"network...");

                        txtAddress.setText("Address: "+address);
                        txtCity.setText("City: "+city);
                        txtState.setText("State: "+state);
                        txtCountry.setText("Country: "+country);
                        txtPostalCode.setText("Postal Code: "+postalCode);
                    }


                } catch (IOException e) {
                    e.printStackTrace();
                }


                Toast.makeText(
                        getApplicationContext(),
                        "Mobile Location (NW): \nLatitude: " + latitude
                                + "\nLongitude: " + longitude,
                        Toast.LENGTH_LONG).show();
            } else {
                showSettingsAlert("NETWORK");
            }

        }
    });
}


public void showSettingsAlert(String provider) {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(
           NetworkProviderActivity.this);

    alertDialog.setTitle(provider + " SETTINGS");

    alertDialog
            .setMessage(provider + " is not enabled! Want to go to settings menu?");

    alertDialog.setPositiveButton("Settings",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(
                            Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    NetworkProviderActivity.this.startActivity(intent);
                }
            });

    alertDialog.setNegativeButton("Cancel",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

    alertDialog.show();
}

【问题讨论】:

  • 最好使用FusedLocationProviderAPI
  • 它只给出纬度和经度。
  • 那么你需要什么?
  • 我需要完整的地址。
  • @Piyush 感谢您的建议。我已经尝试过 FusedLocationProvider API。但是,我想要我的完整地址,即街道编号,本地地址。

标签: android geolocation location android-permissions


【解决方案1】:

您需要在清单上添加权限,以支持等于或高于 23 的 API,您还必须以编程方式请求。

【讨论】:

  • 我也加了。
【解决方案2】:

您需要在清单中添加它。

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

【讨论】:

  • 我已经在我的 mainfest 中添加了这一点。你能告诉我在我的代码中添加权限的位置吗(类:ApplocationService)。因为我无法读取我的 requestpermission() 权限方法。
  • if (isReadStorageAllowed()) { 添加您的谷歌地图活动 } else { requestStoragePermission(); }
  • private boolean isReadStorageAllowed() { //获取权限状态 int result = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION); //如果授予权限返回true if (result == PackageManager.PERMISSION_GRANTED) return true; //如果没有授予权限返回false return false; }
  • //请求权限 private void requestStoragePermission() { if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)) { //如果用户之前拒绝了权限,你的代码就会来to this block //这里可以解释一下为什么需要这个权限 } /最后请求权限 ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MAP_CODE); }
  • 能否请您在我的给定代码中添加此代码。我无法获取它,在我的代码中添加此代码的位置。
猜你喜欢
  • 2017-06-21
  • 1970-01-01
  • 1970-01-01
  • 2017-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-14
  • 2012-04-16
相关资源
最近更新 更多