1
0
mirror of https://codeberg.org/Freeyourgadget/Gadgetbridge synced 2024-11-27 20:36:51 +01:00

First try at periodic db export

This commit is contained in:
Felix Konstantin Maurer 2018-01-04 15:13:06 +01:00
parent 0e2c73e6fe
commit c19da6c6d8
No known key found for this signature in database
GPG Key ID: 74104C914D3A4DE3
7 changed files with 219 additions and 12 deletions

View File

@ -345,6 +345,12 @@
<action android:name="nodomain.freeyourgadget.gadgetbridge.callcontrol" />
</intent-filter>
</receiver>
<receiver
android:enabled="true"
android:name="nodomain.freeyourgadget.gadgetbridge.database.PeriodicExporter"
android:exported="false">
</receiver>
<!--
forcing the DebugActivity to portrait mode avoids crashes with the progress

View File

@ -22,15 +22,20 @@ import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceCategory;
import android.preference.PreferenceManager;
import android.provider.DocumentsContract;
import android.provider.OpenableColumns;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.widget.Toast;
@ -46,6 +51,7 @@ import java.util.Locale;
import nodomain.freeyourgadget.gadgetbridge.BuildConfig;
import nodomain.freeyourgadget.gadgetbridge.GBApplication;
import nodomain.freeyourgadget.gadgetbridge.R;
import nodomain.freeyourgadget.gadgetbridge.database.PeriodicExporter;
import nodomain.freeyourgadget.gadgetbridge.devices.DeviceManager;
import nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandPreferencesActivity;
import nodomain.freeyourgadget.gadgetbridge.model.CannedMessagesSpec;
@ -64,6 +70,8 @@ public class SettingsActivity extends AbstractSettingsActivity {
public static final String PREF_MEASUREMENT_SYSTEM = "measurement_system";
private static final int FILE_REQUEST_CODE = 4711;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -262,17 +270,47 @@ public class SettingsActivity extends AbstractSettingsActivity {
pref = findPreference("weather_city");
pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newVal) {
// reset city id and force a new lookup
GBApplication.getPrefs().getPreferences().edit().putString("weather_cityid",null).apply();
preference.setSummary(newVal.toString());
Intent intent = new Intent("GB_UPDATE_WEATHER");
intent.setPackage(BuildConfig.APPLICATION_ID);
sendBroadcast(intent);
@Override
public boolean onPreferenceChange(Preference preference, Object newVal) {
// reset city id and force a new lookup
GBApplication.getPrefs().getPreferences().edit().putString("weather_cityid", null).apply();
preference.setSummary(newVal.toString());
Intent intent = new Intent("GB_UPDATE_WEATHER");
intent.setPackage(BuildConfig.APPLICATION_ID);
sendBroadcast(intent);
return true;
}
});
pref = findPreference("export_location");
pref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
Intent i = new Intent(Intent.ACTION_CREATE_DOCUMENT);
i.setType("application/x-sqlite3");
i.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(i, "Choose directory"), FILE_REQUEST_CODE);
return true;
}
});
pref = findPreference("auto_export_period");
pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object auto_export_period) {
preference.setSummary(auto_export_period.toString());
boolean auto_export_enabled = GBApplication.getPrefs().getBoolean("auto_export_enabled", false);
PeriodicExporter.sheduleAlarm(getApplicationContext(), (int) auto_export_period, auto_export_enabled);
return true;
}
});
findPreference("auto_export_enabled").setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object autoExportEnabled) {
int auto_export_period = GBApplication.getPrefs().getInt("auto_export_period", 0);
PeriodicExporter.sheduleAlarm(getApplicationContext(), auto_export_period, (boolean) autoExportEnabled);
return true;
}
});
// Get all receivers of Media Buttons
@ -301,6 +339,36 @@ public class SettingsActivity extends AbstractSettingsActivity {
audioPlayer.setDefaultValue(newValues[0]);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == FILE_REQUEST_CODE && data != null) {
Uri uri = data.getData();
PreferenceManager
.getDefaultSharedPreferences(this)
.edit()
.putString("export_location", uri.toString())
.apply();
Cursor cursor = getContentResolver().query(
uri,
new String[] { DocumentsContract.Document.COLUMN_DISPLAY_NAME, DocumentsContract.Document.COLUMN_SUMMARY },
null, null, null, null
);
if (cursor == null || ! cursor.moveToFirst()) {
return;
}
String displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
String summary = cursor.getString(cursor.getColumnIndex(DocumentsContract.Document.COLUMN_SUMMARY));
LOG.info(displayName + " " + summary);
findPreference("export_location").setSummary(displayName);
boolean autoExportEnabled = GBApplication
.getPrefs().getBoolean("auto_export_enabled", false);
int autoExportPeriod = GBApplication
.getPrefs().getInt("auto_export_period", 0);
PeriodicExporter.sheduleAlarm(getApplicationContext(), autoExportPeriod, autoExportEnabled);
}
}
/*
* delayed execution so that the preferences are applied first
*/

View File

@ -21,6 +21,7 @@ import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
@ -29,6 +30,7 @@ import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
@ -118,6 +120,16 @@ public class DBHelper {
}
}
public void exportDB(DBHandler dbHandler, OutputStream dest) throws IOException {
String dbPath = getClosedDBPath(dbHandler);
try {
File source = new File(dbPath);
FileUtils.copyFileToStream(source, dest);
} finally {
dbHandler.openDb();
}
}
private String getDate() {
return new SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(new Date());
}

View File

@ -0,0 +1,64 @@
package nodomain.freeyourgadget.gadgetbridge.database;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.SystemClock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.OutputStream;
import nodomain.freeyourgadget.gadgetbridge.GBApplication;
/**
* Created by maufl on 1/4/18.
*/
public class PeriodicExporter extends BroadcastReceiver {
private static final Logger LOG = LoggerFactory.getLogger(PeriodicExporter.class);
public static void sheduleAlarm(Context context, Integer autoExportPeriod, boolean autoExportEnabled) {
Intent i = new Intent(context, PeriodicExporter.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0 , i, 0);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.cancel(pi);
if (!autoExportEnabled) {
return;
}
int exportPeriod = autoExportPeriod * 1000;// * 60 * 60 * 1000;
if (exportPeriod == 0) {
return;
}
LOG.info("Enabling periodic export");
am.setInexactRepeating(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + exportPeriod,
exportPeriod,
pi
);
}
@Override
public void onReceive(Context context, Intent intent) {
LOG.info("Exporting DB");
try (DBHandler dbHandler = GBApplication.acquireDB()) {
DBHelper helper = new DBHelper(context);
String dst = GBApplication.getPrefs().getString("export_location", null);
if (dst == null) {
LOG.info("Unable to export DB, export locatio not set");
return;
}
Uri dstUri = Uri.parse(dst);
OutputStream out = context.getContentResolver().openOutputStream(dstUri);
helper.exportDB(dbHandler, out);
} catch (Exception ex) {
LOG.info("Exception while exporting DB: ", ex);
}
}
}

View File

@ -18,11 +18,13 @@ package nodomain.freeyourgadget.gadgetbridge.util;
import android.content.ContentResolver;
import android.content.Context;
import android.icu.util.Output;
import android.net.Uri;
import android.os.Environment;
import android.support.annotation.NonNull;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
@ -32,6 +34,7 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
@ -82,6 +85,16 @@ public class FileUtils {
}
}
public static void copyFileToStream(File src, OutputStream dst) throws IOException {
try (FileInputStream in = new FileInputStream(src)) {
byte[] buf = new byte[4096];
while(in.available() > 0) {
int bytes = in.read(buf);
dst.write(buf, 0, bytes);
}
}
}
public static void copyURItoFile(Context ctx, Uri uri, File destFile) throws IOException {
if (uri.getPath().equals(destFile.getPath())) {
return;
@ -98,6 +111,17 @@ public class FileUtils {
}
}
public static void copyFileToURI(Context context, File src, Uri dst) throws IOException {
OutputStream out = context.getContentResolver().openOutputStream(dst);
if (out == null) {
throw new IOException("Unable to open output stream for " + dst.toString());
}
try (OutputStream bufOut = new BufferedOutputStream(out)) {
copyFileToStream(src, bufOut);
bufOut.close();
}
}
/**
* Returns the textual contents of the given file. The contents is expected to be
* in UTF-8 encoding.

View File

@ -1,4 +1,5 @@
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:grid="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
@ -9,8 +10,7 @@
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:grid="http://schemas.android.com/apk/res-auto"
<android.support.v7.widget.GridLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="@dimen/activity_vertical_margin"
@ -29,8 +29,8 @@
<Button
android:id="@+id/importDBButton"
android:text="Import DB"
grid:layout_gravity="center"
grid:layout_column="1" />
grid:layout_column="1"
grid:layout_gravity="center" />
<TextView
@ -50,6 +50,13 @@
grid:layout_columnSpan="2"
grid:layout_columnWeight="1" />
<Button
android:id="@+id/chooseDirectory"
android:text="Choose Directory"
grid:layout_columnSpan="2"
grid:layout_columnWeight="1"
grid:layout_gravity="center" />
<TextView
android:id="@+id/mergeOldActivityDataTitle"

View File

@ -101,6 +101,13 @@
android:defaultValue="true"
android:key="charts_allow_swipe"
android:title="@string/pref_title_charts_swipe" />
<ListPreference
android:defaultValue="metric"
android:entries="@array/pref_entries_unit_system"
android:entryValues="@array/pref_values_unit_system"
android:key="measurement_system"
android:summary="%s"
android:title="@string/pref_title_unit_system" />
</PreferenceCategory>
<PreferenceCategory
android:key="pref_key_datetime"
@ -496,6 +503,25 @@
</PreferenceScreen>
</PreferenceCategory>
<PreferenceCategory
android:key="database"
android:title="Database settings">
<Preference
android:key="export_location"
android:title="Database export location"
android:summary="%s" />
<CheckBoxPreference
android:defaultValue="false"
android:key="auto_export_enabled"
android:title="Enable periodic export" />
<EditTextPreference
android:inputType="number"
android:key="auto_export_period"
android:defaultValue="3"
android:maxLength="3"
android:title="Export every n hours"
android:summary="%n"/>
</PreferenceCategory>
<PreferenceCategory
android:key="pref_key_development"
android:title="@string/pref_header_development">