Skip to content

Commit

Permalink
Show map import progress and error
Browse files Browse the repository at this point in the history
  • Loading branch information
andreynovikov committed Jan 6, 2024
1 parent 66393a6 commit 32d5ee9
Show file tree
Hide file tree
Showing 6 changed files with 72 additions and 10 deletions.
37 changes: 37 additions & 0 deletions app/src/main/java/mobi/maptrek/MainActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,13 @@
import androidx.fragment.app.FragmentFactory;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.Observer;
import androidx.loader.app.LoaderManager;
import androidx.loader.content.Loader;
import androidx.preference.PreferenceManager;
import androidx.work.Data;
import androidx.work.WorkInfo;
import androidx.work.WorkManager;

import android.text.Html;
import android.text.method.LinkMovementMethod;
Expand Down Expand Up @@ -165,6 +169,7 @@
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

import mobi.maptrek.data.MapObject;
Expand Down Expand Up @@ -895,8 +900,10 @@ protected void onStart() {
DataLoader loader = (DataLoader) LoaderManager.getInstance(this).initLoader(0, null, this);
loader.setProgressHandler(mProgressHandler);

ContextCompat.registerReceiver(this, mBroadcastReceiver, new IntentFilter(MapWorker.BROADCAST_MAP_STARTED), ContextCompat.RECEIVER_NOT_EXPORTED);
ContextCompat.registerReceiver(this, mBroadcastReceiver, new IntentFilter(MapWorker.BROADCAST_MAP_ADDED), ContextCompat.RECEIVER_NOT_EXPORTED);
ContextCompat.registerReceiver(this, mBroadcastReceiver, new IntentFilter(MapWorker.BROADCAST_MAP_REMOVED), ContextCompat.RECEIVER_NOT_EXPORTED);
ContextCompat.registerReceiver(this, mBroadcastReceiver, new IntentFilter(MapWorker.BROADCAST_MAP_FAILED), ContextCompat.RECEIVER_NOT_EXPORTED);
ContextCompat.registerReceiver(this, mBroadcastReceiver, new IntentFilter(BaseLocationService.BROADCAST_TRACK_SAVE), ContextCompat.RECEIVER_NOT_EXPORTED);
ContextCompat.registerReceiver(this, mBroadcastReceiver, new IntentFilter(NavigationService.BROADCAST_NAVIGATION_STATUS), ContextCompat.RECEIVER_NOT_EXPORTED);
ContextCompat.registerReceiver(this, mBroadcastReceiver, new IntentFilter(NavigationService.BROADCAST_NAVIGATION_STATE), ContextCompat.RECEIVER_NOT_EXPORTED);
Expand Down Expand Up @@ -4116,8 +4123,38 @@ public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
logger.debug("Broadcast: {}", action);
if (MapWorker.BROADCAST_MAP_ADDED.equals(action) || MapWorker.BROADCAST_MAP_REMOVED.equals(action)) {
if (mProgressHandler != null && MapWorker.BROADCAST_MAP_ADDED.equals(action))
mProgressHandler.onProgressFinished();
mMap.clearMap();
}
if (MapWorker.BROADCAST_MAP_STARTED.equals(action)) {
// TODO: handle rotation (ViewModel?)
final Bundle extras = intent.getExtras();
if (extras == null)
return;
UUID id = (UUID) extras.getSerializable(MapWorker.EXTRA_UUID);
if (id == null)
return;
if (mProgressHandler != null)
mProgressHandler.onProgressStarted(100);
WorkManager.getInstance(getApplicationContext())
.getWorkInfoByIdLiveData(id)
.observe(MainActivity.this, (Observer<WorkInfo>) workInfo -> {
if (workInfo != null) {
Data progress = workInfo.getProgress();
int value = progress.getInt(MapWorker.PROGRESS, 0);
if (mProgressHandler != null)
mProgressHandler.onProgressChanged(value);
}
});
}
if (MapWorker.BROADCAST_MAP_FAILED.equals(action)) {
if (mProgressHandler != null)
mProgressHandler.onProgressFinished();
final Bundle extras = intent.getExtras();
String title = extras != null ? extras.getString(MapWorker.EXTRA_TITLE) : getString(R.string.map);
HelperUtils.showError(getString(R.string.msgMapDownloadFailed, title), mViews.coordinatorLayout);
}
if (BaseLocationService.BROADCAST_TRACK_SAVE.equals(action)) {
final Bundle extras = intent.getExtras();
boolean saved = extras != null && extras.getBoolean("saved");
Expand Down
2 changes: 1 addition & 1 deletion app/src/main/java/mobi/maptrek/MapTrek.java
Original file line number Diff line number Diff line change
Expand Up @@ -448,7 +448,7 @@ synchronized public void optionallyCloseMapDatabase(UUID id) {
e.printStackTrace();
}

logger.error("optionallyCloseMapDatabase {} {}", mMainActivityExists, hasWorks);
logger.error("optionallyCloseMapDatabase activityExists: {}, hasWorks: {}", mMainActivityExists, hasWorks);
if (!mMainActivityExists && !hasWorks) {
// close databases
if (mHillshadeHelper != null) {
Expand Down
38 changes: 30 additions & 8 deletions app/src/main/java/mobi/maptrek/maps/MapWorker.java
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,17 @@ public class MapWorker extends Worker {
public static final String KEY_X = "x";
public static final String KEY_Y = "y";

public static final String BROADCAST_MAP_STARTED = "mobi.maptrek.MapStarted";
public static final String BROADCAST_MAP_ADDED = "mobi.maptrek.MapAdded";
public static final String BROADCAST_MAP_REMOVED = "mobi.maptrek.MapRemoved";
public static final String BROADCAST_MAP_FAILED = "mobi.maptrek.MapFailed";

public static final String EXTRA_X = "x";
public static final String EXTRA_Y = "y";
public static final String EXTRA_TITLE = "title";
public static final String EXTRA_UUID = "uuid";

public static final String PROGRESS = "PROGRESS";

private final NotificationCompat.Builder builder;
private final int notificationId;
Expand Down Expand Up @@ -95,13 +101,14 @@ public Result doWork() {
builder.setContentTitle(title).setTicker(title);
setForegroundAsync(createForegroundInfo());

boolean success = true;
try {
MapTrek application = MapTrek.getApplication();
Index mapIndex = application.getMapIndex();

if (actionImport) {
String fileUri = inputData.getString(KEY_FILE_URI);
importMap(application, mapIndex, fileUri);
success = importMap(application, mapIndex, fileUri);
}
if (actionRemoval) {
int x = inputData.getInt(KEY_X, -1);
Expand All @@ -113,25 +120,29 @@ public Result doWork() {
} catch (Exception e) {
logger.error(e.getMessage(), e);
showErrorNotification();
return Result.failure();
success = false;
}

return Result.success();
if (success)
return Result.success();
else
return Result.failure();
}

private void importMap(MapTrek application, Index mapIndex, String fileUri) {
private boolean importMap(MapTrek application, Index mapIndex, String fileUri) {
Uri uri = Uri.parse(fileUri);
logger.error(uri.toString());

String filename = uri.getLastPathSegment();
if (filename == null)
return;
throw new RuntimeException("missing file name");
boolean hillshade = false;
String title;
final int x, y;
if (Index.BASEMAP_FILENAME.equals(filename)) {
x = -1;
y = -1;
String title = application.getString(R.string.baseMapTitle);
title = application.getString(R.string.baseMapTitle);
builder.setContentTitle(title).setTicker(title);
} else {
String[] parts = filename.split("[\\-.]");
Expand All @@ -142,19 +153,27 @@ private void importMap(MapTrek application, Index mapIndex, String fileUri) {
hillshade = "mbtiles".equals(parts[2]);
if (x > 127 || y > 127)
throw new NumberFormatException("out of range");
String title = application.getString(hillshade ? R.string.hillshadeTitle : R.string.mapTitle, x, y);
title = application.getString(hillshade ? R.string.hillshadeTitle : R.string.mapTitle, x, y);
builder.setContentTitle(title).setTicker(title);
}
setForegroundAsync(createForegroundInfo());
Intent intent = new Intent(BROADCAST_MAP_STARTED).putExtra(EXTRA_TITLE, title).putExtra(EXTRA_UUID, getId());
intent.setPackage(application.getPackageName());
application.sendBroadcast(intent);

if (processDownload(mapIndex, x, y, hillshade, uri.getPath(), new OperationProgressListener())) {
Intent intent = new Intent(BROADCAST_MAP_ADDED).putExtra(EXTRA_X, x).putExtra(EXTRA_Y, y);
intent = new Intent(BROADCAST_MAP_ADDED).putExtra(EXTRA_X, x).putExtra(EXTRA_Y, y);
intent.setPackage(application.getPackageName());
application.sendBroadcast(intent);
builder.setContentText(application.getString(R.string.complete));
setForegroundAsync(createForegroundInfo());
return true;
} else {
showErrorNotification();
intent = new Intent(BROADCAST_MAP_FAILED).putExtra(EXTRA_TITLE, title);
intent.setPackage(application.getPackageName());
application.sendBroadcast(intent);
return false;
}
}

Expand Down Expand Up @@ -215,6 +234,7 @@ public void onProgressStarted(int length) {
String title = getApplicationContext().getString(R.string.processed, 0);
builder.setContentText(title).setTicker(title).setProgress(100, 0, false);
setForegroundAsync(createForegroundInfo());
setProgressAsync(new Data.Builder().putInt(PROGRESS, 0).build());
}

@Override
Expand All @@ -227,6 +247,7 @@ public void onProgressChanged(int progress) {
String title = getApplicationContext().getString(R.string.processed, this.progress);
builder.setContentText(title).setTicker(title).setProgress(100, this.progress, false);
setForegroundAsync(createForegroundInfo());
setProgressAsync(new Data.Builder().putInt(PROGRESS, this.progress).build());
}
}

Expand All @@ -236,6 +257,7 @@ public void onProgressFinished() {
return;
builder.setProgress(0, 0, false);
setForegroundAsync(createForegroundInfo());
setProgressAsync(new Data.Builder().putInt(PROGRESS, 100).build());
}

@Override
Expand Down
1 change: 0 additions & 1 deletion app/src/main/java/mobi/maptrek/maps/maptrek/Index.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;

import android.os.Build;
import android.text.TextUtils;

import org.slf4j.Logger;
Expand Down
2 changes: 2 additions & 0 deletions app/src/main/res/values-ru/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@
<string name="msgOtherFormatsExplanation">Формат GPX сохраняет всю важную информацию и широко используется, но итоговые файлы занимают очень много места. Формат KML не хранит информацию о времени, но итоговые файлы на 30% компактнее, чем в формате GPX.</string>
<string name="msgFailedToGetFile">Не удалось получить файл</string>
<string name="msgRestorePlacesFailed">Ошибка восстановления точек</string>
<string name="msgMapDownloadFailed">%s: произошёл сбой при загрузке</string>

<string name="introOfflineMapsTitle">Офлайн карты</string>
<string name="introOfflineMaps">Векторные карты содержат подробные топографические данные с изолиниями высот и поддержкой затенений рельефа и не требуют подключения к интернету. Вы также можете добавлять собственные карты для покрытия интересующих вас областей. Ваши карты тоже будут затеняться.</string>
Expand Down Expand Up @@ -739,4 +740,5 @@
<string name="limited_access">Частично доступен</string>
<string name="no_access">Недоступен</string>
<string name="fee">Обычно взимается комиссия</string>
<string name="map">Карта</string>
</resources>
2 changes: 2 additions & 0 deletions app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
<string name="iamin">Yes, I\'m in</string>
<string name="nameOrCoordinates">Name or coordinates</string>
<string name="satellitesStub" translatable="false">0/0</string>
<string name="map">Map</string>

<string name="actionSave">Save</string>
<string name="actionStop">Stop</string>
Expand Down Expand Up @@ -174,6 +175,7 @@
<string name="msgMapSelectionExplanation">Grey squares designate areas available for download. When map index is downloaded each square contains information about area map size and data age. If you check hillshades box then information about availability of hillshades for that area is also displayed and sizes are adjusted to incorporate hillshades. Bright green areas denote active (downloaded) areas, dark green are being currently downloaded. If update for specific area is available, square is yellow. If there is an update for world map special check box will appear. To mark active area for removal long press it. If area is removed space is freed not immediately, but gradually upon time. Map index is updated not more then once a day.</string>
<string name="msgMultipleMapsMode">Multi-maps mode enabled. Use double tap to show and hide maps.</string>
<string name="msgEnableGps">You should enable precise location (GPS) in Android settings in order to use real time positioning</string>
<string name="msgMapDownloadFailed">%s failed to download</string>

<string name="introOfflineMapsTitle">Offline maps</string>
<string name="introOfflineMaps">Lightweight offline vector maps contain detailed topological data with elevation contours and support hillshades. You can add custom maps to cover your area of interest. Custom maps will be shaded as well.</string>
Expand Down

0 comments on commit 32d5ee9

Please sign in to comment.