Я создал программу, которая будет получать доступ к вашему местоположению, для этого мне требовалось разрешение на доступ к моему местоположению. Я знаю, какое разрешение нужно применить, и как обработать это разрешение, но я не мог этого сделать в своей основной программе. Каждый раз, когда я пытаюсь добавить разрешение, он не читает 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 ответа
Вам необходимо добавить разрешение в манифест, чтобы поддерживать API, равные 23 и выше, вы также должны запрашивать программно.
Вам нужно добавить это в свой манифест.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Похожие вопросы
Новые вопросы
android
Android - это мобильная операционная система Google, используемая для программирования или разработки цифровых устройств (смартфоны, планшеты, автомобили, телевизоры, одежда, стекло, IoT). Для тем, связанных с Android, используйте специальные теги Android, такие как android-intent, android-activity, android-адаптер и т. Д. Для вопросов, не связанных с разработкой или программированием, но связанных с платформой Android, используйте эту ссылку: https: // android.stackexchange.com .
FusedLocationProviderAPI
.