Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix restore and save backup for newer android versions #1246

Merged
merged 3 commits into from
Sep 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions onebusaway-android/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,6 @@
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
<uses-permission android:name="${applicationId}.permission.TRIP_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,19 @@
import android.content.ContentProviderClient;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import org.apache.commons.io.FileUtils;
import org.onebusaway.android.R;
import org.onebusaway.android.provider.ObaContract;
import org.onebusaway.android.provider.ObaProvider;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
* Big note, that this is currently fairly unsafe.
Expand All @@ -42,33 +46,43 @@
*/
public final class Backup {

private static final String FILE_NAME = "OneBusAway.backup";

private static final String DIRECTORY_NAME = "OBABackups";
public static final String FILE_NAME = "OneBusAway.backup";

private static File getDB(Context context) {
return ObaProvider.getDatabasePath(context);
}

private static File getBackup() {
File backupDir = getBackupDirectory();
return new File(backupDir, FILE_NAME);
}

/**
* Performs a backup to the SD card.
* Initiates a backup process, allowing the user to choose a location
* (such as the Documents directory) to save the backup file.
*/
public static String backup(Context context) throws IOException {
// We need two things:
// 1. The path to the database;
// 2. The path on the SD card to the backup file.
File backupPath = getBackup();
FileUtils.copyFile(getDB(context), backupPath);
return backupPath.getAbsolutePath();
public static void backup(Context context,Uri uri) throws IOException{
try (InputStream inputStream = new FileInputStream(getDB(context));
OutputStream outputStream = context.getContentResolver().openOutputStream(uri)) {
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
if (outputStream != null) {
outputStream.write(buffer, 0, length);
}
}
if (outputStream != null) {
outputStream.flush();
}
Toast.makeText(context,
context.getString(R.string.preferences_db_saved),
Toast.LENGTH_LONG).show();
Log.d("Backup", "Database backup saved successfully to: " + uri);
} catch (IOException e) {
Toast.makeText(context,
context.getString(R.string.preferences_db_save_error, e.getMessage()),
Toast.LENGTH_LONG).show();
Log.e("Backup", "Error saving database backup", e);
}
}

/**
* Performs a restore from the SD card.
* Restores data from the location where the user saved the backup.
* @param uri URI to the backup file, as returned by the system UI picker. Following targeting
* Android 11 we can't access this directory and need to rely on the system UI picker.
*/
Expand Down Expand Up @@ -96,15 +110,4 @@ public static void restore(Context context, Uri uri) throws IOException {
}
}

public static boolean isRestoreAvailable() {
return getBackup().exists();
}

public static File getBackupDirectory() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS + "/" + DIRECTORY_NAME);
} else {
return Environment.getExternalStoragePublicDirectory(DIRECTORY_NAME);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,8 @@
*/
package org.onebusaway.android.io.backup;

import static org.onebusaway.android.io.backup.Backup.getBackupDirectory;
import static org.onebusaway.android.ui.PreferencesActivity.REQUEST_CODE_RESTORE_BACKUP;

import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.provider.DocumentsContract;
import android.util.AttributeSet;

public class RestorePreference extends Preference {
Expand All @@ -50,20 +43,11 @@ public boolean isPersistent() {

@Override
public boolean isEnabled() {
// This is only enabled if the SD card is attached.
final String state = Environment.getExternalStorageState();
// Also, this is only enabled if there's a backup file
return (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state) ||
Environment.MEDIA_MOUNTED.equals(state)) &&
Backup.isRestoreAvailable();
return true;
}

@Override
protected void onClick() {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.setType("*/*");
intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, getBackupDirectory().toURI());
((PreferenceActivity) getContext()).startActivityForResult(intent, REQUEST_CODE_RESTORE_BACKUP);
super.onClick();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,7 @@
*/
package org.onebusaway.android.io.backup;

import org.onebusaway.android.util.BackupUtils;

import android.content.Context;
import android.os.Environment;
import android.preference.Preference;
import android.util.AttributeSet;

Expand Down Expand Up @@ -46,13 +43,11 @@ public boolean isPersistent() {

@Override
public boolean isEnabled() {
// This is only enabled if the SD card is attached.
return Environment.MEDIA_MOUNTED
.equals(Environment.getExternalStorageState());
return true;
}

@Override
protected void onClick() {
BackupUtils.save(getContext());
super.onClick();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,12 @@
*/
package org.onebusaway.android.ui;

import static org.onebusaway.android.util.PermissionUtils.RESTORE_BACKUP_PERMISSION_REQUEST;
import static org.onebusaway.android.util.PermissionUtils.SAVE_BACKUP_PERMISSION_REQUEST;
import static org.onebusaway.android.util.PermissionUtils.STORAGE_PERMISSIONS;

import static org.onebusaway.android.util.UIUtils.setAppTheme;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
Expand All @@ -47,9 +42,7 @@
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;

import com.google.firebase.analytics.FirebaseAnalytics;

Expand All @@ -60,13 +53,9 @@
import org.onebusaway.android.io.elements.ObaRegion;
import org.onebusaway.android.provider.ObaContract;
import org.onebusaway.android.region.ObaRegionsTask;
import org.onebusaway.android.travelbehavior.TravelBehaviorManager;
import org.onebusaway.android.travelbehavior.io.coroutines.FirebaseDataPusher;
import org.onebusaway.android.travelbehavior.utils.TravelBehaviorUtils;
import org.onebusaway.android.util.BackupUtils;
import org.onebusaway.android.util.BuildFlavorUtils;
import org.onebusaway.android.util.PermissionUtils;
import org.onebusaway.android.util.PreferenceUtils;
import org.onebusaway.android.util.ShowcaseViewUtils;

import java.net.MalformedURLException;
Expand All @@ -83,6 +72,7 @@ public class PreferencesActivity extends PreferenceActivity
public static final String SHOW_CHECK_REGION_DIALOG = ".checkRegionDialog";

public static final int REQUEST_CODE_RESTORE_BACKUP = 1234;
public static final int REQUEST_CODE_SAVE_BACKUP = 1199;

Preference mPreference;

Expand Down Expand Up @@ -373,13 +363,9 @@ public boolean onPreferenceClick(Preference pref) {
null);
AboutActivity.start(this);
} else if (pref.equals(mSaveBackup)) {
// SavePreference will get the click event but will ignore it if permissions haven't
// been granted yet so we can handle permissions here
maybeRequestPermissions(SAVE_BACKUP_PERMISSION_REQUEST);
BackupUtils.createBackupFile(this);
} else if (pref.equals(mRestoreBackup)){
// RestorePreference will get the click event but will ignore it if permissions haven't
// been granted yet so we can handle permissions here.
maybeRequestPermissions(RESTORE_BACKUP_PERMISSION_REQUEST);
BackupUtils.selectBackupFile(this);
} else if (pref.equals(pushFirebaseData)) {
// Try to push firebase data to the server
FirebaseDataPusher pusher = new FirebaseDataPusher();
Expand All @@ -391,69 +377,21 @@ public boolean onPreferenceClick(Preference pref) {
return true;
}

private void maybeRequestPermissions(int permissionRequest) {
if (!PermissionUtils.hasGrantedAllPermissions(this, STORAGE_PERMISSIONS)) {
// Request permissions from the user
ActivityCompat.requestPermissions(this, STORAGE_PERMISSIONS, permissionRequest);
}
}

@SuppressLint("MissingPermission")
@Override
public void onRequestPermissionsResult(
int requestCode, String[] permissions, int[] grantResults) {
int result = PackageManager.PERMISSION_DENIED;
if (requestCode == SAVE_BACKUP_PERMISSION_REQUEST || requestCode == RESTORE_BACKUP_PERMISSION_REQUEST) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
result = PackageManager.PERMISSION_GRANTED;
// User granted permission
if (requestCode == SAVE_BACKUP_PERMISSION_REQUEST) {
BackupUtils.save(this);
} else {
// For restore, ask them to browse to the backup file, because after targeting Android 11 we can't just access it directly
// This is automatically invoked by RestorePreference.onClick(), so do nothing here
}
} else {
showStoragePermissionDialog(this, requestCode);
}
}
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_RESTORE_BACKUP) {
if(data != null){
BackupUtils.restore(this, data.getData());
if(resultCode != RESULT_OK) return;
Uri uri = data.getData();
if(uri != null){
if (requestCode == REQUEST_CODE_RESTORE_BACKUP) {
BackupUtils.restore(this, uri);
}else if(requestCode == REQUEST_CODE_SAVE_BACKUP){
BackupUtils.save(this,uri);
}
}
}

/**
* Shows the dialog to explain why storage permissions are needed
* @param activity Activity used to show the dialog
* @param requestCode The requesting permission code (SAVE_BACKUP_PERMISSION_REQUEST or RESTORE_BACKUP_PERMISSION_REQUEST)
*/
private void showStoragePermissionDialog(Activity activity, int requestCode) {
androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(this)
.setTitle(R.string.storage_permissions_title)
.setMessage(R.string.storage_permissions_message)
.setCancelable(false)
.setPositiveButton(R.string.ok,
(dialog, which) -> {
// Request permissions from the user
ActivityCompat
.requestPermissions(activity, STORAGE_PERMISSIONS, requestCode);
}
)
.setNegativeButton(R.string.no_thanks,
(dialog, which) -> {
// No-op
}
);
builder.create().show();
}

@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (preference.equals(mCustomApiUrlPref) && newValue instanceof String) {
Expand Down
Loading
Loading