Update app permissions to support Android 10 and 11.
LocationBasedServices/maptology/pipeline/head This commit looks good

This commit is contained in:
2021-06-30 20:20:06 +02:00
parent 4ea3d60932
commit cfb2fcbe2f
9 changed files with 194 additions and 53 deletions
@@ -458,8 +458,17 @@ public class LocationService extends AbstractService {
* @return True if gps permissions are set.
*/
private boolean hasGpsPermissions() {
return ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
List<String> permissions = new ArrayList<>();
permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
permissions.add(Manifest.permission.ACCESS_BACKGROUND_LOCATION);
}
boolean granted = true;
for (String permission: permissions) {
granted &= ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED;
}
return granted;
}
/**
@@ -1,5 +1,6 @@
package com.maptology.android.app;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.snackbar.Snackbar;
import com.maptology.android.app.fragment.GrantListFragment;
import com.maptology.android.app.fragment.ManageFragment;
@@ -20,6 +21,7 @@ import com.maptology.android.feign.model.User;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
@@ -28,24 +30,27 @@ import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;
import com.google.android.material.navigation.NavigationView;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.core.content.PermissionChecker;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.PreferenceManager;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* The main activity that is launched once the device is registered.
@@ -104,7 +109,7 @@ public class MainActivity extends AppCompatActivity implements
public void onValueChanged(Value<DeviceHandle> source, DeviceHandle oldValue, DeviceHandle newValue) {
if (newValue != null) {
MenuItem webapp = navigationView.getMenu().findItem(R.id.menu_webapp);
MenuItem connect =navigationView.getMenu().findItem(R.id.menu_connect);
MenuItem connect = navigationView.getMenu().findItem(R.id.menu_connect);
connect.setVisible(newValue.getUser() == null);
webapp.setVisible(newValue.getUser() != null);
}
@@ -259,7 +264,6 @@ public class MainActivity extends AppCompatActivity implements
super.onDrawerClosed(view);
setTitle(R.string.application_short);
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
setTitle(R.string.drawer_title);
@@ -285,65 +289,89 @@ public class MainActivity extends AppCompatActivity implements
* Method to request location permission for the app.
*/
private void checkPermissions() {
String[] permissions = new String[] {android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION };
if (Build.VERSION.SDK_INT >= 29) {
permissions = new String[] {android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_BACKGROUND_LOCATION };
}
if (!hasAllPermissions(permissions)) {
Log.d(TAG, "Requesting permissions.");
ActivityCompat.requestPermissions(this, permissions, CODE_REQUEST_PERMISSIONS);
} else {
Log.d(TAG, "All permissions granted.");
if (! app.getRepository().isLocalizable()) return;
boolean coarse = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
boolean fine = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
if (!(coarse && fine)) {
Log.d(TAG, "Requesting foreground localization.");
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
PermissionDialogFragment dialog = new PermissionDialogFragment();
dialog.setForeground(true);
getSupportFragmentManager().beginTransaction().add(dialog, "foreground").commit();
} else {
requestForegroundLocalization();
}
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
boolean background = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_BACKGROUND_LOCATION) == PackageManager.PERMISSION_GRANTED;
if (!background){
Log.d(TAG, "Requesting background localization.");
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_BACKGROUND_LOCATION)) {
PermissionDialogFragment dialog = new PermissionDialogFragment();
dialog.setForeground(false);
getSupportFragmentManager().beginTransaction().add(dialog, "background").commit();
} else {
requestBackgroundLocalization();
}
}
}
}
/**
* Checks whether a permission has been granted.
*
* @param permission The permission to check.
* @return True if granted, false otherwise.
* Request the foreground localization permission.
*/
private boolean hasPermission(String permission) {
return PermissionChecker.checkSelfPermission(this, permission) == PermissionChecker.PERMISSION_GRANTED;
private void requestForegroundLocalization() {
ActivityCompat.requestPermissions(this, new String[] {
Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION
}, CODE_REQUEST_PERMISSIONS);
}
/**
* Checks if all permissions have been granted.
*
* @param permissions The permissions.
* @return True if all are granted, false if one is missing.
* Request background localization permission.
*/
private boolean hasAllPermissions(String[] permissions) {
for (String p: permissions) {
if (!hasPermission(p)) return false;
}
return true;
private void requestBackgroundLocalization() {
ActivityCompat.requestPermissions(this, new String[] {
Manifest.permission.ACCESS_BACKGROUND_LOCATION
}, CODE_REQUEST_PERMISSIONS);
}
/**
* Cancels the localization request.
*/
private void cancelLocalization() {
app.getRepository().setLocalizable(false);
AbstractService.stopServices(this);
Snackbar.make(findViewById(R.id.coordinator), R.string.permission_missing,
Snackbar.LENGTH_LONG).setAction(R.string.permission_configure, v -> {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivity(intent);
}).show();
}
/**
* Method handles the requested permission (whether it was given or not).
*
* @param requestCode requestCode identifies requested permission
* @param permissions permissions The permissions.
* @param grantResults results The results for the permissions.
* @param requestCode Identifies requested permission.
* @param permissions The permissions.
* @param grantResults The results for the permissions.
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case CODE_REQUEST_PERMISSIONS: {
boolean granted = true;
StringBuilder b = new StringBuilder();
for (int i = 0, s = Math.min(permissions.length, grantResults.length); i < s; i++) {
boolean next = (grantResults[i] == PackageManager.PERMISSION_GRANTED);
granted &= next;
b.append(permissions[i] + "=" + next + " ");
for (int i = 0; i < grantResults.length; i++) {
boolean value = grantResults[i] == PackageManager.PERMISSION_GRANTED;
granted &= value;
Log.d(TAG, permissions[i] + ": " + value);
}
Log.d(TAG, "Permission result: " + b.toString());
Log.d(TAG, "All permissions granted: " + granted);
if (!granted) {
prefs.edit().putBoolean(Repository.KEY_PRIVACY_LOCALIZE, false).apply();
showMissingPermission();
cancelLocalization();
} else {
AbstractService.runService(this);
checkPermissions();
}
break;
}
@@ -497,4 +525,46 @@ public class MainActivity extends AppCompatActivity implements
MANAGE
}
/**
* A dialog to explain the permissions.
*/
public static class PermissionDialogFragment extends DialogFragment {
/**
* Marks the fragment either as foreground or background.
*
* @param foreground True for foreground, false for background.
*/
public void setForeground(boolean foreground) {
Bundle b = new Bundle();
b.putBoolean("foreground", foreground);
setArguments(b);
}
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
boolean foreground = getArguments().getBoolean("foreground");
MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(getActivity());
builder.setTitle(R.string.permission_required);
builder.setMessage(foreground ? R.string.permission_foreground_explain : R.string.permission_background_explain);
builder.setPositiveButton(android.R.string.ok, (dialog, which) -> {
if (foreground) {
((MainActivity)getActivity()).requestForegroundLocalization();
} else {
((MainActivity)getActivity()).requestBackgroundLocalization();
}
});
builder.setNegativeButton(android.R.string.cancel, (dialog, which) -> {
dialog.dismiss();
});
builder.setOnCancelListener(dialog -> ((MainActivity)getActivity()).cancelLocalization());
return builder.create();
}
}
}
@@ -17,16 +17,19 @@ import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import androidx.core.content.pm.PackageInfoCompat;
import androidx.preference.CheckBoxPreference;
import androidx.preference.Preference;
import androidx.preference.PreferenceCategory;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceGroup;
import androidx.preference.PreferenceManager;
import androidx.preference.PreferenceScreen;
import android.util.Log;
import android.view.LayoutInflater;
@@ -144,6 +147,18 @@ public class SettingsFragment extends PreferenceFragmentCompat {
*/
private PreferenceGroup developmentGroup;
/**
* A listener for shared preferences.
*/
private SharedPreferences.OnSharedPreferenceChangeListener preferenceListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (Repository.KEY_PRIVACY_LOCALIZE.equals(key)) {
updateLocalize();
}
}
};
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
@@ -179,6 +194,29 @@ public class SettingsFragment extends PreferenceFragmentCompat {
}
}
@Override
public void onResume() {
super.onResume();
PreferenceManager.getDefaultSharedPreferences(getContext()).registerOnSharedPreferenceChangeListener(preferenceListener);
updateLocalize();
}
@Override
public void onPause() {
super.onPause();
PreferenceManager.getDefaultSharedPreferences(getContext()).unregisterOnSharedPreferenceChangeListener(preferenceListener);
}
private void updateLocalize() {
CheckBoxPreference p = findPreference(Repository.KEY_PRIVACY_LOCALIZE);
if (p != null) {
boolean state = getApp().getRepository().isLocalizable();
if (p.isChecked() != state) {
p.setChecked(state);
}
}
}
/**
* Determines whether the logger switch is available.
*
@@ -10,7 +10,7 @@ import com.maptology.android.feign.model.User;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import androidx.preference.PreferenceManager;
/**
@@ -149,9 +149,9 @@ public class Repository {
*/
public Repository(Context context) {
this.context = context;
this.deviceHandle = new PersistentValue<DeviceHandle>(this, new JacksonSerializer<DeviceHandle>(DeviceHandle.class), "device.json");
this.user = new PersistentValue<User>(this, new JacksonSerializer<User>(User.class), "user.json");
this.lastUpdate = new PersistentValue<ReleasedLocation>(this, new JacksonSerializer<ReleasedLocation>(ReleasedLocation.class), "update.json");
this.deviceHandle = new PersistentValue<>(this, new JacksonSerializer<>(DeviceHandle.class), "device.json");
this.user = new PersistentValue<>(this, new JacksonSerializer<>(User.class), "user.json");
this.lastUpdate = new PersistentValue<>(this, new JacksonSerializer<>(ReleasedLocation.class), "update.json");
}
/**
@@ -172,12 +172,24 @@ public class Repository {
return getPreference(KEY_PRIVACY_LOCALIZE, R.bool.privacy_localize_default);
}
/**
* Enables or disables localization.
*
* @param value True to enable, false to disable.
*/
public void setLocalizable(boolean value) {
setPreference(KEY_PRIVACY_LOCALIZE, value);
}
/**
* Determines whether logging is enabled.
*
* @return True if logging is enabled, false otherwise.
*/
public boolean isLoggable() {
return getPreference(KEY_PRIVACY_LOGGABLE, R.bool.privacy_loggable_default);
}
/**
* Sets whether the user has allowed that his positions can be used for research.
*
@@ -5,6 +5,12 @@
<string name="terms_button_accept">Bedingungen annehmen</string>
<string name="terms_permisson_checkbox">Erlaubst Du uns die anonyme Nutzung Deiner Positionsdaten für Forschungszwecke? Du kannst Deine Wahl jederzeit in den Einstellungen der App ändern.</string>
<string name="permission_required">Berechtigung erforderlich</string>
<string name="permission_foreground_explain">Damit Du Deinen Standort in der Karte anzeigen und mit anderen teilen kannst, benötigt Maptology die Berechtigung zum Zugriff auf Deinen Standort.</string>
<string name="permission_background_explain">Damit Du Deinen Standort auch dann teilen kannst, wenn Du die App nicht geöffnet hast, benötigt Maptology die Berechtigung zur Standortbestimmung im Hintergrund.</string>
<string name="permission_missing">Für die Standortbestimmung fehlt eine wichtige Berechtigung.</string>
<string name="permission_configure">Ändern</string>
<!-- a language code that we will use to detect the translation currently active -->
<string name="language_code">de</string>
@@ -5,6 +5,12 @@
<string name="terms_button_accept">Accept conditions</string>
<string name="terms_permisson_checkbox">Do you want to share your location anonymously for research? You can change your decision in the settings at any time.</string>
<string name="permission_required">Permission required</string>
<string name="permission_foreground_explain">Maptology needs permission to access your location to be able to display it on a map and to share it with your friends.</string>
<string name="permission_background_explain">Maptology needs permission to access your location in the background, so you can share your location even when you are not using the app.</string>
<string name="permission_missing">Localization is missing an important permission.</string>
<string name="permission_configure">Setup</string>
<!-- a language code that we will use to detect the translation currently active -->
<string name="language_code">en</string>
+2 -2
View File
@@ -1,13 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.MaptologyTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<style name="Theme.MaptologyTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="preferenceTheme">@style/settingsTheme</item>
</style>
<style name="Theme.MaptologyTheme.NoActionBar" parent="Theme.AppCompat.Light.NoActionBar">
<style name="Theme.MaptologyTheme.NoActionBar" parent="Theme.MaterialComponents.Light.NoActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
+1 -1
View File
@@ -1,6 +1,6 @@
buildscript {
dependencies {
classpath 'com.android.tools.build:gradle:4.1.2'
classpath 'com.android.tools.build:gradle:4.2.1'
classpath 'com.google.android.gms:oss-licenses-plugin:0.10.2'
classpath 'org.handte.gradle:gradle-android-eclipse:1.0.0'
}
+1 -1
View File
@@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-6.7.1-bin.zip