'Follow-up code not executing after checking permissions
The code I have written should check the permissions in the OnStart method and regardless of the outcome of whether the user gives access, the same two pieces of code should execute:
- Starting my service
- Auto-login the user if they have provided credentials before
If I retype my credentials and turn the app on and off then on again - then for around 2-5 minutes it will automatically log me in. If I have the app off for longer than that, the autologin will not work.
OnStart:
@Override
protected void onStart() {
super.onStart();
List<String> permissions = new ArrayList<>();
permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
permissions.add(Manifest.permission.ACTIVITY_RECOGNITION);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.S)
permissions.add(Manifest.permission.SCHEDULE_EXACT_ALARM);
checkPermission(permissions.toArray(new String[0]), INITIAL_REQUESTS_CODE);
}
checkPermission Function:
public void checkPermission(String[] permissions, int requestCode) {
// Checking if permission is not granted
boolean ungrantedPermissions = false;
for (String permission : permissions) {
if (ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_DENIED) {
ungrantedPermissions = true;
break;
}
}
if (ungrantedPermissions)
ActivityCompat.requestPermissions(this, permissions, requestCode);
else{
startStepCounterService();
attemptLoginWithSavedCredentials();
}
}
onRequestPermissionResult:
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode,
permissions,
grantResults);
startStepCounterService();
attemptLoginWithSavedCredentials();
}
startStepCounterService Function:
private void startStepCounterService() {
if(!isMyServiceRunning(StepCounterService.class))
{
Intent newIntent = new Intent(this, StepCounterService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(newIntent);
} else {
startService(newIntent);
}
}
}
attemptLoginWithSavedCredentials Function:
private void attemptLoginWithSavedCredentials() {
String savedUsername = SaveSharedPreference.getUserName(this);
String savedPassword = SaveSharedPreference.getUserPassword(this);
if(!savedUsername.isEmpty() && !savedPassword.isEmpty())
{
LoadingExtensions.showLoadingIcon(loadingIndicator, rootView);
loginManager.login(savedUsername, savedPassword);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
