如何允许应用访问设备的位置

时间:2017-07-31 05:43:48

标签: android geolocation location android-permissions

我创建了将访问您所在位置的程序,因为我需要允许访问我的位置。我知道要应用的权限以及如何处理该权限但我无法在我的主程序中完成。每次我尝试添加权限它都不会读取 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();
}

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

你需要在你的maniufest中添加它。

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