#android #gps #location
#Android #gps #Расположение
Вопрос:
У меня есть класс, который проверяет разрешение на местоположение и показывает диалоговое окно, если оно не предоставлено, и оно работает нормально, если я запускаю его отдельно, но когда я пытаюсь использовать его в другом классе, он выдает исключение
«Попытка вызвать виртуальный метод ‘android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()’ для нулевой ссылки на объект»
Это мой класс :
public class LocSettingActivity extends AppCompatActivity {
private static final int REQUEST_CHECK_SETTINGS = 0x1;
private static GoogleApiClient mGoogleApiClient;
private static final int ACCESS_FINE_LOCATION_INTENT_ID = 3;
private static final String BROADCAST_ACTION = "android.location.PROVIDERS_CHANGED";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loc_setting);
initGoogleAPIClient(this);//Init Google API Client
}
/* Initiate Google API Client */
private void initGoogleAPIClient(Context context) {
//Without Google API Client Auto Location Dialog will not work
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
/* Check Location Permission for Marshmallow Devices */
public void checkPermissions(Context context) {
initGoogleAPIClient(context);
if (Build.VERSION.SDK_INT >= 23) {
if (ContextCompat.checkSelfPermission(context,
android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)
requestLocationPermission();
else
showSettingDialog();
} else
showSettingDialog();
}
/* Show Popup to access User Permission */
public void requestLocationPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(LocSettingActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(LocSettingActivity.this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
ACCESS_FINE_LOCATION_INTENT_ID);
} else {
ActivityCompat.requestPermissions(LocSettingActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
ACCESS_FINE_LOCATION_INTENT_ID);
}
}
/* Show Location Access Dialog */
public void showSettingDialog() {
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);//Setting priotity of Location request to high
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);//5 sec Time interval for location update
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true); //this is the key ingredient to show dialog always when GPS is off
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
final LocationSettingsStates state = result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied. The client can initialize location
// requests here.
// updateGPSStatus("GPS is Enabled in your device");
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the user
// a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(LocSettingActivity.this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
// Ignore the error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way to fix the
// settings so we won't show the dialog.
break;
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
// Check for the integer request code originally supplied to startResolutionForResult().
case REQUEST_CHECK_SETTINGS:
switch (resultCode) {
case RESULT_OK:
Log.e("Settings", "Result OK");
// updateGPSStatus("GPS is Enabled in your device");
//startLocationUpdates();
break;
case RESULT_CANCELED:
Log.e("Settings", "Result Cancel");
// updateGPSStatus("GPS is Disabled in your device");
break;
}
break;
}
}
@Override
protected void onResume() {
super.onResume();
registerReceiver(gpsLocationReceiver, new IntentFilter(BROADCAST_ACTION));//Register broadcast receiver to check the status of GPS
checkPermissions(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
//Unregister receiver on destroy
if (gpsLocationReceiver != null)
unregisterReceiver(gpsLocationReceiver);
}
//Run on UI
public Runnable sendUpdatesToUI = new Runnable() {
public void run() {
showSettingDialog();
}
};
// Broadcast receiver to check status of GPS
private BroadcastReceiver gpsLocationReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
try {
//If Action is Location
if (intent.getAction().matches(BROADCAST_ACTION)) {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//Check if GPS is turned ON or OFF
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Log.e("About GPS", "GPS is Enabled in your device");
// updateGPSStatus("GPS is Enabled in your device");
} else {
//If GPS turned OFF show Location Dialog
new Handler().postDelayed(sendUpdatesToUI, 10);
// showSettingDialog();
// updateGPSStatus("GPS is Disabled in your device");
checkPermissions(context);
Log.e("About GPS", "GPS is Disabled in your device");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
//Method to update GPS status text
private void updateGPSStatus(Context context,String status) {
Toast.makeText(context, status, Toast.LENGTH_SHORT).show();
}
/* On Request permission method to check the permisison is granted or not for Marshmallow Devices */
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
try {
switch (requestCode) {
case ACCESS_FINE_LOCATION_INTENT_ID: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
amp;amp; grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//If permission granted show location dialog if APIClient is not null
if (mGoogleApiClient == null) {
initGoogleAPIClient(this);
showSettingDialog();
} else
showSettingDialog();
} else {
// updateGPSStatus("Location Permission denied.");
Toast.makeText(LocSettingActivity.this, "Location Permission denied.", Toast.LENGTH_SHORT).show();
simpleAlertGps();
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void simpleAlertGps() {
try {
android.app.AlertDialog alertDialog = new android.app.AlertDialog.Builder(this).create();
alertDialog.setTitle("");
alertDialog.setMessage("Your Gps Must Be On For Better Result");
alertDialog.setButton(android.app.AlertDialog.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try {
/*Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);*/
checkPermissions(LocSettingActivity.this);
dialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(LocSettingActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
alertDialog.show();
} catch (Exception e) {
e.printStackTrace();
}
}
И вот я получаю это в другом классе
LocSettingActivity locSettingActivity = new LocSettingActivity();
public void onResume() {
super.onResume();
locSettingActivity.checkPermissions(this);
}
public void openTuckLocation(View view) {
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
in=new Intent(PagerMainActivity.this, MapsActivityLocation.class);
}
else {
locSettingActivity.checkPermissions(this);
return;
}
}
Комментарии:
1. если вы используете для получения местоположения, используйте разрешение местоположения в общедоступном классе и импортируйте его туда, где вы хотите указать местоположение
2. Я только получаю разрешение на этом занятии, а не на что-то еще
Ответ №1:
вместо
locSettingActivity.checkPermissions(this);
использовать
locSettingActivity.checkPermissions(getApplicationContext);
Или
locSettingActivity.checkPermissions(ActivityName.this);
поскольку иногда контекст также может выдавать ошибку