Refactor startup

This commit is contained in:
Victor Shcherb 2015-03-06 01:58:15 +01:00
parent 3007fa5a91
commit 2ed43c34e1
18 changed files with 644 additions and 488 deletions

View file

@ -36,6 +36,14 @@ public class MapPoiTypes {
public String getTranslation(AbstractPoiType type); public String getTranslation(AbstractPoiType type);
} }
public static MapPoiTypes getDefaultNoInit() {
if(DEFAULT_INSTANCE == null){
DEFAULT_INSTANCE = new MapPoiTypes(null);
}
return DEFAULT_INSTANCE;
}
public static MapPoiTypes getDefault() { public static MapPoiTypes getDefault() {
if(DEFAULT_INSTANCE == null){ if(DEFAULT_INSTANCE == null){
DEFAULT_INSTANCE = new MapPoiTypes(null); DEFAULT_INSTANCE = new MapPoiTypes(null);
@ -43,13 +51,6 @@ public class MapPoiTypes {
} }
return DEFAULT_INSTANCE; return DEFAULT_INSTANCE;
} }
public static MapPoiTypes initDefault(PoiTranslator pt) {
MapPoiTypes df = getDefault();
df.setPoiTranslator(pt);
return df;
}
public PoiCategory getOtherPoiCategory() { public PoiCategory getOtherPoiCategory() {
@ -120,7 +121,7 @@ public class MapPoiTypes {
} }
protected void init(){ public void init(){
InputStream is; InputStream is;
try { try {
if(resourceName == null){ if(resourceName == null){

View file

@ -1,56 +1,114 @@
package net.osmand.plus; package net.osmand.plus;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import net.osmand.IProgress;
import net.osmand.IndexConstants;
import net.osmand.PlatformUtil;
import net.osmand.access.AccessibleAlertBuilder;
import net.osmand.map.OsmandRegions;
import net.osmand.osm.AbstractPoiType;
import net.osmand.osm.MapPoiTypes;
import net.osmand.plus.activities.DayNightHelper;
import net.osmand.plus.activities.HelpActivity;
import net.osmand.plus.activities.SavingTrackHelper;
import net.osmand.plus.download.DownloadActivity;
import net.osmand.plus.helpers.AvoidSpecificRoads;
import net.osmand.plus.helpers.WaypointHelper;
import net.osmand.plus.monitoring.LiveMonitoringHelper;
import net.osmand.plus.poi.PoiFiltersHelper;
import net.osmand.plus.render.MapRenderRepositories;
import net.osmand.plus.render.NativeOsmandLibrary;
import net.osmand.plus.render.RendererRegistry;
import net.osmand.plus.resources.ResourceManager;
import net.osmand.plus.routing.RoutingHelper;
import net.osmand.plus.views.corenative.NativeCoreContext;
import net.osmand.plus.voice.CommandPlayerException;
import net.osmand.plus.voice.CommandPlayerFactory;
import net.osmand.render.RenderingRulesStorage;
import net.osmand.router.RoutingConfiguration;
import net.osmand.util.Algorithms;
import org.xmlpull.v1.XmlPullParserException;
import android.app.Activity; import android.app.Activity;
import android.app.AlertDialog; import android.app.AlertDialog;
import android.app.Dialog; import android.app.ProgressDialog;
import android.content.Context; import android.content.Context;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo; import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import net.osmand.access.AccessibleAlertBuilder; import btools.routingapp.BRouterServiceConnection;
import net.osmand.plus.activities.HelpActivity;
import net.osmand.plus.activities.MapActivity;
import net.osmand.plus.activities.TipsAndTricksActivity;
import net.osmand.plus.download.DownloadActivity;
import net.osmand.plus.render.MapRenderRepositories;
import java.io.File;
import java.util.Random;
/** /**
* Created by Denis * Created by Denis
* on 03.03.15. * on 03.03.15.
*/ */
public class AppInitializer { public class AppInitializer implements IProgress {
public static final boolean TIPS_AND_TRICKS = false; public static final boolean TIPS_AND_TRICKS = false;
private static final String FIRST_TIME_APP_RUN = "FIRST_TIME_APP_RUN"; //$NON-NLS-1$ private static final String FIRST_TIME_APP_RUN = "FIRST_TIME_APP_RUN"; //$NON-NLS-1$
private static final String VECTOR_INDEXES_CHECK = "VECTOR_INDEXES_CHECK"; //$NON-NLS-1$ private static final String VECTOR_INDEXES_CHECK = "VECTOR_INDEXES_CHECK"; //$NON-NLS-1$
private static final String TIPS_SHOW = "TIPS_SHOW"; //$NON-NLS-1$
private static final String VERSION_INSTALLED = "VERSION_INSTALLED"; //$NON-NLS-1$ private static final String VERSION_INSTALLED = "VERSION_INSTALLED"; //$NON-NLS-1$
private static final String EXCEPTION_FILE_SIZE = "EXCEPTION_FS"; //$NON-NLS-1$ private static final String EXCEPTION_FILE_SIZE = "EXCEPTION_FS"; //$NON-NLS-1$
public static final String LATEST_CHANGES_URL = "changes-1.9.html"; public static final String LATEST_CHANGES_URL = "changes-1.9.html";
public static final int APP_EXIT_CODE = 4; public static final int APP_EXIT_CODE = 4;
public static final String APP_EXIT_KEY = "APP_EXIT_KEY"; public static final String APP_EXIT_KEY = "APP_EXIT_KEY";
private OsmandApplication app;
private static final org.apache.commons.logging.Log LOG = PlatformUtil.getLog(AppInitializer.class);
public boolean initApp(final Activity activity, OsmandApplication app) {
final OsmAndAppCustomization appCustomization = app.getAppCustomization(); private boolean initSettings = false;
// restore follow route mode private boolean firstTime;
if (app.getSettings().FOLLOW_THE_ROUTE.get() && !app.getRoutingHelper().isRouteCalculated()) { private boolean appVersionChanged;
if(!(activity instanceof MapActivity)) { private long startTime;
startMapActivity(activity); private long startBgTime;
} private boolean appInitializing = true;
return false; private List<String> warnings = new ArrayList<String>();
private String taskName;
private List<AppInitializeListener> listeners = new ArrayList<AppInitializer.AppInitializeListener>();
public enum InitEvents {
FAVORITES_INITIALIZED, NATIVE_INITIALIZED, TASK_CHANGED, MAPS_INITIALIZED, POI_TYPES_INITIALIZED, ASSETS_COPIED, INIT_RENDERERS, RESTORE_BACKUPS, INDEX_REGION_BOUNDARIES, SAVE_GPX_TRACKS, LOAD_GPX_TRACKS;
}
public interface AppInitializeListener {
public void onProgress(AppInitializer init, InitEvents event);
public void onFinish(AppInitializer init);
}
public AppInitializer(OsmandApplication app) {
this.app = app;
}
public List<String> getWarnings() {
return warnings;
}
public boolean isAppInitializing() {
return appInitializing;
}
private void initUiVars(Activity activity) {
if(initSettings) {
return;
} }
boolean firstTime = false;
SharedPreferences pref = activity.getPreferences(Context.MODE_WORLD_WRITEABLE); SharedPreferences pref = activity.getPreferences(Context.MODE_WORLD_WRITEABLE);
boolean appVersionChanged = false;
if (!pref.contains(FIRST_TIME_APP_RUN)) { if (!pref.contains(FIRST_TIME_APP_RUN)) {
firstTime = true; firstTime = true;
pref.edit().putBoolean(FIRST_TIME_APP_RUN, true).commit(); pref.edit().putBoolean(FIRST_TIME_APP_RUN, true).commit();
@ -59,51 +117,44 @@ public class AppInitializer {
pref.edit().putString(VERSION_INSTALLED, Version.getFullVersion(app)).commit(); pref.edit().putString(VERSION_INSTALLED, Version.getFullVersion(app)).commit();
appVersionChanged = true; appVersionChanged = true;
} }
if (appCustomization.showFirstTimeRunAndTips(firstTime, appVersionChanged)) { initSettings = true;
if (firstTime) { }
applicationInstalledFirstTime(activity);
} else { public boolean isFirstTime(Activity a) {
int i = pref.getInt(TIPS_SHOW, 0); initUiVars(a);
if (i < 7) {
pref.edit().putInt(TIPS_SHOW, ++i).commit();
}
if (i == 1 || i == 5 || appVersionChanged) {
if (TIPS_AND_TRICKS) {
TipsAndTricksActivity tipsActivity = new TipsAndTricksActivity(activity);
Dialog dlg = tipsActivity.getDialogToShowTips(!appVersionChanged, false);
dlg.show();
} else {
if (appVersionChanged) {
final Intent helpIntent = new Intent(activity, HelpActivity.class);
helpIntent.putExtra(HelpActivity.TITLE, Version.getAppVersion((OsmandApplication)activity.getApplication()));
helpIntent.putExtra(HelpActivity.URL, LATEST_CHANGES_URL);
activity.startActivity(helpIntent);
}
}
}
}
}
return firstTime; return firstTime;
} }
public boolean checkAppVersionChanged(Activity activity) {
initUiVars(activity);
if (!firstTime && appVersionChanged) {
final Intent helpIntent = new Intent(activity, HelpActivity.class);
helpIntent.putExtra(HelpActivity.TITLE, Version.getAppVersion(app));
helpIntent.putExtra(HelpActivity.URL, LATEST_CHANGES_URL);
activity.startActivity(helpIntent);
return true;
}
return false;
}
public boolean checkPreviousRunsForExceptions(Activity ctx,boolean firstTime) { public boolean checkPreviousRunsForExceptions(Activity activity) {
long size = ctx.getPreferences(Context.MODE_WORLD_READABLE).getLong(EXCEPTION_FILE_SIZE, 0); initUiVars(activity);
final OsmandApplication app = ((OsmandApplication) ctx.getApplication()); long size = activity.getPreferences(Context.MODE_WORLD_READABLE).getLong(EXCEPTION_FILE_SIZE, 0);
final File file = app.getAppPath(OsmandApplication.EXCEPTION_PATH); final File file = app.getAppPath(OsmandApplication.EXCEPTION_PATH);
if (file.exists() && file.length() > 0) { if (file.exists() && file.length() > 0) {
if (size != file.length() && !firstTime) { if (size != file.length() && !firstTime) {
return true; return true;
} }
ctx.getPreferences(Context.MODE_WORLD_WRITEABLE).edit().putLong(EXCEPTION_FILE_SIZE, file.length()).commit(); activity.getPreferences(Context.MODE_WORLD_WRITEABLE).edit().putLong(EXCEPTION_FILE_SIZE, file.length()).commit();
} else { } else {
if (size > 0) { if (size > 0) {
ctx.getPreferences(Context.MODE_WORLD_WRITEABLE).edit().putLong(EXCEPTION_FILE_SIZE, 0).commit(); activity.getPreferences(Context.MODE_WORLD_WRITEABLE).edit().putLong(EXCEPTION_FILE_SIZE, 0).commit();
} }
} }
return false; return false;
} }
// TODO
public void checkVectorIndexesDownloaded(final Activity ctx) { public void checkVectorIndexesDownloaded(final Activity ctx) {
OsmandApplication app = (OsmandApplication)ctx.getApplication(); OsmandApplication app = (OsmandApplication)ctx.getApplication();
MapRenderRepositories maps = app.getResourceManager().getRenderer(); MapRenderRepositories maps = app.getResourceManager().getRenderer();
@ -144,6 +195,7 @@ public class AppInitializer {
ctx.startActivityForResult(mapIndent, 0); ctx.startActivityForResult(mapIndent, 0);
} }
// TODO
private void applicationInstalledFirstTime(final Activity ctx) { private void applicationInstalledFirstTime(final Activity ctx) {
final OsmandApplication app = (OsmandApplication)ctx.getApplication(); final OsmandApplication app = (OsmandApplication)ctx.getApplication();
boolean netOsmandWasInstalled = false; boolean netOsmandWasInstalled = false;
@ -174,7 +226,370 @@ public class AppInitializer {
builder.show(); builder.show();
} }
} }
private void indexRegionsBoundaries(boolean overwrite) {
try {
File file = app.getAppPath("regions.ocbf");
if (file != null) {
if (!file.exists() || overwrite) {
Algorithms.streamCopy(OsmandRegions.class.getResourceAsStream("regions.ocbf"),
new FileOutputStream(file));
}
}
app.regions.prepareFile(file.getAbsolutePath());
} catch (IOException e) {
LOG.error(e.getMessage(), e);
}
}
private void initPoiTypes() {
app.poiTypes.init();
app.poiTypes.setPoiTranslator(new MapPoiTypes.PoiTranslator() {
@Override
public String getTranslation(AbstractPoiType type) {
try {
Field f = R.string.class.getField("poi_" + type.getKeyName());
if (f != null) {
Integer in = (Integer) f.get(null);
return app.getString(in);
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
return null;
}
});
}
public void onCreateApplication() {
// always update application mode to default
OsmandSettings osmandSettings = app.getSettings();
if (!osmandSettings.FOLLOW_THE_ROUTE.get()) {
osmandSettings.APPLICATION_MODE.set(osmandSettings.DEFAULT_APPLICATION_MODE.get());
}
startTime = System.currentTimeMillis();
try {
app.bRouterServiceConnection = startupInit(BRouterServiceConnection.connect(app), BRouterServiceConnection.class);
} catch (Exception e) {
e.printStackTrace();
}
app.applyTheme(app);
app.poiTypes = startupInit(MapPoiTypes.getDefaultNoInit(), MapPoiTypes.class);
app.routingHelper = startupInit(new RoutingHelper(app), RoutingHelper.class);
app.resourceManager = startupInit(new ResourceManager(app), ResourceManager.class);
app.daynightHelper = startupInit(new DayNightHelper(app), DayNightHelper.class);
app.avoidSpecificRoads = startupInit(new AvoidSpecificRoads(app), AvoidSpecificRoads.class);
app.locationProvider = startupInit(new OsmAndLocationProvider(app), OsmAndLocationProvider.class);
app.savingTrackHelper = startupInit(new SavingTrackHelper(app), SavingTrackHelper.class);
app.liveMonitoringHelper = startupInit(new LiveMonitoringHelper(app), LiveMonitoringHelper.class);
app.selectedGpxHelper = startupInit(new GpxSelectionHelper(app, app.savingTrackHelper), GpxSelectionHelper.class);
app.favorites = startupInit(new FavouritesDbHelper(app), FavouritesDbHelper.class);
app.waypointHelper = startupInit(new WaypointHelper(app), WaypointHelper.class);
app.regions = startupInit(new OsmandRegions(), OsmandRegions.class);
String lang = osmandSettings.PREFERRED_LOCALE.get();
String clang = "".equals(lang) ? new Locale(lang).getLanguage() : lang;
app.regions.setLocale(clang);
app.poiFilters = startupInit(new PoiFiltersHelper(app), PoiFiltersHelper.class);
app.rendererRegistry = startupInit(new RendererRegistry(), RendererRegistry.class);
app.targetPointsHelper = startupInit(new TargetPointsHelper(app), TargetPointsHelper.class);
}
private <T> T startupInit(T object, Class<T> class1) {
long t = System.currentTimeMillis();
if(t - startTime > 7) {
System.err.println("Startup service " + class1.getName() + " took too long " + (t - startTime) + " ms");
}
startTime = t;
return object;
}
public void initPlugins() {
OsmandPlugin.initPlugins(app);
}
public net.osmand.router.RoutingConfiguration.Builder getLazyDefaultRoutingConfig() {
long tm = System.currentTimeMillis();
try {
File routingXml = app.getAppPath(IndexConstants.ROUTING_XML_FILE);
if (routingXml.exists() && routingXml.canRead()) {
try {
return RoutingConfiguration.parseFromInputStream(new FileInputStream(routingXml));
} catch (XmlPullParserException e) {
throw new IllegalStateException(e);
} catch (IOException e) {
throw new IllegalStateException(e);
}
} else {
return RoutingConfiguration.getDefault();
}
} finally {
long te = System.currentTimeMillis();
if(te - tm > 30) {
System.err.println("Defalt routing config init took " + (te - tm) + " ms");
}
}
}
public void initVoiceDataInDifferentThread(final Activity uiContext, final String voiceProvider, final Runnable run, boolean showDialog) {
final ProgressDialog dlg = showDialog ? ProgressDialog.show(uiContext, app.getString(R.string.loading_data),
app.getString(R.string.voice_data_initializing)) : null;
new Thread(new Runnable() {
@Override
public void run() {
try {
if (app.player != null) {
app.player.clear();
}
app.player = CommandPlayerFactory.createCommandPlayer(voiceProvider, app, uiContext);
app.getRoutingHelper().getVoiceRouter().setPlayer(app.player);
if(dlg != null) {
dlg.dismiss();
}
if (run != null && uiContext != null) {
uiContext.runOnUiThread(run);
}
} catch (CommandPlayerException e) {
if(dlg != null) {
dlg.dismiss();
}
app.showToastMessage(e.getError());
}
}
}).start();
}
private void startApplicationBackground() {
try {
startBgTime = System.currentTimeMillis();
initPoiTypes();
notifyEvent(InitEvents.POI_TYPES_INITIALIZED);
app.favorites.loadFavorites();
notifyEvent(InitEvents.FAVORITES_INITIALIZED);
initNativeCore();
notifyEvent(InitEvents.NATIVE_INITIALIZED);
app.resourceManager.reloadIndexesOnStart(this, warnings);
indexRegionsBoundaries(false);
notifyEvent(InitEvents.INDEX_REGION_BOUNDARIES);
app.selectedGpxHelper.loadGPXTracks(this);
notifyEvent(InitEvents.LOAD_GPX_TRACKS);
saveGPXTracks();
notifyEvent(InitEvents.SAVE_GPX_TRACKS);
// restore backuped favorites to normal file
restoreBackupForFavoritesFiles();
notifyEvent(InitEvents.RESTORE_BACKUPS);
} catch (RuntimeException e) {
e.printStackTrace();
warnings.add(e.getMessage());
} finally {
appInitializing = false;
notifyFinish();
if (warnings != null && !warnings.isEmpty()) {
app.showToastMessage(formatWarnings(warnings).toString());
}
}
}
private void restoreBackupForFavoritesFiles() {
final File appDir = app.getAppPath(null);
File save = new File(appDir, FavouritesDbHelper.FILE_TO_SAVE);
File bak = new File(appDir, FavouritesDbHelper.FILE_TO_BACKUP);
if (bak.exists() && (!save.exists() || bak.lastModified() > save.lastModified())) {
if (save.exists()) {
save.delete();
}
bak.renameTo(save);
}
}
private void saveGPXTracks() {
if (app.savingTrackHelper.hasDataToSave()) {
long timeUpdated = app.savingTrackHelper.getLastTrackPointTime();
if (System.currentTimeMillis() - timeUpdated >= 45000) {
startTask(app.getString(R.string.saving_gpx_tracks), -1);
try {
warnings.addAll(app.savingTrackHelper.saveDataToGpx(app.getAppCustomization().getTracksDir()));
} catch (RuntimeException e) {
warnings.add(e.getMessage());
}
} else {
app.savingTrackHelper.loadGpxFromDatabase();
}
}
if(app.getSettings().SAVE_GLOBAL_TRACK_TO_GPX.get()){
app.startNavigationService(NavigationService.USED_BY_GPX);
}
}
private void initNativeCore() {
if (!"qnx".equals(System.getProperty("os.name"))) {
OsmandSettings osmandSettings = app.getSettings();
if (osmandSettings.USE_OPENGL_RENDER.get()) {
boolean success = false;
if (!osmandSettings.OPENGL_RENDER_FAILED.get()) {
osmandSettings.OPENGL_RENDER_FAILED.set(true);
success = NativeCoreContext.tryCatchInit(app);
if (success) {
osmandSettings.OPENGL_RENDER_FAILED.set(false);
}
}
if (!success) {
// try next time once again ?
osmandSettings.OPENGL_RENDER_FAILED.set(false);
warnings.add("Native OpenGL library is not supported. Please try again after exit");
}
}
if (osmandSettings.NATIVE_RENDERING_FAILED.get()) {
osmandSettings.SAFE_MODE.set(true);
osmandSettings.NATIVE_RENDERING_FAILED.set(false);
warnings.add(app.getString(R.string.native_library_not_supported));
} else {
osmandSettings.SAFE_MODE.set(false);
osmandSettings.NATIVE_RENDERING_FAILED.set(true);
startTask(app.getString(R.string.init_native_library), -1);
RenderingRulesStorage storage = app.getRendererRegistry().getCurrentSelectedRenderer();
boolean initialized = NativeOsmandLibrary.getLibrary(storage, app) != null;
osmandSettings.NATIVE_RENDERING_FAILED.set(false);
if (!initialized) {
LOG.info("Native library could not be loaded!");
}
}
}
}
private StringBuilder formatWarnings(List<String> warnings) {
final StringBuilder b = new StringBuilder();
boolean f = true;
for (String w : warnings) {
if (f) {
f = false;
} else {
b.append('\n');
}
b.append(w);
}
return b;
}
public void notifyFinish() {
app.uiHandler.post(new Runnable() {
@Override
public void run() {
for(AppInitializeListener l : listeners) {
l.onFinish(AppInitializer.this);
}
}
});
}
public void notifyEvent(final InitEvents event) {
long time = System.currentTimeMillis();
System.out.println("Initialized " + event + " in " + (time - startBgTime) + " ms");
app.uiHandler.post(new Runnable() {
@Override
public void run() {
for(AppInitializeListener l : listeners) {
l.onProgress(AppInitializer.this, event);
}
}
});
startBgTime = time;
}
@Override
public void startTask(String taskName, int work) {
this.taskName = taskName;
}
@Override
public void startWork(int work) {
}
@Override
public void progress(int deltaWork) {
}
@Override
public void remaining(int remainingWork) {
}
@Override
public void finishTask() {
taskName = null;
notifyEvent(InitEvents.TASK_CHANGED);
}
public String getCurrentInitTaskName() {
return taskName;
}
@Override
public boolean isIndeterminate() {
return true;
}
@Override
public boolean isInterrupted() {
return false;
}
private boolean applicationBgInitializing = false;
public synchronized void startApplication() {
if (applicationBgInitializing) {
return;
}
applicationBgInitializing = true;
new Thread(new Runnable() { //$NON-NLS-1$
@Override
public void run() {
try {
startApplicationBackground();
} finally {
applicationBgInitializing = false;
}
}
}, "Initializing app").run();
;
}
public void addListener(AppInitializeListener listener) {
this.listeners.add(listener);
if(!appInitializing) {
listener.onFinish(this);
}
}
public void removeListener(AppInitializer listener) {
this.listeners.remove(listener);
}
} }

View file

@ -33,9 +33,9 @@ public class GpxSelectionHelper {
private List<SelectedGpxFile> selectedGPXFiles = new java.util.ArrayList<SelectedGpxFile>(); private List<SelectedGpxFile> selectedGPXFiles = new java.util.ArrayList<SelectedGpxFile>();
private SavingTrackHelper savingTrackHelper; private SavingTrackHelper savingTrackHelper;
public GpxSelectionHelper(OsmandApplication osmandApplication) { public GpxSelectionHelper(OsmandApplication osmandApplication, SavingTrackHelper trackHelper) {
this.app = osmandApplication; this.app = osmandApplication;
savingTrackHelper = this.app.getSavingTrackHelper(); savingTrackHelper = trackHelper;
} }
public void clearAllGpxFileToShow() { public void clearAllGpxFileToShow() {

View file

@ -3,12 +3,9 @@ package net.osmand.plus;
import java.io.BufferedWriter; import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream; import java.io.PrintStream;
import java.lang.Thread.UncaughtExceptionHandler; import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Field;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
@ -18,8 +15,9 @@ import net.osmand.PlatformUtil;
import net.osmand.access.AccessibilityPlugin; import net.osmand.access.AccessibilityPlugin;
import net.osmand.access.AccessibleAlertBuilder; import net.osmand.access.AccessibleAlertBuilder;
import net.osmand.access.AccessibleToast; import net.osmand.access.AccessibleToast;
import net.osmand.osm.AbstractPoiType; import net.osmand.map.OsmandRegions;
import net.osmand.osm.MapPoiTypes; import net.osmand.osm.MapPoiTypes;
import net.osmand.plus.AppInitializer.AppInitializeListener;
import net.osmand.plus.access.AccessibilityMode; import net.osmand.plus.access.AccessibilityMode;
import net.osmand.plus.activities.DayNightHelper; import net.osmand.plus.activities.DayNightHelper;
import net.osmand.plus.activities.MainMenuActivity; import net.osmand.plus.activities.MainMenuActivity;
@ -43,9 +41,6 @@ import net.osmand.plus.voice.CommandPlayerFactory;
import net.osmand.render.RenderingRulesStorage; import net.osmand.render.RenderingRulesStorage;
import net.osmand.router.RoutingConfiguration; import net.osmand.router.RoutingConfiguration;
import net.osmand.util.Algorithms; import net.osmand.util.Algorithms;
import org.xmlpull.v1.XmlPullParserException;
import android.app.Activity; import android.app.Activity;
import android.app.AlarmManager; import android.app.AlarmManager;
import android.app.AlertDialog; import android.app.AlertDialog;
@ -82,39 +77,36 @@ public class OsmandApplication extends Application {
public static final String EXCEPTION_PATH = "exception.log"; //$NON-NLS-1$ public static final String EXCEPTION_PATH = "exception.log"; //$NON-NLS-1$
private static final org.apache.commons.logging.Log LOG = PlatformUtil.getLog(OsmandApplication.class); private static final org.apache.commons.logging.Log LOG = PlatformUtil.getLog(OsmandApplication.class);
final AppInitializer appInitializer = new AppInitializer(this);
ResourceManager resourceManager = null;
PoiFiltersHelper poiFilters = null;
MapPoiTypes poiTypes = null;
RoutingHelper routingHelper = null;
FavouritesDbHelper favorites = null;
CommandPlayer player = null;
OsmandSettings osmandSettings = null; OsmandSettings osmandSettings = null;
OsmAndAppCustomization appCustomization; OsmAndAppCustomization appCustomization;
DayNightHelper daynightHelper; private final SQLiteAPI sqliteAPI = new SQLiteAPIImpl(this);
private final OsmAndTaskManager taskManager = new OsmAndTaskManager(this);
Handler uiHandler;
NavigationService navigationService; NavigationService navigationService;
RendererRegistry rendererRegistry;
OsmAndLocationProvider locationProvider;
OsmAndTaskManager taskManager;
// start variables
private ProgressImplementation startDialog;
private Handler uiHandler;
private GpxSelectionHelper selectedGpxHelper;
private SavingTrackHelper savingTrackHelper;
private LiveMonitoringHelper liveMonitoringHelper;
private TargetPointsHelper targetPointsHelper;
private RoutingConfiguration.Builder defaultRoutingConfig;
private WaypointHelper waypointHelper;
private AvoidSpecificRoads avoidSpecificRoads;
private boolean applicationInitializing = false;
private Locale preferredLocale = null; private Locale preferredLocale = null;
SQLiteAPI sqliteAPI; // start variables
ResourceManager resourceManager;
OsmAndLocationProvider locationProvider;
RendererRegistry rendererRegistry;
DayNightHelper daynightHelper;
PoiFiltersHelper poiFilters;
MapPoiTypes poiTypes;
RoutingHelper routingHelper;
FavouritesDbHelper favorites;
CommandPlayer player;
GpxSelectionHelper selectedGpxHelper;
SavingTrackHelper savingTrackHelper;
LiveMonitoringHelper liveMonitoringHelper;
TargetPointsHelper targetPointsHelper;
WaypointHelper waypointHelper;
AvoidSpecificRoads avoidSpecificRoads;
BRouterServiceConnection bRouterServiceConnection; BRouterServiceConnection bRouterServiceConnection;
OsmandRegions regions;
RoutingConfiguration.Builder defaultRoutingConfig;
// Typeface // Typeface
@ -132,89 +124,40 @@ public class OsmandApplication extends Application {
} }
super.onCreate(); super.onCreate();
createInUiThread(); createInUiThread();
sqliteAPI = new SQLiteAPIImpl(this); uiHandler = new Handler();
try {
bRouterServiceConnection = BRouterServiceConnection.connect(this);
} catch(Exception e) {
e.printStackTrace();
}
if(Version.isSherpafy(this)) { if(Version.isSherpafy(this)) {
appCustomization = new SherpafyCustomization(); appCustomization = new SherpafyCustomization();
} else { } else {
appCustomization = new OsmAndAppCustomization(); appCustomization = new OsmAndAppCustomization();
} }
appCustomization.setup(this); appCustomization.setup(this);
osmandSettings = appCustomization.getOsmandSettings(); osmandSettings = appCustomization.getOsmandSettings();
// always update application mode to default
if(!osmandSettings.FOLLOW_THE_ROUTE.get()){
osmandSettings.APPLICATION_MODE.set(osmandSettings.DEFAULT_APPLICATION_MODE.get());
}
applyTheme(this);
poiTypes = initPoiTypes(); appInitializer.onCreateApplication();
routingHelper = new RoutingHelper(this, player);
taskManager = new OsmAndTaskManager(this);
resourceManager = new ResourceManager(this);
daynightHelper = new DayNightHelper(this);
avoidSpecificRoads = new AvoidSpecificRoads(this);
locationProvider = new OsmAndLocationProvider(this);
savingTrackHelper = new SavingTrackHelper(this);
liveMonitoringHelper = new LiveMonitoringHelper(this);
selectedGpxHelper = new GpxSelectionHelper(this);
favorites = new FavouritesDbHelper(this);
waypointHelper = new WaypointHelper(this);
uiHandler = new Handler();
rendererRegistry = new RendererRegistry();
targetPointsHelper = new TargetPointsHelper(this);
// if(!osmandSettings.FOLLOW_THE_ROUTE.get()) { // if(!osmandSettings.FOLLOW_THE_ROUTE.get()) {
// targetPointsHelper.clearPointToNavigate(false); // targetPointsHelper.clearPointToNavigate(false);
// } // }
checkPreferredLocale(); checkPreferredLocale();
startApplication(); startApplication();
if (LOG.isDebugEnabled()) { if (LOG.isInfoEnabled()) {
LOG.debug("Time to start application " + (System.currentTimeMillis() - timeToStart) + " ms. Should be less < 800 ms"); LOG.info("Time to start application " + (System.currentTimeMillis() - timeToStart) + " ms. Should be less < 800 ms");
} }
timeToStart = System.currentTimeMillis(); timeToStart = System.currentTimeMillis();
OsmandPlugin.initPlugins(this); appInitializer.initPlugins();
if (LOG.isDebugEnabled()) { if (LOG.isInfoEnabled()) {
LOG.debug("Time to init plugins " + (System.currentTimeMillis() - timeToStart) + " ms. Should be less < 800 ms"); LOG.info("Time to init plugins " + (System.currentTimeMillis() - timeToStart) + " ms. Should be less < 800 ms");
} }
}
public AppInitializer getAppInitializer() {
return appInitializer;
} }
public MapPoiTypes getPoiTypes() { public MapPoiTypes getPoiTypes() {
if(poiTypes == null) {
throw new IllegalStateException("State exception");
}
return poiTypes; return poiTypes;
} }
private MapPoiTypes initPoiTypes() {
return MapPoiTypes.initDefault(new MapPoiTypes.PoiTranslator() {
@Override
public String getTranslation(AbstractPoiType type) {
try {
Field f = R.string.class.getField("poi_" + type.getKeyName());
if (f != null) {
Integer in = (Integer) f.get(null);
return getString(in);
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
return null;
}
});
}
private void createInUiThread() { private void createInUiThread() {
new Toast(this); // activate in UI thread to avoid further exceptions new Toast(this); // activate in UI thread to avoid further exceptions
new AsyncTask<View, Void, Void>() { new AsyncTask<View, Void, Void>() {
@ -248,7 +191,6 @@ public class OsmandApplication extends Application {
return avoidSpecificRoads; return avoidSpecificRoads;
} }
public OsmAndLocationProvider getLocationProvider() { public OsmAndLocationProvider getLocationProvider() {
return locationProvider; return locationProvider;
} }
@ -288,9 +230,6 @@ public class OsmandApplication extends Application {
} }
public PoiFiltersHelper getPoiFilters() { public PoiFiltersHelper getPoiFilters() {
if (poiFilters == null) {
poiFilters = new PoiFiltersHelper(this);
}
return poiFilters; return poiFilters;
} }
@ -341,44 +280,26 @@ public class OsmandApplication extends Application {
config.locale = preferredLocale; config.locale = preferredLocale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
} }
String clang = "".equals(lang) ? config.locale.getLanguage() : lang;
resourceManager.getOsmandRegions().setLocale(clang);
} }
public static final int PROGRESS_DIALOG = 5; public static final int PROGRESS_DIALOG = 5;
public void checkApplicationIsBeingInitialized(Activity activity, ProgressDialog progressDialog) { public void checkApplicationIsBeingInitialized(Activity activity, AppInitializeListener listener) {
// start application if it was previously closed // start application if it was previously closed
startApplication(); if(listener != null) {
synchronized (OsmandApplication.this) { appInitializer.addListener(listener);
if (startDialog != null) {
progressDialog.setTitle(getString(R.string.loading_data));
progressDialog.setMessage(getString(R.string.reading_indexes));
activity.showDialog(PROGRESS_DIALOG);
startDialog.setDialog(progressDialog);
} else {
progressDialog.dismiss();
}
} }
} }
public void checkApplicationIsBeingInitialized(Activity activity, TextView tv, ProgressBar progressBar, public void unsubscribeInitListener(AppInitializer listener) {
Runnable onClose) { if(listener != null) {
// start application if it was previously closed appInitializer.removeListener(listener);
startApplication(); }
synchronized (OsmandApplication.this) {
if (startDialog != null ) {
tv.setText(getString(R.string.loading_data));
startDialog.setProgressBar(tv, progressBar, onClose);
} else if (onClose != null) {
onClose.run();
}
}
} }
public boolean isApplicationInitializing() { public boolean isApplicationInitializing() {
return startDialog != null; return appInitializer.isAppInitializing();
} }
public RoutingHelper getRoutingHelper() { public RoutingHelper getRoutingHelper() {
@ -444,40 +365,12 @@ public class OsmandApplication extends Application {
} else { } else {
if (player == null || !Algorithms.objectEquals(voiceProvider, player.getCurrentVoice())) { if (player == null || !Algorithms.objectEquals(voiceProvider, player.getCurrentVoice())) {
initVoiceDataInDifferentThread(uiContext, voiceProvider, run, showDialog); appInitializer. initVoiceDataInDifferentThread(uiContext, voiceProvider, run, showDialog);
} }
} }
} }
private void initVoiceDataInDifferentThread(final Activity uiContext, final String voiceProvider, final Runnable run, boolean showDialog) {
final ProgressDialog dlg = showDialog ? ProgressDialog.show(uiContext, getString(R.string.loading_data),
getString(R.string.voice_data_initializing)) : null;
new Thread(new Runnable() {
@Override
public void run() {
try {
if (player != null) {
player.clear();
}
player = CommandPlayerFactory.createCommandPlayer(voiceProvider, OsmandApplication.this, uiContext);
routingHelper.getVoiceRouter().setPlayer(player);
if(dlg != null) {
dlg.dismiss();
}
if (run != null && uiContext != null) {
uiContext.runOnUiThread(run);
}
} catch (CommandPlayerException e) {
if(dlg != null) {
dlg.dismiss();
}
showToastMessage(e.getError());
}
}
}).start();
}
public NavigationService getNavigationService() { public NavigationService getNavigationService() {
return navigationService; return navigationService;
} }
@ -516,11 +409,9 @@ public class OsmandApplication extends Application {
} }
private void closeApplicationAnyway(final Activity activity, boolean disableService) { private void closeApplicationAnyway(final Activity activity, boolean disableService) {
if (applicationInitializing) { if (appInitializer.isAppInitializing()) {
resourceManager.close(); resourceManager.close();
} }
applicationInitializing = false;
activity.finish(); activity.finish();
if (getNavigationService() == null) { if (getNavigationService() == null) {
@ -547,141 +438,9 @@ public class OsmandApplication extends Application {
} }
public synchronized void startApplication() { public synchronized void startApplication() {
if (applicationInitializing) {
return;
}
applicationInitializing = true;
startDialog = new ProgressImplementation(this, null, false);
startDialog.setRunnable("Initializing app", new Runnable() { //$NON-NLS-1$
@Override
public void run() {
startApplicationBackground();
}
});
startDialog.run();
Thread.setDefaultUncaughtExceptionHandler(new DefaultExceptionHandler()); Thread.setDefaultUncaughtExceptionHandler(new DefaultExceptionHandler());
appInitializer.startApplication();
} }
private void startApplicationBackground() {
List<String> warnings = new ArrayList<String>();
try {
favorites.loadFavorites();
if (!"qnx".equals(System.getProperty("os.name"))) {
if (osmandSettings.USE_OPENGL_RENDER.get()) {
boolean success = false;
if (!osmandSettings.OPENGL_RENDER_FAILED.get()) {
osmandSettings.OPENGL_RENDER_FAILED.set(true);
success = NativeCoreContext.tryCatchInit(this);
if (success) {
osmandSettings.OPENGL_RENDER_FAILED.set(false);
}
}
if (!success) {
// try next time once again ?
osmandSettings.OPENGL_RENDER_FAILED.set(false);
warnings.add("Native OpenGL library is not supported. Please try again after exit");
}
}
if (osmandSettings.NATIVE_RENDERING_FAILED.get()) {
osmandSettings.SAFE_MODE.set(true);
osmandSettings.NATIVE_RENDERING_FAILED.set(false);
warnings.add(getString(R.string.native_library_not_supported));
} else {
osmandSettings.SAFE_MODE.set(false);
osmandSettings.NATIVE_RENDERING_FAILED.set(true);
startDialog.startTask(getString(R.string.init_native_library), -1);
RenderingRulesStorage storage = rendererRegistry.getCurrentSelectedRenderer();
boolean initialized = NativeOsmandLibrary.getLibrary(storage, this) != null;
osmandSettings.NATIVE_RENDERING_FAILED.set(false);
if (!initialized) {
LOG.info("Native library could not be loaded!");
}
}
}
warnings.addAll(resourceManager.reloadIndexes(startDialog));
player = null;
if (savingTrackHelper.hasDataToSave()) {
long timeUpdated = savingTrackHelper.getLastTrackPointTime();
if (System.currentTimeMillis() - timeUpdated >= 45000) {
startDialog.startTask(getString(R.string.saving_gpx_tracks), -1);
try {
warnings.addAll(savingTrackHelper.saveDataToGpx(appCustomization.getTracksDir()));
} catch (RuntimeException e) {
warnings.add(e.getMessage());
}
} else {
savingTrackHelper.loadGpxFromDatabase();
}
}
if(getSettings().SAVE_GLOBAL_TRACK_TO_GPX.get()){
startNavigationService(NavigationService.USED_BY_GPX);
}
// restore backuped favorites to normal file
final File appDir = getAppPath(null);
File save = new File(appDir, FavouritesDbHelper.FILE_TO_SAVE);
File bak = new File(appDir, FavouritesDbHelper.FILE_TO_BACKUP);
if (bak.exists() && (!save.exists() || bak.lastModified() > save.lastModified())) {
if (save.exists()) {
save.delete();
}
bak.renameTo(save);
}
} catch (RuntimeException e) {
e.printStackTrace();
warnings.add(e.getMessage());
} finally {
synchronized (OsmandApplication.this) {
final ProgressDialog toDismiss;
final Runnable pb;
if (startDialog != null) {
toDismiss = startDialog.getDialog();
pb = startDialog.getFinishRunnable();
} else {
toDismiss = null;
pb = null;
}
startDialog = null;
if (toDismiss != null || pb != null) {
uiHandler.post(new Runnable() {
@Override
public void run() {
if(pb != null) {
pb.run();
}
if (toDismiss != null) {
// TODO handling this dialog is bad, we need a better standard way
toDismiss.dismiss();
// toDismiss.getOwnerActivity().dismissDialog(PROGRESS_DIALOG);
}
}
});
}
if (warnings != null && !warnings.isEmpty()) {
showToastMessage(formatWarnings(warnings).toString());
}
}
}
}
private StringBuilder formatWarnings(List<String> warnings) {
final StringBuilder b = new StringBuilder();
boolean f = true;
for (String w : warnings) {
if (f) {
f = false;
} else {
b.append('\n');
}
b.append(w);
}
return b;
}
private class DefaultExceptionHandler implements UncaughtExceptionHandler { private class DefaultExceptionHandler implements UncaughtExceptionHandler {
@ -692,7 +451,7 @@ public class OsmandApplication extends Application {
defaultHandler = Thread.getDefaultUncaughtExceptionHandler(); defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
intent = PendingIntent.getActivity(OsmandApplication.this.getBaseContext(), 0, intent = PendingIntent.getActivity(OsmandApplication.this.getBaseContext(), 0,
new Intent(OsmandApplication.this.getBaseContext(), new Intent(OsmandApplication.this.getBaseContext(),
getAppCustomization().getMainMenuActivity()), 0); getAppCustomization().getMapActivity()), 0);
} }
@Override @Override
@ -844,23 +603,16 @@ public class OsmandApplication extends Application {
} }
public RoutingConfiguration.Builder getDefaultRoutingConfig() { public RoutingConfiguration.Builder getDefaultRoutingConfig() {
if (defaultRoutingConfig == null) { if(defaultRoutingConfig == null) {
File routingXml = getAppPath(IndexConstants.ROUTING_XML_FILE); defaultRoutingConfig = appInitializer.getLazyDefaultRoutingConfig();
if (routingXml.exists() && routingXml.canRead()) {
try {
defaultRoutingConfig = RoutingConfiguration.parseFromInputStream(new FileInputStream(routingXml));
} catch (XmlPullParserException e) {
throw new IllegalStateException(e);
} catch (IOException e) {
throw new IllegalStateException(e);
}
} else {
defaultRoutingConfig = RoutingConfiguration.getDefault();
}
} }
return defaultRoutingConfig; return defaultRoutingConfig;
} }
public OsmandRegions getRegions() {
return regions;
}
public boolean accessibilityExtensions() { public boolean accessibilityExtensions() {
return (Build.VERSION.SDK_INT < 14) ? getSettings().ACCESSIBILITY_EXTENSIONS.get() : false; return (Build.VERSION.SDK_INT < 14) ? getSettings().ACCESSIBILITY_EXTENSIONS.get() : false;
} }

View file

@ -60,12 +60,6 @@ import android.widget.TextView;
*/ */
public class MainMenuActivity extends BaseDownloadActivity implements OsmAndLocationProvider.OsmAndCompassListener, OsmAndLocationProvider.OsmAndLocationListener { public class MainMenuActivity extends BaseDownloadActivity implements OsmAndLocationProvider.OsmAndCompassListener, OsmAndLocationProvider.OsmAndLocationListener {
private static final String FIRST_TIME_APP_RUN = "FIRST_TIME_APP_RUN"; //$NON-NLS-1$
private static final String VECTOR_INDEXES_CHECK = "VECTOR_INDEXES_CHECK"; //$NON-NLS-1$
private static final String TIPS_SHOW = "TIPS_SHOW"; //$NON-NLS-1$
private static final String VERSION_INSTALLED = "VERSION_INSTALLED"; //$NON-NLS-1$
private static final String EXCEPTION_FILE_SIZE = "EXCEPTION_FS"; //$NON-NLS-1$
private static final int HELP_ID = 0; private static final int HELP_ID = 0;
private static final int SETTINGS_ID = 1; private static final int SETTINGS_ID = 1;
private static final int EXIT_ID = 2; private static final int EXIT_ID = 2;
@ -176,10 +170,8 @@ public class MainMenuActivity extends BaseDownloadActivity implements OsmAndLoca
actionBarBackground.setCallback(mDrawableCallback); actionBarBackground.setCallback(mDrawableCallback);
} }
AppInitializer initializer = new AppInitializer(); if (getMyApplication().getSettings().FOLLOW_THE_ROUTE.get() && !getMyApplication().getRoutingHelper().isRouteCalculated()) {
boolean firstTime = initializer.initApp(this, getMyApplication()); startMapActivity();
if (getMyApplication().getAppCustomization().checkExceptionsOnStart()) {
initializer.checkPreviousRunsForExceptions(this, firstTime);
} }
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {

View file

@ -143,14 +143,7 @@ public class MapActivity extends AccessibleActivity {
dashboardOnMap = new DashboardOnMap(this); dashboardOnMap = new DashboardOnMap(this);
dashboardOnMap.createDashboardView(); dashboardOnMap.createDashboardView();
if (getMyApplication().isApplicationInitializing()) { if (app.isApplicationInitializing()) {
AppInitializer initializer = new AppInitializer();
boolean firstTime = initializer.initApp(this, getMyApplication());
if (getMyApplication().getAppCustomization().checkExceptionsOnStart()) {
if (initializer.checkPreviousRunsForExceptions(this, firstTime)) {
dashboardOnMap.addErrorFragment();
}
}
dashboardOnMap.setDashboardVisibility(true); dashboardOnMap.setDashboardVisibility(true);
} }

View file

@ -5,6 +5,7 @@ import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@ -600,7 +601,8 @@ public class SettingsGeneralActivity extends SettingsBaseActivity {
@Override @Override
protected List<String> doInBackground(Void... params) { protected List<String> doInBackground(Void... params) {
return getMyApplication().getResourceManager().reloadIndexes(IProgress.EMPTY_PROGRESS); return getMyApplication().getResourceManager().reloadIndexes(IProgress.EMPTY_PROGRESS,
new ArrayList<String>());
} }
protected void onPostExecute(List<String> result) { protected void onPostExecute(List<String> result) {

View file

@ -17,10 +17,13 @@ import net.osmand.data.LatLon;
import net.osmand.data.MapObject; import net.osmand.data.MapObject;
import net.osmand.data.PointDescription; import net.osmand.data.PointDescription;
import net.osmand.data.Street; import net.osmand.data.Street;
import net.osmand.plus.AppInitializer;
import net.osmand.plus.OsmAndFormatter; import net.osmand.plus.OsmAndFormatter;
import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandApplication;
import net.osmand.plus.OsmandSettings; import net.osmand.plus.OsmandSettings;
import net.osmand.plus.R; import net.osmand.plus.R;
import net.osmand.plus.AppInitializer.AppInitializeListener;
import net.osmand.plus.AppInitializer.InitEvents;
import net.osmand.plus.activities.MapActivity; import net.osmand.plus.activities.MapActivity;
import net.osmand.plus.activities.OsmandListActivity; import net.osmand.plus.activities.OsmandListActivity;
import net.osmand.plus.resources.RegionAddressRepository; import net.osmand.plus.resources.RegionAddressRepository;
@ -43,15 +46,22 @@ public class GeoIntentActivity extends OsmandListActivity {
private ProgressDialog progressDlg; private ProgressDialog progressDlg;
private LatLon location; private LatLon location;
private ProgressDialog startProgressDialog;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
setContentView(R.layout.search_address_offline); setContentView(R.layout.search_address_offline);
getSupportActionBar().setTitle(R.string.search_osm_offline); getSupportActionBar().setTitle(R.string.search_osm_offline);
startProgressDialog = new ProgressDialog(this);
getMyApplication().checkApplicationIsBeingInitialized(this, startProgressDialog); getMyApplication().checkApplicationIsBeingInitialized(this, new AppInitializeListener() {
@Override
public void onProgress(AppInitializer init, InitEvents event) {
}
@Override
public void onFinish(AppInitializer init) {
}
});
location = getMyApplication().getSettings().getLastKnownMapLocation(); location = getMyApplication().getSettings().getLastKnownMapLocation();
final Intent intent = getIntent(); final Intent intent = getIntent();
@ -135,14 +145,6 @@ public class GeoIntentActivity extends OsmandListActivity {
} }
@Override
protected Dialog onCreateDialog(int id) {
if (id == OsmandApplication.PROGRESS_DIALOG) {
return startProgressDialog;
}
return super.onCreateDialog(id);
}
private class MapObjectAdapter extends ArrayAdapter<MapObject> { private class MapObjectAdapter extends ArrayAdapter<MapObject> {
public MapObjectAdapter(List<MapObject> places) { public MapObjectAdapter(List<MapObject> places) {

View file

@ -1,26 +1,32 @@
package net.osmand.plus.dashboard; package net.osmand.plus.dashboard;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.util.DisplayMetrics;
import android.view.*;
import android.widget.ImageView;
import net.osmand.data.LatLon; import net.osmand.data.LatLon;
import net.osmand.data.RotatedTileBox; import net.osmand.data.RotatedTileBox;
import net.osmand.map.MapTileDownloader.DownloadRequest; import net.osmand.map.MapTileDownloader.DownloadRequest;
import net.osmand.map.MapTileDownloader.IMapDownloaderCallback; import net.osmand.map.MapTileDownloader.IMapDownloaderCallback;
import net.osmand.plus.AppInitializer;
import net.osmand.plus.AppInitializer.AppInitializeListener;
import net.osmand.plus.AppInitializer.InitEvents;
import net.osmand.plus.R; import net.osmand.plus.R;
import net.osmand.plus.activities.MainMenuActivity; import net.osmand.plus.activities.MainMenuActivity;
import net.osmand.plus.activities.MapActivity; import net.osmand.plus.activities.MapActivity;
import net.osmand.plus.render.MapRenderRepositories; import net.osmand.plus.render.MapRenderRepositories;
import net.osmand.plus.resources.ResourceManager; import net.osmand.plus.resources.ResourceManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.drawable.Drawable; import android.graphics.drawable.Drawable;
import android.os.Bundle; import android.os.Bundle;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import android.widget.ProgressBar; import android.util.DisplayMetrics;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView; import android.widget.TextView;
/** /**
@ -119,17 +125,22 @@ public class DashMapFragment extends DashBaseFragment implements IMapDownloaderC
public void onViewCreated(final View view, @Nullable Bundle savedInstanceState) { public void onViewCreated(final View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState); super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.map_image).setVisibility(View.GONE); view.findViewById(R.id.map_image).setVisibility(View.GONE);
if (getMyApplication().isApplicationInitializing()) {
getMyApplication().checkApplicationIsBeingInitialized(getActivity(), (TextView) view.findViewById(R.id.ProgressMessage), getMyApplication().checkApplicationIsBeingInitialized(getActivity(), new AppInitializeListener() {
(ProgressBar) view.findViewById(R.id.ProgressBar), new Runnable() {
@Override @Override
public void run() { public void onProgress(AppInitializer init, InitEvents event) {
applicationInitialized(view); String tn = init.getCurrentInitTaskName();
} if(tn != null) {
}); ((TextView) view.findViewById(R.id.ProgressMessage)).setText(tn);
} else { }
applicationInitialized(view); }
}
@Override
public void onFinish(AppInitializer init) {
applicationInitialized(view);
}
});
} }
private void applicationInitialized(View view) { private void applicationInitialized(View view) {

View file

@ -133,9 +133,13 @@ public class DashboardOnMap {
} }
private void addDashboardFragments(){ private void addDashboardFragments() {
FragmentManager manager =ma. getSupportFragmentManager(); FragmentManager manager = ma.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = manager.beginTransaction(); FragmentTransaction fragmentTransaction = manager.beginTransaction();
if (manager.findFragmentByTag(DashErrorFragment.TAG) == null && ma.getMyApplication().getAppInitializer().checkPreviousRunsForExceptions(ma)) {
DashErrorFragment errorFragment = new DashErrorFragment();
fragmentTransaction.add(R.id.content, errorFragment, DashErrorFragment.TAG);
}
if (manager.findFragmentByTag(DashSearchFragment.TAG) == null) { if (manager.findFragmentByTag(DashSearchFragment.TAG) == null) {
fragmentTransaction.add(R.id.content, new DashSearchFragment(), DashSearchFragment.TAG); fragmentTransaction.add(R.id.content, new DashSearchFragment(), DashSearchFragment.TAG);
} }
@ -151,23 +155,13 @@ public class DashboardOnMap {
if (manager.findFragmentByTag(DashTrackFragment.TAG) == null) { if (manager.findFragmentByTag(DashTrackFragment.TAG) == null) {
fragmentTransaction.add(R.id.content, new DashTrackFragment(), DashTrackFragment.TAG); fragmentTransaction.add(R.id.content, new DashTrackFragment(), DashTrackFragment.TAG);
} }
//fragmentTransaction.add(R.id.content, new DashUpdatesFragment(), DashUpdatesFragment.TAG); // fragmentTransaction.add(R.id.content, new DashUpdatesFragment(), DashUpdatesFragment.TAG);
if (manager.findFragmentByTag(DashPluginsFragment.TAG) == null) { if (manager.findFragmentByTag(DashPluginsFragment.TAG) == null) {
fragmentTransaction.add(R.id.content, new DashPluginsFragment(), DashPluginsFragment.TAG); fragmentTransaction.add(R.id.content, new DashPluginsFragment(), DashPluginsFragment.TAG);
} }
fragmentTransaction.commit(); fragmentTransaction.commit();
} }
public void addErrorFragment() {
FragmentManager manager = ma.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = manager.beginTransaction();
if (manager.findFragmentByTag(DashErrorFragment.TAG) == null) {
DashErrorFragment errorFragment = new DashErrorFragment();
fragmentTransaction.add(R.id.content, errorFragment, DashErrorFragment.TAG).commit();
}
}

View file

@ -322,7 +322,7 @@ public class BaseDownloadActivity extends ActionBarProgressActivity {
if (result) { if (result) {
settings.setExternalStorageDirectory(newLoc); settings.setExternalStorageDirectory(newLoc);
getMyApplication().getResourceManager().resetStoreDirectory(); getMyApplication().getResourceManager().resetStoreDirectory();
getMyApplication().getResourceManager().reloadIndexes(progress); getMyApplication().getResourceManager().reloadIndexes(progress, new ArrayList<String>());
} }
return result; return result;
} }

View file

@ -751,7 +751,9 @@ public class LocalIndexesFragment extends OsmandExpandableListFragment {
} }
@Override @Override
protected List<String> doInBackground(Void... params) { protected List<String> doInBackground(Void... params) {
return getMyApplication().getResourceManager().reloadIndexes(IProgress.EMPTY_PROGRESS); return getMyApplication().getResourceManager().reloadIndexes(IProgress.EMPTY_PROGRESS,
new ArrayList<String>()
);
} }
}; };

View file

@ -39,11 +39,9 @@ public class PoiFiltersHelper {
private static final String UDF_PARKING = "parking"; private static final String UDF_PARKING = "parking";
private static final String[] DEL = new String[] {}; private static final String[] DEL = new String[] {};
private MapPoiTypes poiTypes;
public PoiFiltersHelper(OsmandApplication application){ public PoiFiltersHelper(OsmandApplication application){
this.application = application; this.application = application;
poiTypes = application.getPoiTypes();
} }
public NameFinderPoiFilter getNameFinderPOIFilter() { public NameFinderPoiFilter getNameFinderPOIFilter() {
if(nameFinderPOIFilter == null){ if(nameFinderPOIFilter == null){
@ -75,14 +73,19 @@ public class PoiFiltersHelper {
return findPoiFilter(filterId, getUserDefinedPoiFilters(), getTopStandardFilters(), getOsmDefinedPoiFilters()); return findPoiFilter(filterId, getUserDefinedPoiFilters(), getTopStandardFilters(), getOsmDefinedPoiFilters());
} }
public MapPoiTypes getPoiTypes() {
return application.getPoiTypes();
}
private void putAll(Map<PoiCategory, LinkedHashSet<String>> types, String tp) { private void putAll(Map<PoiCategory, LinkedHashSet<String>> types, String tp) {
types.put(poiTypes.getPoiCategoryByName(tp), null); types.put(getPoiTypes().getPoiCategoryByName(tp), null);
} }
private void putValues(Map<PoiCategory, LinkedHashSet<String>> types, String p, String... vls) { private void putValues(Map<PoiCategory, LinkedHashSet<String>> types, String p, String... vls) {
LinkedHashSet<String> list = new LinkedHashSet<String>(); LinkedHashSet<String> list = new LinkedHashSet<String>();
Collections.addAll(list, vls); Collections.addAll(list, vls);
types.put(poiTypes.getPoiCategoryByName(p), list); types.put(getPoiTypes().getPoiCategoryByName(p), list);
} }
private List<PoiLegacyFilter> getUserDefinedDefaultFilters() { private List<PoiLegacyFilter> getUserDefinedDefaultFilters() {
@ -221,7 +224,7 @@ public class PoiFiltersHelper {
public List<PoiLegacyFilter> getOsmDefinedPoiFilters(){ public List<PoiLegacyFilter> getOsmDefinedPoiFilters(){
if(cacheOsmDefinedFilters == null){ if(cacheOsmDefinedFilters == null){
cacheOsmDefinedFilters = new ArrayList<PoiLegacyFilter>(); cacheOsmDefinedFilters = new ArrayList<PoiLegacyFilter>();
for(PoiCategory t : poiTypes.getCategories()){ for(PoiCategory t : getPoiTypes().getCategories()){
cacheOsmDefinedFilters.add(new PoiLegacyFilter(t, application)); cacheOsmDefinedFilters.add(new PoiLegacyFilter(t, application));
} }
final Collator instance = Collator.getInstance(); final Collator instance = Collator.getInstance();
@ -432,7 +435,7 @@ public class PoiFiltersHelper {
map.put(filterId, new LinkedHashMap<PoiCategory, LinkedHashSet<String>>()); map.put(filterId, new LinkedHashMap<PoiCategory, LinkedHashSet<String>>());
} }
Map<PoiCategory, LinkedHashSet<String>> m = map.get(filterId); Map<PoiCategory, LinkedHashSet<String>> m = map.get(filterId);
PoiCategory a = poiTypes.getPoiCategoryByName(query.getString(1)); PoiCategory a = getPoiTypes().getPoiCategoryByName(query.getString(1));
String subCategory = query.getString(2); String subCategory = query.getString(2);
if(subCategory == null){ if(subCategory == null){
m.put(a, null); m.put(a, null);

View file

@ -1,14 +1,10 @@
package net.osmand.plus.resources; package net.osmand.plus.resources;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLConnection;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Stack; import java.util.Stack;

View file

@ -35,6 +35,8 @@ import net.osmand.map.MapTileDownloader;
import net.osmand.map.MapTileDownloader.DownloadRequest; import net.osmand.map.MapTileDownloader.DownloadRequest;
import net.osmand.map.OsmandRegions; import net.osmand.map.OsmandRegions;
import net.osmand.osm.PoiCategory; import net.osmand.osm.PoiCategory;
import net.osmand.plus.AppInitializer;
import net.osmand.plus.AppInitializer.InitEvents;
import net.osmand.plus.BusyIndicator; import net.osmand.plus.BusyIndicator;
import net.osmand.plus.OsmAndFormatter; import net.osmand.plus.OsmAndFormatter;
import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandApplication;
@ -127,8 +129,6 @@ public class ResourceManager {
protected final MapRenderRepositories renderer; protected final MapRenderRepositories renderer;
protected final OsmandRegions regions;
protected final MapTileDownloader tileDownloader; protected final MapTileDownloader tileDownloader;
public final AsyncLoadingThread asyncLoadingThread = new AsyncLoadingThread(this); public final AsyncLoadingThread asyncLoadingThread = new AsyncLoadingThread(this);
@ -156,7 +156,6 @@ public class ResourceManager {
float tiles = (dm.widthPixels / 256 + 2) * (dm.heightPixels / 256 + 2) * 3; float tiles = (dm.widthPixels / 256 + 2) * (dm.heightPixels / 256 + 2) * 3;
log.info("Tiles to load in memory : " + tiles); log.info("Tiles to load in memory : " + tiles);
maxImgCacheSize = (int) (tiles) ; maxImgCacheSize = (int) (tiles) ;
regions = new OsmandRegions();
} }
public MapTileDownloader getMapTileDownloader() { public MapTileDownloader getMapTileDownloader() {
@ -406,22 +405,26 @@ public class ResourceManager {
////////////////////////////////////////////// Working with indexes //////////////////////////////////////////////// ////////////////////////////////////////////// Working with indexes ////////////////////////////////////////////////
public List<String> reloadIndexes(IProgress progress){ public List<String> reloadIndexesOnStart(AppInitializer progress, List<String> warnings){
close(); close();
List<String> warnings = new ArrayList<String>();
// check we have some assets to copy to sdcard // check we have some assets to copy to sdcard
warnings.addAll(checkAssets(progress)); warnings.addAll(checkAssets(progress));
progress.notifyEvent(InitEvents.ASSETS_COPIED);
initRenderers(progress); initRenderers(progress);
progress.notifyEvent(InitEvents.INIT_RENDERERS);
reloadIndexes(progress, warnings);
progress.notifyEvent(InitEvents.MAPS_INITIALIZED);
return warnings;
}
public List<String> reloadIndexes(IProgress progress, List<String> warnings) {
geoidAltitudeCorrection = new GeoidAltitudeCorrection(context.getAppPath(null)); geoidAltitudeCorrection = new GeoidAltitudeCorrection(context.getAppPath(null));
indexRegionsBoundaries(progress, false);
// do it lazy // do it lazy
// indexingImageTiles(progress); // indexingImageTiles(progress);
context.getSelectedGpxHelper().loadGPXTracks(progress);
warnings.addAll(indexingMaps(progress)); warnings.addAll(indexingMaps(progress));
warnings.addAll(indexVoiceFiles(progress)); warnings.addAll(indexVoiceFiles(progress));
warnings.addAll(OsmandPlugin.onIndexingFiles(progress)); warnings.addAll(OsmandPlugin.onIndexingFiles(progress));
warnings.addAll(indexAdditionalMaps(progress)); warnings.addAll(indexAdditionalMaps(progress));
return warnings; return warnings;
} }
@ -429,21 +432,6 @@ public class ResourceManager {
return context.getAppCustomization().onIndexingFiles(progress, indexFileNames); return context.getAppCustomization().onIndexingFiles(progress, indexFileNames);
} }
private void indexRegionsBoundaries(IProgress progress, boolean overwrite) {
try {
File file = context.getAppPath("regions.ocbf");
if (file != null) {
if (!file.exists() || overwrite) {
Algorithms.streamCopy(OsmandRegions.class.getResourceAsStream("regions.ocbf"),
new FileOutputStream(file));
}
}
regions.prepareFile(file.getAbsolutePath());
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
public List<String> indexVoiceFiles(IProgress progress){ public List<String> indexVoiceFiles(IProgress progress){
File file = context.getAppPath(IndexConstants.VOICE_INDEX_DIR); File file = context.getAppPath(IndexConstants.VOICE_INDEX_DIR);
@ -476,12 +464,10 @@ public class ResourceManager {
if(applicationDataDir.canWrite()){ if(applicationDataDir.canWrite()){
try { try {
progress.startTask(context.getString(R.string.installing_new_resources), -1); progress.startTask(context.getString(R.string.installing_new_resources), -1);
indexRegionsBoundaries(progress, true);
AssetManager assetManager = context.getAssets(); AssetManager assetManager = context.getAssets();
boolean isFirstInstall = context.getSettings().PREVIOUS_INSTALLED_VERSION.get().equals(""); boolean isFirstInstall = context.getSettings().PREVIOUS_INSTALLED_VERSION.get().equals("");
unpackBundledAssets(assetManager, applicationDataDir, progress, isFirstInstall); unpackBundledAssets(assetManager, applicationDataDir, progress, isFirstInstall);
context.getSettings().PREVIOUS_INSTALLED_VERSION.set(Version.getFullVersion(context)); context.getSettings().PREVIOUS_INSTALLED_VERSION.set(Version.getFullVersion(context));
context.getPoiFilters().updateFilters(false); context.getPoiFilters().updateFilters(false);
} catch (SQLiteException e) { } catch (SQLiteException e) {
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
@ -1027,7 +1013,7 @@ public class ResourceManager {
} }
public OsmandRegions getOsmandRegions() { public OsmandRegions getOsmandRegions() {
return regions; return context.getRegions();
} }

View file

@ -63,7 +63,7 @@ public class RoutingHelper {
private ApplicationMode mode; private ApplicationMode mode;
private OsmandSettings settings; private OsmandSettings settings;
private RouteProvider provider = new RouteProvider(); private RouteProvider provider;
private VoiceRouter voiceRouter; private VoiceRouter voiceRouter;
private boolean isDeviatedFromRoute = false; private boolean isDeviatedFromRoute = false;
@ -82,10 +82,11 @@ public class RoutingHelper {
return isDeviatedFromRoute; return isDeviatedFromRoute;
} }
public RoutingHelper(OsmandApplication context, CommandPlayer player){ public RoutingHelper(OsmandApplication context){
this.app = context; this.app = context;
settings = context.getSettings(); settings = context.getSettings();
voiceRouter = new VoiceRouter(this, settings, player); voiceRouter = new VoiceRouter(this, settings);
provider = new RouteProvider();
} }

View file

@ -76,9 +76,8 @@ public class VoiceRouter {
} }
private ConcurrentHashMap<VoiceMessageListener, Integer> voiceMessageListeners; private ConcurrentHashMap<VoiceMessageListener, Integer> voiceMessageListeners;
public VoiceRouter(RoutingHelper router, final OsmandSettings settings, CommandPlayer player) { public VoiceRouter(RoutingHelper router, final OsmandSettings settings) {
this.router = router; this.router = router;
this.player = player;
this.settings = settings; this.settings = settings;
empty = new Struct(""); empty = new Struct("");

View file

@ -1,8 +1,11 @@
package net.osmand.plus.sherpafy; package net.osmand.plus.sherpafy;
import android.support.v4.app.Fragment; import android.support.v4.app.Fragment;
import net.osmand.plus.AppInitializer;
import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandApplication;
import net.osmand.plus.R; import net.osmand.plus.R;
import net.osmand.plus.AppInitializer.AppInitializeListener;
import net.osmand.plus.AppInitializer.InitEvents;
import android.os.Bundle; import android.os.Bundle;
import android.view.View; import android.view.View;
import android.widget.ProgressBar; import android.widget.ProgressBar;
@ -27,19 +30,23 @@ public class SherpafyLoadingFragment extends Fragment {
@Override @Override
public void onViewCreated(final View view, Bundle savedInstanceState) { public void onViewCreated(final View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState); super.onViewCreated(view, savedInstanceState);
if(app.isApplicationInitializing()) { ((OsmandApplication) getActivity().getApplication()).checkApplicationIsBeingInitialized(getActivity(),
app.checkApplicationIsBeingInitialized(getActivity(), (TextView) view.findViewById(R.id.ProgressMessage), new AppInitializeListener() {
(ProgressBar) view.findViewById(R.id.ProgressBar), new Runnable() {
@Override @Override
public void run() { public void onProgress(AppInitializer init, InitEvents event) {
((TextView) view.findViewById(R.id.ProgressMessage)).setVisibility(View.GONE); String tn = init.getCurrentInitTaskName();
view.findViewById(R.id.ProgressBar).setVisibility(View.GONE); if (tn != null) {
((TourViewActivity)getActivity()).showSelectedItem(); ((TextView) view.findViewById(R.id.ProgressMessage)).setText(tn);
}
}
@Override
public void onFinish(AppInitializer init) {
((TourViewActivity) getActivity()).showSelectedItem();
} }
}); });
} else {
((TourViewActivity)getActivity()).showSelectedItem();
}
} }
} }