Working version

This commit is contained in:
Victor Shcherb 2013-05-26 14:49:28 +02:00
parent c274747075
commit 85008c9c88
16 changed files with 877 additions and 590 deletions

View file

@ -19,8 +19,6 @@ public interface IProgress {
public void remaining(int remainingWork);
public void setGeneralProgress(String genProgress);
public void finishTask();
public boolean isIndeterminate();
@ -35,9 +33,6 @@ public interface IProgress {
@Override
public void startTask(String taskName, int work) {}
@Override
public void setGeneralProgress(String genProgress) {}
@Override
public void remaining(int remainingWork) {}

View file

@ -449,7 +449,7 @@ public class RenderingRulesStorage {
return depends;
}
};
storage.parseRulesFromXmlInputStream(RenderingRulesStorage.class.getResourceAsStream("winter+ski.render.xml"), resolver);
storage.parseRulesFromXmlInputStream(RenderingRulesStorage.class.getResourceAsStream("default.render.xml"), resolver);
// storage.printDebug(TEXT_RULES, System.out);
// long tm = System.nanoTime();
// int count = 100000;

View file

@ -66,6 +66,9 @@
<filter attrIntValue="3"/>
</renderingAttribute>
<!-- Use hmRendered for more map detail and better visibility of small roads -->
<renderingConstant name="hmRendered" value="false"/>
<renderingAttribute name="roadsDensityLimitPerTile">
<!-- Number of roads to display per tile -->
<filter appMode="pedestrian" attrIntValue="24"/>
@ -76,8 +79,7 @@
<!-- filter does not work for renderingConstant - the last one will be used, but better use separate depends Rendering style -->
<!-- Use hmRendered for more map detail and better visibility of small roads -->
<renderingConstant name="hmRendered" value="false"/>
<!-- roadColors="Modified Mapnik" -->
<renderingConstant name="motorwayRoadColor" value="#809bff"/>

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

View file

@ -5,6 +5,70 @@
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/ProgressView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:visibility="gone" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginRight="3dp"
android:gravity="center_vertical|left"
android:orientation="horizontal" >
<ProgressBar
android:id="@+id/IndeterminateProgressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="true"
android:indeterminateOnly="true"
android:visibility="gone" />
<TextView
android:id="@+id/ProgressMessage"
android:layout_width="wrap_content"
android:layout_height="48dp"
android:layout_marginLeft="3dp"
android:ellipsize="marquee"
android:gravity="left|center_vertical"
android:singleLine="true"
android:text=""
android:textSize="14sp" />
<TextView
android:id="@+id/ProgressPercent"
android:layout_width="fill_parent"
android:layout_height="48dp"
android:layout_weight="1"
android:gravity="right|center_vertical"
android:text=""
android:textSize="14sp" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="3dp"
android:layout_marginRight="3dp"
android:gravity="center_vertical"
android:orientation="horizontal" >
<ProgressBar
android:id="@+id/DeterminateProgressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<ImageButton
android:id="@+id/Cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/a_1_navigation_cancel_small_dark" />
</LinearLayout>
</LinearLayout>
<EditText
android:id="@+id/search_box"
@ -18,14 +82,14 @@
<ExpandableListView
android:id="@android:id/list"
style="@style/OsmandListView"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"
android:layout_marginTop="0dp"
android:layout_weight="1"
android:groupIndicator="@android:color/transparent"
style="@style/OsmandListView" />
android:groupIndicator="@android:color/transparent" />
<Button
android:id="@+id/DownloadButton"

View file

@ -9,7 +9,7 @@
3. All your modified/created strings are in the top of the file (to make easier find what\'s translated).
PLEASE: Have a look at http://code.google.com/p/osmand/wiki/UIConsistency, it may really improve your and our work :-) Thx - Hardy
-->
<string name="wait_current_task_finished">Please wait current task will be finished</string>
<string name="use_kalman_filter_compass_descr">Use Kalman filter to avoid compass aberrations</string>
<string name="use_kalman_filter_compass">Use Kalman filter</string>
<string name="access_mark_final_location_first">Accessibility mode : please select destination first</string>
@ -1289,7 +1289,7 @@ Afghanistan, Albania, Algeria, Andorra, Angola, Anguilla, Antigua and Barbuda, A
<string name="address">Address</string>
<string name="download_index_success">Download successful</string>
<string name="error_io_error">I/O error occured</string>
<string name="downloading_file">Downloading file&#8230;</string>
<string name="downloading_file_new">Downloading </string>
<string name="downloading">Downloading&#8230;</string>
<string name="downloading_list_indexes">Downloading list of available regions&#8230;</string>
<string name="list_index_files_was_not_loaded">The list of regions was not retrieved from osmand.net.</string>

View file

@ -199,9 +199,4 @@ public class ProgressDialogImplementation implements IProgress {
deltaProgress = 0;
}
@Override
public void setGeneralProgress(String genProgress) {
// not implemented yet
}
}

View file

@ -3,7 +3,6 @@ package net.osmand.plus.activities;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
@ -11,9 +10,7 @@ import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import net.osmand.IProgress;
import net.osmand.IndexConstants;
import net.osmand.PlatformUtil;
import net.osmand.access.AccessibleToast;
import net.osmand.map.RegionCountry;
import net.osmand.map.RegionRegistry;
@ -21,27 +18,21 @@ import net.osmand.plus.ClientContext;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.OsmandPlugin;
import net.osmand.plus.OsmandSettings;
import net.osmand.plus.OsmandSettings.OsmandPreference;
import net.osmand.plus.ProgressDialogImplementation;
import net.osmand.plus.R;
import net.osmand.plus.Version;
import net.osmand.plus.base.BasicProgressAsyncTask;
import net.osmand.plus.base.SuggestExternalDirectoryDialog;
import net.osmand.plus.download.DownloadActivityType;
import net.osmand.plus.download.DownloadEntry;
import net.osmand.plus.download.DownloadFileHelper;
import net.osmand.plus.download.DownloadFileHelper.DownloadFileShowWarning;
import net.osmand.plus.download.DownloadIndexAdapter;
import net.osmand.plus.download.DownloadIndexListThread;
import net.osmand.plus.download.DownloadTracker;
import net.osmand.plus.download.DownloadIndexesThread;
import net.osmand.plus.download.IndexItem;
import net.osmand.plus.download.IndexItemCategory;
import net.osmand.plus.download.SrtmIndexItem;
import net.osmand.plus.resources.ResourceManager;
import net.osmand.plus.srtmplugin.SRTMPlugin;
import net.osmand.util.Algorithms;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
@ -49,6 +40,7 @@ import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.os.StatFs;
import android.text.Editable;
@ -60,6 +52,8 @@ import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.ActionBar;
@ -70,8 +64,6 @@ import com.actionbarsherlock.view.SubMenu;
public class DownloadIndexActivity extends OsmandExpandableListActivity {
private static final org.apache.commons.logging.Log log = PlatformUtil.getLog(DownloadIndexActivity.class);
/** menus **/
private static final int MORE_ID = 10;
private static final int RELOAD_ID = 0;
@ -79,17 +71,10 @@ public class DownloadIndexActivity extends OsmandExpandableListActivity {
private static final int DESELECT_ALL_ID = 2;
private static final int FILTER_EXISTING_REGIONS = 3;
/** dialogs **/
public static final int DIALOG_MAP_VERSION_UPDATE = 0;
public static final int DIALOG_PROGRESS_FILE = 1;
public static final int DIALOG_PROGRESS_LIST = 2;
public static final String FILTER_KEY = "filter";
private static DownloadIndexListThread downloadListIndexThread;
private static DownloadIndexesThread downloadListIndexThread;
private ProgressDialog progressFileDlg = null;
private TreeMap<IndexItem, List<DownloadEntry>> entriesToDownload = new TreeMap<IndexItem, List<DownloadEntry>>();
private DownloadActivityType type = DownloadActivityType.NORMAL_FILE;
@ -98,25 +83,35 @@ public class DownloadIndexActivity extends OsmandExpandableListActivity {
private TextWatcher textWatcher ;
private EditText filterText;
private DownloadFileHelper downloadFileHelper = null;
private OsmandSettings settings;
private ArrayAdapter<String> spinnerAdapter;
private List<SrtmIndexItem> cachedSRTMFiles;
private View progressView;
private ProgressBar indeterminateProgressBar;
private ProgressBar determinateProgressBar;
private TextView progressMessage;
private TextView progressPercent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
settings = ((OsmandApplication) getApplication()).getSettings();
if(downloadListIndexThread == null) {
downloadListIndexThread = new DownloadIndexListThread(this);
downloadListIndexThread = new DownloadIndexesThread(this);
}
setContentView(R.layout.download_index);
indeterminateProgressBar = (ProgressBar) findViewById(R.id.IndeterminateProgressBar);
determinateProgressBar = (ProgressBar) findViewById(R.id.DeterminateProgressBar);
progressView = findViewById(R.id.ProgressView);
progressMessage = (TextView) findViewById(R.id.ProgressMessage);
progressPercent = (TextView) findViewById(R.id.ProgressPercent);
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
getSupportActionBar().setTitle(R.string.local_index_download);
// recreation upon rotation is prevented in manifest file
downloadFileHelper = new DownloadFileHelper(getClientContext());
findViewById(R.id.DownloadButton).setOnClickListener(new View.OnClickListener(){
@Override
@ -155,10 +150,11 @@ public class DownloadIndexActivity extends OsmandExpandableListActivity {
}
}
List<IndexItem> list = new ArrayList<IndexItem>();
downloadListIndexThread.setUiActivity(this);
if (downloadListIndexThread.getCachedIndexFiles() != null && downloadListIndexThread.isDownloadedFromInternet()) {
list = getFilteredByType();
} else {
downloadIndexList();
downloadListIndexThread.runReloadIndexFiles();
}
DownloadIndexAdapter adapter = new DownloadIndexAdapter(this, list);
setListAdapter(adapter);
@ -185,6 +181,12 @@ public class DownloadIndexActivity extends OsmandExpandableListActivity {
});
}
@Override
protected void onResume() {
super.onResume();
updateProgress(false, downloadListIndexThread.getCurrentRunningTask());
}
private void showDialogOfFreeDownloadsIfNeeded() {
@ -223,16 +225,12 @@ public class DownloadIndexActivity extends OsmandExpandableListActivity {
}
}
private void downloadIndexList() {
showDialog(DIALOG_PROGRESS_LIST);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == RELOAD_ID) {
// re-create the thread
downloadListIndexThread = new DownloadIndexListThread(this);
downloadIndexList();
downloadListIndexThread.runReloadIndexFiles();
return true;
} else if (item.getItemId() == SELECT_ALL_ID) {
selectAll();
@ -321,7 +319,7 @@ public class DownloadIndexActivity extends OsmandExpandableListActivity {
}
private void makeDownloadVisible() {
public void makeDownloadVisible() {
findViewById(R.id.DownloadButton).setVisibility(View.VISIBLE);
if(Version.isFreeVersion(getMyApplication())) {
int left = MAXIMUM_AVAILABLE_FREE_DOWNLOADS - settings.NUMBER_OF_FREE_DOWNLOADS.get() - entriesToDownload.size();
@ -459,81 +457,6 @@ public class DownloadIndexActivity extends OsmandExpandableListActivity {
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_MAP_VERSION_UPDATE:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.map_version_changed_info);
builder.setPositiveButton(R.string.button_upgrade_osmandplus, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=pname:net.osmand.plus"));
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
log.error("Exception", e);
}
}
});
builder.setNegativeButton(R.string.default_buttons_cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
removeDialog(DIALOG_MAP_VERSION_UPDATE);
}
});
return builder.create();
case DIALOG_PROGRESS_LIST:
ProgressDialog dialog = new ProgressDialog(this);
dialog.setTitle(R.string.downloading);
dialog.setMessage(getString(R.string.downloading_list_indexes));
dialog.setCancelable(true);
return dialog;
case DIALOG_PROGRESS_FILE:
ProgressDialogImplementation progress = ProgressDialogImplementation.createProgressDialog(
DownloadIndexActivity.this,
getString(R.string.downloading),
getString(R.string.downloading_file),
ProgressDialog.STYLE_HORIZONTAL,
new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
makeSureUserCancelDownload(dialog);
}
});
progressFileDlg = progress.getDialog();
progressFileDlg.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
downloadFileHelper.setInterruptDownloading(true);
}
});
return progress.getDialog();
}
return null;
}
@Override
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case DIALOG_PROGRESS_FILE:
DownloadIndexesAsyncTask task = new DownloadIndexesAsyncTask(new ProgressDialogImplementation(progressFileDlg,true));
IndexItem[] indexes = entriesToDownload.keySet().toArray(new IndexItem[0]);
task.execute(indexes);
break;
case DIALOG_PROGRESS_LIST:
downloadListIndexThread.setUiActivity(this);
if(downloadListIndexThread.getState() == Thread.State.NEW){
downloadListIndexThread.start();
} else if(downloadListIndexThread.getState() == Thread.State.TERMINATED){
// possibly exception occurred we don't have cache of files
downloadListIndexThread = new DownloadIndexListThread(this);
downloadListIndexThread.setUiActivity(this);
downloadListIndexThread.start();
}
break;
}
}
public ExpandableListView getListView() {
return super.getExpandableListView();
@ -543,6 +466,7 @@ public class DownloadIndexActivity extends OsmandExpandableListActivity {
return super.getExpandableListAdapter();
}
// TODO
private void makeSureUserCancelDownload(final DialogInterface dlg) {
Builder bld = new AlertDialog.Builder(this);
bld.setTitle(getString(R.string.default_buttons_cancel));
@ -700,7 +624,7 @@ public class DownloadIndexActivity extends OsmandExpandableListActivity {
StatFs fs = new StatFs(dir.getAbsolutePath());
asz = (((long) fs.getAvailableBlocks()) * fs.getBlockSize()) / (1 << 20);
}
if(asz != -1 && asz < sz * 2 ){
if(asz != -1 && asz < sz ){
AccessibleToast.makeText(this, getString(R.string.download_files_not_enough_space, sz, asz), Toast.LENGTH_LONG).show();
} else {
Builder builder = new AlertDialog.Builder(this);
@ -713,7 +637,7 @@ public class DownloadIndexActivity extends OsmandExpandableListActivity {
builder.setPositiveButton(R.string.default_buttons_yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
showDialog(DIALOG_PROGRESS_FILE);
downloadListIndexThread.runDownloadFiles(entriesToDownload);
}
});
builder.setNegativeButton(R.string.default_buttons_no, null);
@ -726,9 +650,6 @@ public class DownloadIndexActivity extends OsmandExpandableListActivity {
@Override
protected void onDestroy() {
super.onDestroy();
if(isFinishing()){
downloadFileHelper.setInterruptDownloading(true);
}
if (textWatcher != null) {
EditText filterText = (EditText) findViewById(R.id.search_box);
filterText.removeTextChangedListener(textWatcher);
@ -736,168 +657,34 @@ public class DownloadIndexActivity extends OsmandExpandableListActivity {
downloadListIndexThread.setUiActivity(null);
}
public class DownloadIndexesAsyncTask extends AsyncTask<IndexItem, Object, String> implements DownloadFileShowWarning {
private IProgress progress;
private OsmandPreference<Integer> downloads;
public DownloadIndexesAsyncTask(ProgressDialogImplementation progressDialogImplementation) {
this.progress = progressDialogImplementation;
downloads = DownloadIndexActivity.this.getMyApplication().getSettings().NUMBER_OF_FREE_DOWNLOADS;
}
@Override
protected void onProgressUpdate(Object... values) {
for (Object o : values) {
if (o instanceof DownloadEntry) {
((DownloadIndexAdapter) getExpandableListAdapter()).notifyDataSetInvalidated();
if(entriesToDownload.isEmpty()){
findViewById(R.id.DownloadButton).setVisibility(View.GONE);
} else {
makeDownloadVisible();
}
} else if (o instanceof String) {
AccessibleToast.makeText(DownloadIndexActivity.this, (String) o, Toast.LENGTH_LONG).show();
}
}
super.onProgressUpdate(values);
}
@Override
protected void onPreExecute() {
downloadFileHelper.setInterruptDownloading(false);
View mainView = findViewById(R.id.MainLayout);
if (mainView != null) {
mainView.setKeepScreenOn(true);
}
}
@Override
protected void onPostExecute(String result) {
if (result != null) {
AccessibleToast.makeText(DownloadIndexActivity.this, result, Toast.LENGTH_LONG).show();
}
View mainView = DownloadIndexActivity.this.findViewById(R.id.MainLayout);
if (mainView != null) {
mainView.setKeepScreenOn(false);
}
DownloadIndexActivity.this.updateLoadedFiles();
DownloadIndexAdapter adapter = ((DownloadIndexAdapter) getExpandableListAdapter());
if (adapter != null) {
adapter.notifyDataSetInvalidated();
}
}
private int countAllDownloadEntry(IndexItem... filesToDownload){
int t = 0;
for(IndexItem i : filesToDownload){
List<DownloadEntry> list = DownloadIndexActivity.this.entriesToDownload.get(i);
if(list != null){
t += list.size();
}
}
return t;
}
@Override
protected String doInBackground(IndexItem... filesToDownload) {
try {
List<File> filesToReindex = new ArrayList<File>();
boolean forceWifi = DownloadIndexActivity.this.downloadFileHelper.isWifiConnected();
int counter = 1;
int all = countAllDownloadEntry(filesToDownload);
for (int i = 0; i < filesToDownload.length; i++) {
IndexItem filename = filesToDownload[i];
List<DownloadEntry> list = DownloadIndexActivity.this.entriesToDownload.get(filename);
if (list != null) {
for (DownloadEntry entry : list) {
String indexOfAllFiles = all <= 1 ? "" : (" [" + counter + "/" + all + "]");
counter++;
boolean result = downloadFile(entry, filesToReindex, indexOfAllFiles, forceWifi);
if (result) {
DownloadIndexActivity.this.entriesToDownload.remove(filename);
if (entry.type != DownloadActivityType.SRTM_FILE && entry.type != DownloadActivityType.HILLSHADE_FILE) {
downloads.set(downloads.get() + 1);
}
if (entry.existingBackupFile != null) {
Algorithms.removeAllFiles(entry.existingBackupFile);
}
trackEvent(entry);
publishProgress(entry);
}
}
}
}
boolean vectorMapsToReindex = false;
for (File f : filesToReindex) {
if (f.getName().endsWith(IndexConstants.BINARY_MAP_INDEX_EXT)) {
vectorMapsToReindex = true;
break;
}
}
// reindex vector maps all at one time
ResourceManager manager = getMyApplication().getResourceManager();
manager.indexVoiceFiles(progress);
if (vectorMapsToReindex) {
List<String> warnings = manager.indexingMaps(progress);
if (!warnings.isEmpty()) {
return warnings.get(0);
}
}
} catch (InterruptedException e) {
// do not dismiss dialog
} finally {
if (DownloadIndexActivity.this.progressFileDlg != null) {
removeDialog(DownloadIndexActivity.DIALOG_PROGRESS_FILE);
DownloadIndexActivity.this.progressFileDlg = null;
}
}
return null;
}
private void trackEvent(DownloadEntry entry) {
String v = Version.getAppName(getMyApplication());
if (Version.isProductionVersion(getMyApplication())) {
v = Version.getFullVersion(getMyApplication());
} else {
v += " test";
}
new DownloadTracker().trackEvent(getMyApplication(), v, Version.getAppName(getMyApplication()),
entry.baseName, 1, DownloadIndexActivity.this.getString(R.string.ga_api_key));
}
@Override
public void showWarning(String warning) {
publishProgress(warning);
}
public boolean downloadFile(DownloadEntry de, List<File> filesToReindex, String indexOfAllFiles, boolean forceWifi)
throws InterruptedException {
boolean res = false;
if (de.isAsset) {
try {
ResourceManager.copyAssets(getAssets(), de.fileToSave.getPath(), de.fileToUnzip);
de.fileToUnzip.setLastModified(de.dateModified);
res = true;
} catch (IOException e) {
log.error("Copy exception", e);
}
} else {
res = downloadFileHelper.downloadFile(de, progress, filesToReindex, indexOfAllFiles, this, forceWifi);
}
if (res && de.attachedEntry != null) {
return downloadFile(de.attachedEntry, filesToReindex, indexOfAllFiles, forceWifi);
}
return res;
}
}
public ClientContext getClientContext() {
return getMyApplication();
}
public void updateProgress(boolean updateOnlyProgress, BasicProgressAsyncTask<?, ?, ?> basicProgressAsyncTask) {
if(updateOnlyProgress) {
if(!basicProgressAsyncTask.isIndeterminate()) {
progressPercent.setText(basicProgressAsyncTask.getProgressPercentage() +"%");
determinateProgressBar.setProgress(basicProgressAsyncTask.getProgressPercentage());
}
} else {
boolean visible = basicProgressAsyncTask != null && basicProgressAsyncTask.getStatus() != Status.FINISHED;
progressView.setVisibility(visible ? View.VISIBLE : View.GONE);
if (visible) {
boolean indeterminate = basicProgressAsyncTask.isIndeterminate();
indeterminateProgressBar.setVisibility(!indeterminate ? View.GONE : View.VISIBLE);
determinateProgressBar.setVisibility(indeterminate ? View.GONE : View.VISIBLE);
progressPercent.setVisibility(indeterminate ? View.GONE : View.VISIBLE);
progressMessage.setText(basicProgressAsyncTask.getDescription());
if (!indeterminate) {
progressPercent.setText(basicProgressAsyncTask.getProgressPercentage() + "%");
determinateProgressBar.setProgress(basicProgressAsyncTask.getProgressPercentage());
}
}
}
}
}

View file

@ -0,0 +1,124 @@
package net.osmand.plus.base;
import net.osmand.IProgress;
import net.osmand.plus.R;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
public abstract class BasicProgressAsyncTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> implements IProgress {
protected String taskName;
protected int progress;
protected int deltaProgress;
protected int work;
protected String message = ""; //$NON-NLS-1$
protected Context ctx;
protected boolean interrupted = false;
private Handler uiHandler;
public BasicProgressAsyncTask(Context ctx) {
this.ctx = ctx;
this.work = -1;
}
public String getDescription() {
return message;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
uiHandler = new Handler();
this.interrupted = false;
}
@Override
public void startTask(String taskName, int work) {
if (taskName == null) {
taskName = ""; //$NON-NLS-1$
}
message = taskName;
this.taskName = taskName;
startWork(work);
updProgress(false);
}
protected abstract void updateProgress(boolean updateOnlyProgress);
@Override
public void startWork(int work) {
this.work = work;
if (this.work == 0) {
this.work = 1;
}
progress = 0;
deltaProgress = 0;
}
@Override
public void progress(int deltaWork) {
if (!isIndeterminate()) {
this.deltaProgress += deltaWork;
// update only each percent
if ((deltaProgress > (work / 100)) || ((progress + deltaProgress) >= work)) {
this.progress += deltaProgress;
this.deltaProgress = 0;
updProgress(true);
}
}
}
private void updProgress(final boolean updateOnlyProgress) {
if(uiHandler != null && (!uiHandler.hasMessages(1) || !updateOnlyProgress)) {
Message msg = Message.obtain(uiHandler, new Runnable() {
@Override
public void run() {
updateProgress(updateOnlyProgress);
}
});
msg.what = 1;
uiHandler.sendMessage(msg);
}
}
@Override
public void remaining(int remainingWork) {
int newprogress = work - remainingWork;
progress(newprogress - this.progress);
}
@Override
public void finishTask() {
work = -1;
progress = 0;
if (taskName != null) {
message = ctx.getResources().getString(R.string.finished_task) + " : " + taskName; //$NON-NLS-1$
updProgress(false);
}
}
@Override
public boolean isIndeterminate() {
return work == -1;
}
public int getProgressPercentage() {
if (work > 0) {
return (progress * 100) / work;
}
return progress;
}
public void setInterrupted(boolean interrupted) {
this.interrupted = interrupted;
}
@Override
public boolean isInterrupted() {
return interrupted;
}
}

View file

@ -4,11 +4,15 @@ import java.io.File;
import java.util.List;
public class DownloadEntry {
public File fileToSave;
public File fileToUnzip;
public boolean unzip;
public Long dateModified;
public double sizeMB;
public File targetFile;
public boolean zipStream;
public boolean unzipFolder;
public File fileToDownload;
public String baseName;
public String urlToDownload;
public int parts;
@ -25,8 +29,7 @@ public class DownloadEntry {
public DownloadEntry(String assetName, String fileName, long dateModified) {
this.dateModified = dateModified;
fileToUnzip = new File(fileName);
fileToSave = new File(assetName);
targetFile = new File(fileName);
isAsset = true;
}

View file

@ -1,13 +1,12 @@
package net.osmand.plus.download;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
@ -18,6 +17,7 @@ import net.osmand.PlatformUtil;
import net.osmand.plus.ClientContext;
import net.osmand.plus.R;
import net.osmand.plus.Version;
import net.osmand.util.Algorithms;
import org.apache.commons.logging.Log;
@ -40,85 +40,156 @@ public class DownloadFileHelper {
public void showWarning(String warning);
}
private void downloadFileInternal(String fileName, FileOutputStream out, URL url, String part, String indexOfAllFiles,
IProgress progress, boolean forceWifi) throws IOException, InterruptedException {
InputStream is = null;
byte[] buffer = new byte[BUFFER_SIZE];
int read = 0;
int length = 0;
int fileread = 0;
int triesDownload = TRIES_TO_DOWNLOAD;
boolean notFound = false;
boolean first = true;
try {
while (triesDownload > 0) {
try {
if (!first) {
log.info("Reconnecting"); //$NON-NLS-1$
try {
Thread.sleep(TIMEOUT_BETWEEN_DOWNLOADS);
} catch (InterruptedException e) {
private InputStream getInputStreamToDownload(final URL url, final boolean forceWifi) throws IOException {
InputStream cis = new InputStream() {
byte[] buffer = new byte[BUFFER_SIZE];
int bufLen = 0;
int bufRead = 0;
int length = 0;
int fileread = 0;
int triesDownload = TRIES_TO_DOWNLOAD;
boolean notFound = false;
boolean first = true;
private InputStream is;
private void reconnect() throws IOException {
while (triesDownload > 0) {
try {
if (!first) {
log.info("Reconnecting"); //$NON-NLS-1$
try {
Thread.sleep(TIMEOUT_BETWEEN_DOWNLOADS);
} catch (InterruptedException e) {
}
}
}
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("User-Agent", Version.getFullVersion(ctx)); //$NON-NLS-1$
conn.setReadTimeout(30000);
if (fileread > 0) {
String range = "bytes="+fileread + "-" + (length -1); //$NON-NLS-1$ //$NON-NLS-2$
conn.setRequestProperty("Range", range); //$NON-NLS-1$
}
conn.setConnectTimeout(30000);
log.info(conn.getResponseMessage() + " " + conn.getResponseCode()); //$NON-NLS-1$
boolean wifiConnectionBroken = forceWifi && !isWifiConnected();
if(conn.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND){
notFound = true;
break;
}
if ((conn.getResponseCode() != HttpURLConnection.HTTP_PARTIAL &&
conn.getResponseCode() != HttpURLConnection.HTTP_OK ) || wifiConnectionBroken) {
conn.disconnect();
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("User-Agent", Version.getFullVersion(ctx)); //$NON-NLS-1$
conn.setReadTimeout(30000);
if (fileread > 0) {
String range = "bytes="+fileread + "-" + (length -1); //$NON-NLS-1$ //$NON-NLS-2$
conn.setRequestProperty("Range", range); //$NON-NLS-1$
}
conn.setConnectTimeout(30000);
log.info(conn.getResponseMessage() + " " + conn.getResponseCode()); //$NON-NLS-1$
boolean wifiConnectionBroken = forceWifi && !isWifiConnected();
if(conn.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND){
notFound = true;
break;
}
if ((conn.getResponseCode() != HttpURLConnection.HTTP_PARTIAL &&
conn.getResponseCode() != HttpURLConnection.HTTP_OK ) || wifiConnectionBroken) {
conn.disconnect();
triesDownload--;
continue;
}
is = conn.getInputStream();
if (first) {
length = conn.getContentLength();
}
first = false;
return;
} catch (IOException e) {
log.error("IOException", e); //$NON-NLS-1$
triesDownload--;
continue;
}
is = conn.getInputStream();
if (first) {
length = conn.getContentLength();
String taskName = ctx.getString(R.string.downloading_file) + indexOfAllFiles +" " + fileName;
if(part != null){
taskName += part;
}
progress.startTask(taskName, length / 1024); //$NON-NLS-1$
}
first = false;
while ((read = is.read(buffer)) != -1) {
if(interruptDownloading){
throw new InterruptedException();
}
out.write(buffer, 0, read);
fileread += read;
progress.remaining((length - fileread) / 1024);
}
if(length <= fileread){
triesDownload = 0;
}
} catch (IOException e) {
log.error("IOException", e); //$NON-NLS-1$
triesDownload--;
}
if(notFound) {
throw new IOException("File not found "); //$NON-NLS-1$
} else if(length == 0){
throw new IOException("File was not fully read"); //$NON-NLS-1$
} else if(triesDownload == 0 && length != fileread) {
throw new IOException("File was not fully read"); //$NON-NLS-1$
}
}
} finally {
if (is != null) {
is.close();
// use as prepare
@Override
public synchronized void reset() throws IOException {
reconnect();
}
}
if(notFound) {
throw new IOException("File not found " + fileName); //$NON-NLS-1$
} else if(length != fileread || length == 0){
throw new IOException("File was not fully read"); //$NON-NLS-1$
}
@Override
public int read(byte[] buffer, int offset, int len) throws IOException {
int r = 0;
while(len > 0) {
if(bufLen == -1) {
return -1;
}
int av = bufLen - bufRead;
if(len > av){
System.arraycopy(this.buffer, bufRead, buffer, offset, av);
len -= av;
offset += av;
bufRead += av;
r += av;
refillBuffer();
} else {
System.arraycopy(this.buffer, bufRead, buffer, offset, len);
bufRead += len;
r += len;
return r;
}
}
return r;
}
@Override
public int read() throws IOException {
int r = -1;
if(bufLen == -1) {
return -1;
}
refillBuffer();
if(bufRead < bufLen) {
byte b = buffer[bufRead++];
return b >= 0 ? b : b + 256;
}
if (length <= fileread) {
throw new IOException("File was not fully read"); //$NON-NLS-1$
}
return r;
}
private void refillBuffer() throws IOException {
boolean readAgain = bufRead >= bufLen;
while (readAgain) {
if (is == null) {
reconnect();
}
try {
readAgain = false;
bufRead = 0;
if ((bufLen = is.read(buffer)) != -1) {
if (interruptDownloading) {
throw new IOException("Interrupted");
}
fileread += bufLen;
}
} catch (IOException e) {
log.error("IOException", e); //$NON-NLS-1$
triesDownload--;
reconnect();
readAgain = true;
}
}
}
@Override
public void close() throws IOException {
if (is != null) {
is.close();
}
}
@Override
public int available() throws IOException {
if (is == null) {
reconnect();
}
return length - fileread;
}
};
cis.reset();
return cis;
}
public boolean isWifiConnected(){
@ -126,62 +197,65 @@ public class DownloadFileHelper {
}
public boolean downloadFile(DownloadEntry de, IProgress progress,
List<File> toReIndex, String indexOfAllFiles,
DownloadFileShowWarning showWarningCallback, boolean forceWifi) throws InterruptedException {
List<File> toReIndex, DownloadFileShowWarning showWarningCallback, boolean forceWifi) throws InterruptedException {
try {
FileOutputStream out = new FileOutputStream(de.fileToSave);
try {
if (de.parts == 1) {
URL url = new URL(de.urlToDownload); //$NON-NLS-1$
log.info("Download " + de.urlToDownload);
downloadFileInternal(de.baseName, out, url, null, indexOfAllFiles, progress, forceWifi);
} else {
for (int i = 1; i <= de.parts; i++) {
URL url = new URL(de.urlToDownload + "-" + i); //$NON-NLS-1$
log.info("Download " + de.urlToDownload + "-" + i);
downloadFileInternal(de.baseName, out, url, " [" + i + "/" + de.parts + "]", indexOfAllFiles, progress, forceWifi);
}
final List<InputStream> downloadInputStreams = new ArrayList<InputStream>();
if (de.parts == 1) {
URL url = new URL(de.urlToDownload); //$NON-NLS-1$
downloadInputStreams.add(getInputStreamToDownload(url, forceWifi));
} else {
for (int i = 1; i <= de.parts; i++) {
URL url = new URL(de.urlToDownload + "-" + i); //$NON-NLS-1$
downloadInputStreams.add(getInputStreamToDownload(url, forceWifi));
}
} finally {
out.close();
}
unzipFile(de, progress, toReIndex);
de.fileToDownload = de.targetFile;
if(de.targetFile.exists() && !de.unzipFolder) {
de.fileToDownload = new File(de.targetFile.getParentFile(), de.targetFile.getName() +".download");
}
unzipFile(de, progress, downloadInputStreams);
if(!de.targetFile.getAbsolutePath().equals(de.fileToDownload.getAbsolutePath())){
Algorithms.removeAllFiles(de.targetFile);
boolean renamed = de.fileToDownload.renameTo(de.targetFile);
if(!renamed) {
showWarningCallback.showWarning(ctx.getString(R.string.error_io_error) + " : old file can't be deleted");
return false;
}
}
toReIndex.add(de.targetFile);
showWarningCallback.showWarning(ctx.getString(R.string.download_index_success));
return true;
} catch (IOException e) {
log.error("Exception ocurred", e); //$NON-NLS-1$
showWarningCallback.showWarning(ctx.getString(R.string.error_io_error) + " : " + e.getMessage());
// Possibly file is corrupted
de.fileToSave.delete();
Algorithms.removeAllFiles(de.fileToDownload);
return false;
} catch (InterruptedException e) {
// Possibly file is corrupted
de.fileToSave.delete();
throw e;
}
}
private void unzipFile(DownloadEntry de, IProgress progress, List<File> toReIndex)
throws FileNotFoundException, IOException {
if (de.fileToSave.getName().endsWith(".zip")) { //$NON-NLS-1$
if (de.unzip) {
de.fileToUnzip.mkdirs();
private void unzipFile(DownloadEntry de, IProgress progress, List<InputStream> is) throws IOException {
String taskName = ctx.getString(R.string.downloading_file_new) + " " + de.baseName;
CountingMultiInputStream fin = new CountingMultiInputStream(is);
int len = (int) fin.available();
progress.startTask(taskName, len / 1024);
if (!de.zipStream) {
copyFile(de, progress, fin, len, fin, de.fileToDownload);
} else {
if (de.unzipFolder) {
de.fileToDownload.mkdirs();
}
CountingInputStream fin = new CountingInputStream(new FileInputStream(de.fileToSave));
ZipInputStream zipIn = new ZipInputStream(fin);
ZipEntry entry = null;
boolean first = true;
int len = (int) de.fileToSave.length();
progress.startTask(ctx.getString(R.string.unzipping_file), len / 1024);
while ((entry = zipIn.getNextEntry()) != null) {
if (entry.isDirectory() || entry.getName().endsWith(IndexConstants.GEN_LOG_EXT)) {
continue;
}
File fs;
if (!de.unzip) {
if (!de.unzipFolder) {
if (first) {
fs = de.fileToUnzip;
fs = de.fileToDownload;
first = false;
} else {
String name = entry.getName();
@ -194,29 +268,33 @@ public class DownloadFileHelper {
name = name.substring(0, ind) + name.substring(i, name.length());
}
}
fs = new File(de.fileToUnzip.getParent(), name);
fs = new File(de.fileToDownload.getParent(), name);
}
} else {
fs = new File(de.fileToUnzip, entry.getName());
fs = new File(de.fileToDownload, entry.getName());
}
FileOutputStream out = new FileOutputStream(fs);
int read;
byte[] buffer = new byte[BUFFER_SIZE];
int remaining = len;
while ((read = zipIn.read(buffer)) != -1) {
out.write(buffer, 0, read);
remaining -= fin.lastReadCount();
progress.remaining(remaining / 1024);
}
out.close();
if (de.dateModified != null) {
fs.setLastModified(de.dateModified);
}
toReIndex.add(fs);
copyFile(de, progress, fin, len, zipIn, fs);
}
zipIn.close();
de.fileToSave.delete(); // zip is no needed more
}
fin.close();
}
private void copyFile(DownloadEntry de, IProgress progress, CountingMultiInputStream countIS, int length, InputStream toRead, File targetFile)
throws IOException {
FileOutputStream out = new FileOutputStream(targetFile);
int read;
byte[] buffer = new byte[BUFFER_SIZE];
int remaining = length;
while ((read = toRead.read(buffer)) != -1) {
out.write(buffer, 0, read);
remaining -= countIS.getAndClearReadCount();
progress.remaining(remaining / 1024);
}
out.close();
if (de.dateModified != null) {
targetFile.setLastModified(de.dateModified);
}
}
@ -229,92 +307,67 @@ public class DownloadFileHelper {
return interruptDownloading;
}
private static class CountingInputStream extends InputStream {
private static class CountingMultiInputStream extends InputStream {
private final InputStream delegate;
private final InputStream[] delegate;
private int count;
private int currentRead = 0;
public CountingInputStream(InputStream delegate) {
this.delegate = delegate;
public CountingMultiInputStream(List<InputStream> streams) {
this.delegate = streams.toArray(new InputStream[streams.size()]);
}
public int lastReadCount() {
@Override
public int read(byte[] buffer, int offset, int length)
throws IOException {
int r = -1;
while (r == -1 && currentRead < delegate.length) {
r = delegate[currentRead].read(buffer, offset, length);
if (r == -1) {
delegate[currentRead].close();
currentRead++;
}
}
if (r > 0) {
this.count += r;
}
return r;
}
@Override
public int read() throws IOException {
if (currentRead >= delegate.length) {
return -1;
}
int r = -1;
while (r == -1 && currentRead < delegate.length) {
r = delegate[currentRead].read();
if (r == -1) {
delegate[currentRead].close();
currentRead++;
} else {
this.count++;
}
}
return r;
}
@Override
public int available() throws IOException {
int av = 0;
for(int i = currentRead; i < delegate.length; i++) {
av += delegate[i].available();
}
return av;
}
public int getAndClearReadCount() {
int last = count;
count = 0;
return last;
}
@Override
public int available() throws IOException {
return delegate.available();
}
@Override
public void close() throws IOException {
delegate.close();
}
@Override
public boolean equals(Object o) {
return delegate.equals(o);
}
@Override
public int hashCode() {
return delegate.hashCode();
}
@Override
public void mark(int readlimit) {
delegate.mark(readlimit);
}
@Override
public boolean markSupported() {
return delegate.markSupported();
}
@Override
public int read() throws IOException {
int read = delegate.read();
if (read > 0) {
this.count++;;
}
return read;
}
@Override
public int read(byte[] buffer, int offset, int length)
throws IOException {
int read = delegate.read(buffer, offset, length);
if (read > 0) {
this.count += read;
}
return read;
}
@Override
public int read(byte[] buffer) throws IOException {
int read = delegate.read(buffer);
if (read > 0) {
this.count += read;
}
return read;
}
@Override
public void reset() throws IOException {
delegate.reset();
}
@Override
public long skip(long byteCount) throws IOException {
return delegate.skip(byteCount);
}
@Override
public String toString() {
return delegate.toString();
}
}
}

View file

@ -1,68 +0,0 @@
package net.osmand.plus.download;
import java.util.ArrayList;
import java.util.List;
import net.osmand.access.AccessibleToast;
import net.osmand.plus.R;
import net.osmand.plus.activities.DownloadIndexActivity;
import android.content.Context;
import android.view.View;
import android.widget.Toast;
public class DownloadIndexListThread extends Thread {
private DownloadIndexActivity uiActivity = null;
private IndexFileList indexFiles = null;
private final Context ctx;
public DownloadIndexListThread(Context ctx) {
super("DownloadIndexes");
this.ctx = ctx;
}
public void setUiActivity(DownloadIndexActivity uiActivity) {
this.uiActivity = uiActivity;
}
public List<IndexItem> getCachedIndexFiles() {
return indexFiles != null ? indexFiles.getIndexFiles() : null;
}
public boolean isDownloadedFromInternet() {
return indexFiles != null && indexFiles.isDownloadedFromInternet();
}
@Override
public void run() {
indexFiles = DownloadOsmandIndexesHelper.getIndexesList(ctx);
if (uiActivity != null) {
uiActivity.removeDialog(DownloadIndexActivity.DIALOG_PROGRESS_LIST);
uiActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
if (indexFiles != null) {
boolean basemapExists = uiActivity.getMyApplication().getResourceManager().containsBasemap();
IndexItem basemap = indexFiles.getBasemap();
if (!basemapExists && basemap != null) {
List<DownloadEntry> downloadEntry = basemap
.createDownloadEntry(uiActivity.getClientContext(), uiActivity.getType(), new ArrayList<DownloadEntry>());
uiActivity.getEntriesToDownload().put(basemap, downloadEntry);
AccessibleToast.makeText(uiActivity, R.string.basemap_was_selected_to_download, Toast.LENGTH_LONG).show();
uiActivity.findViewById(R.id.DownloadButton).setVisibility(View.VISIBLE);
}
uiActivity.setListAdapter(new DownloadIndexAdapter(uiActivity, uiActivity.getFilteredByType()));
if (indexFiles.isIncreasedMapVersion()) {
uiActivity.showDialog(DownloadIndexActivity.DIALOG_MAP_VERSION_UPDATE);
}
} else {
AccessibleToast.makeText(uiActivity, R.string.list_index_files_was_not_loaded, Toast.LENGTH_LONG).show();
}
}
});
}
}
}

View file

@ -0,0 +1,340 @@
package net.osmand.plus.download;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
import net.osmand.IndexConstants;
import net.osmand.PlatformUtil;
import net.osmand.access.AccessibleToast;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.OsmandSettings.OsmandPreference;
import net.osmand.plus.R;
import net.osmand.plus.Version;
import net.osmand.plus.activities.DownloadIndexActivity;
import net.osmand.plus.base.BasicProgressAsyncTask;
import net.osmand.plus.download.DownloadFileHelper.DownloadFileShowWarning;
import net.osmand.plus.resources.ResourceManager;
import net.osmand.util.Algorithms;
import org.apache.commons.logging.Log;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask.Status;
import android.view.View;
import android.widget.Toast;
public class DownloadIndexesThread {
private DownloadIndexActivity uiActivity = null;
private IndexFileList indexFiles = null;
private final Context ctx;
private OsmandApplication app;
private final static Log log = PlatformUtil.getLog(DownloadIndexesThread.class);
private DownloadFileHelper downloadFileHelper;
private BasicProgressAsyncTask<?, ?, ?> currentRunningTask;
public DownloadIndexesThread(Context ctx) {
this.ctx = ctx;
app = (OsmandApplication) ctx.getApplicationContext();
downloadFileHelper = new DownloadFileHelper(app);
}
public void setUiActivity(DownloadIndexActivity uiActivity) {
this.uiActivity = uiActivity;
}
public List<IndexItem> getCachedIndexFiles() {
return indexFiles != null ? indexFiles.getIndexFiles() : null;
}
public boolean isDownloadedFromInternet() {
return indexFiles != null && indexFiles.isDownloadedFromInternet();
}
public class DownloadIndexesAsyncTask extends BasicProgressAsyncTask<IndexItem, Object, String> implements DownloadFileShowWarning {
private OsmandPreference<Integer> downloads;
private TreeMap<IndexItem, List<DownloadEntry>> entriesToDownload;
public DownloadIndexesAsyncTask(Context ctx, TreeMap<IndexItem, List<DownloadEntry>> entriesToDownload) {
super(ctx);
this.entriesToDownload = entriesToDownload;
downloads = app.getSettings().NUMBER_OF_FREE_DOWNLOADS;
}
@Override
protected void onProgressUpdate(Object... values) {
for (Object o : values) {
if (o instanceof DownloadEntry) {
if (uiActivity != null) {
((DownloadIndexAdapter) uiActivity.getExpandableListAdapter()).notifyDataSetInvalidated();
if (entriesToDownload.isEmpty()) {
uiActivity.findViewById(R.id.DownloadButton).setVisibility(View.GONE);
} else {
uiActivity.makeDownloadVisible();
}
}
} else if (o instanceof String) {
AccessibleToast.makeText(ctx, (String) o, Toast.LENGTH_LONG).show();
}
}
super.onProgressUpdate(values);
}
@Override
protected void onPreExecute() {
currentRunningTask = this;
super.onPreExecute();
if (uiActivity != null) {
downloadFileHelper.setInterruptDownloading(false);
View mainView = uiActivity.findViewById(R.id.MainLayout);
if (mainView != null) {
mainView.setKeepScreenOn(true);
}
}
}
@Override
protected void onPostExecute(String result) {
if (result != null) {
AccessibleToast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
if (uiActivity != null) {
View mainView = uiActivity.findViewById(R.id.MainLayout);
if (mainView != null) {
mainView.setKeepScreenOn(false);
}
uiActivity.updateLoadedFiles();
DownloadIndexAdapter adapter = ((DownloadIndexAdapter) uiActivity.getExpandableListAdapter());
if (adapter != null) {
adapter.notifyDataSetInvalidated();
}
}
if(uiActivity != null) {
uiActivity.updateProgress(false, null);
}
}
private int countAllDownloadEntry(IndexItem... filesToDownload){
int t = 0;
for(IndexItem i : filesToDownload){
List<DownloadEntry> list = entriesToDownload.get(i);
if(list != null){
t += list.size();
}
}
return t;
}
@Override
protected String doInBackground(IndexItem... filesToDownload) {
try {
List<File> filesToReindex = new ArrayList<File>();
boolean forceWifi = downloadFileHelper.isWifiConnected();
int counter = 1;
int all = countAllDownloadEntry(filesToDownload);
for (int i = 0; i < filesToDownload.length; i++) {
IndexItem filename = filesToDownload[i];
List<DownloadEntry> list = entriesToDownload.get(filename);
if (list != null) {
for (DownloadEntry entry : list) {
String indexOfAllFiles = all <= 1 ? "" : (" [" + counter + "/" + all + "]");
counter++;
boolean result = downloadFile(entry, filesToReindex, indexOfAllFiles, forceWifi);
if (result) {
entriesToDownload.remove(filename);
if (entry.type != DownloadActivityType.SRTM_FILE && entry.type != DownloadActivityType.HILLSHADE_FILE) {
downloads.set(downloads.get() + 1);
}
if (entry.existingBackupFile != null) {
Algorithms.removeAllFiles(entry.existingBackupFile);
}
trackEvent(entry);
publishProgress(entry);
}
}
}
}
boolean vectorMapsToReindex = false;
for (File f : filesToReindex) {
if (f.getName().endsWith(IndexConstants.BINARY_MAP_INDEX_EXT)) {
vectorMapsToReindex = true;
break;
}
}
// reindex vector maps all at one time
ResourceManager manager = app.getResourceManager();
manager.indexVoiceFiles(this);
if (vectorMapsToReindex) {
List<String> warnings = manager.indexingMaps(this);
if (!warnings.isEmpty()) {
return warnings.get(0);
}
}
} catch (InterruptedException e) {
// do not dismiss dialog
}
return null;
}
private void trackEvent(DownloadEntry entry) {
String v = Version.getAppName(app);
if (Version.isProductionVersion(app)) {
v = Version.getFullVersion(app);
} else {
v += " test";
}
new DownloadTracker().trackEvent(app, v, Version.getAppName(app),
entry.baseName, 1, app.getString(R.string.ga_api_key));
}
@Override
public void showWarning(String warning) {
publishProgress(warning);
}
public boolean downloadFile(DownloadEntry de, List<File> filesToReindex, String indexOfAllFiles, boolean forceWifi)
throws InterruptedException {
boolean res = false;
if (de.isAsset) {
try {
ResourceManager.copyAssets(app.getAssets(), de.targetFile.getPath(), de.targetFile);
de.targetFile.setLastModified(de.dateModified);
res = true;
} catch (IOException e) {
log.error("Copy exception", e);
}
} else {
res = downloadFileHelper.downloadFile(de, this, filesToReindex, this, forceWifi);
}
if (res && de.attachedEntry != null) {
return downloadFile(de.attachedEntry, filesToReindex, indexOfAllFiles, forceWifi);
}
return res;
}
@Override
protected void updateProgress(boolean updateOnlyProgress) {
if(uiActivity != null) {
uiActivity.updateProgress(updateOnlyProgress, this);
}
}
}
private boolean checkRunning() {
if(getCurrentRunningTask() != null) {
AccessibleToast.makeText(app, R.string.wait_current_task_finished, Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
public void runDownloadFiles(TreeMap<IndexItem, List<DownloadEntry>> entriesToDownload){
if(checkRunning()) {
return;
}
IndexItem[] indexes = entriesToDownload.keySet().toArray(new IndexItem[0]);
DownloadIndexesAsyncTask task = new DownloadIndexesAsyncTask(ctx, entriesToDownload);
task.execute(indexes);
}
public void runReloadIndexFiles() {
if(checkRunning()) {
return;
}
final BasicProgressAsyncTask<Void, Void, IndexFileList> inst = new BasicProgressAsyncTask<Void, Void, IndexFileList>(ctx) {
@Override
protected IndexFileList doInBackground(Void... params) {
return DownloadOsmandIndexesHelper.getIndexesList(ctx);
};
@Override
protected void onPreExecute() {
currentRunningTask = this;
super.onPreExecute();
this.message = ctx.getString(R.string.downloading_list_indexes);
if(uiActivity != null) {
uiActivity.updateProgress(false, this);
}
}
protected void onPostExecute(IndexFileList result) {
indexFiles = result;
if (indexFiles != null && uiActivity != null) {
boolean basemapExists = uiActivity.getMyApplication().getResourceManager().containsBasemap();
IndexItem basemap = indexFiles.getBasemap();
if (!basemapExists && basemap != null) {
List<DownloadEntry> downloadEntry = basemap
.createDownloadEntry(uiActivity.getClientContext(), uiActivity.getType(), new ArrayList<DownloadEntry>());
uiActivity.getEntriesToDownload().put(basemap, downloadEntry);
AccessibleToast.makeText(uiActivity, R.string.basemap_was_selected_to_download, Toast.LENGTH_LONG).show();
uiActivity.findViewById(R.id.DownloadButton).setVisibility(View.VISIBLE);
}
uiActivity.setListAdapter(new DownloadIndexAdapter(uiActivity, uiActivity.getFilteredByType()));
if (indexFiles.isIncreasedMapVersion()) {
showWarnDialog();
}
} else {
AccessibleToast.makeText(ctx, R.string.list_index_files_was_not_loaded, Toast.LENGTH_LONG).show();
}
if(uiActivity != null) {
uiActivity.updateProgress(false, null);
}
}
private void showWarnDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
builder.setMessage(R.string.map_version_changed_info);
builder.setPositiveButton(R.string.button_upgrade_osmandplus, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=pname:net.osmand.plus"));
try {
ctx.startActivity(intent);
} catch (ActivityNotFoundException e) {
}
}
});
builder.setNegativeButton(R.string.default_buttons_cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
@Override
protected void updateProgress(boolean updateOnlyProgress) {
if(uiActivity != null) {
uiActivity.updateProgress(updateOnlyProgress, this);
}
};
};
inst.execute(new Void[0]);
}
public BasicProgressAsyncTask<?, ?, ?> getCurrentRunningTask() {
if(currentRunningTask != null && currentRunningTask.getStatus() == Status.FINISHED) {
currentRunningTask = null;
}
return currentRunningTask;
}
}

View file

@ -1,14 +1,10 @@
package net.osmand.plus.download;
import static net.osmand.IndexConstants.BINARY_MAP_INDEX_EXT;
import static net.osmand.IndexConstants.BINARY_MAP_INDEX_EXT_ZIP;
import static net.osmand.IndexConstants.TTSVOICE_INDEX_EXT_ZIP;
import static net.osmand.IndexConstants.VOICE_INDEX_EXT_ZIP;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@ -128,42 +124,39 @@ public class IndexItem implements Comparable<IndexItem> {
List<DownloadEntry> downloadEntries) {
String fileName = this.fileName;
File parent = null;
String toSavePostfix = null;
String toCheckPostfix = null;
String extension = null;
boolean unzipDir = false;
boolean zipStream = false;
boolean preventMediaIndexing = false;
if (fileName.endsWith(IndexConstants.BINARY_MAP_INDEX_EXT)) {
parent = ctx.getAppPath(IndexConstants.MAPS_PATH);
toSavePostfix = BINARY_MAP_INDEX_EXT;
toCheckPostfix = BINARY_MAP_INDEX_EXT;
extension = BINARY_MAP_INDEX_EXT;
} else if (fileName.endsWith(IndexConstants.BINARY_MAP_INDEX_EXT_ZIP)) {
parent = ctx.getAppPath(IndexConstants.MAPS_PATH);
toSavePostfix = BINARY_MAP_INDEX_EXT_ZIP;
toCheckPostfix = BINARY_MAP_INDEX_EXT;
zipStream = true;
extension = BINARY_MAP_INDEX_EXT;
} else if (fileName.endsWith(IndexConstants.EXTRA_ZIP_EXT)) {
parent = ctx.getAppPath("");
// unzipDir = true;
toSavePostfix = IndexConstants.EXTRA_ZIP_EXT;
toCheckPostfix = IndexConstants.EXTRA_EXT;
zipStream = true;
extension = IndexConstants.EXTRA_EXT;
} else if (fileName.endsWith(IndexConstants.SQLITE_EXT)) {
parent = ctx.getAppPath(IndexConstants.TILES_INDEX_DIR);
toSavePostfix = IndexConstants.SQLITE_EXT;
toCheckPostfix = IndexConstants.SQLITE_EXT;
extension = IndexConstants.SQLITE_EXT;
} else if (fileName.endsWith(IndexConstants.VOICE_INDEX_EXT_ZIP)) {
parent = ctx.getAppPath(IndexConstants.VOICE_INDEX_DIR);
toSavePostfix = VOICE_INDEX_EXT_ZIP;
toCheckPostfix = ""; //$NON-NLS-1$
zipStream = true;
extension = ""; //$NON-NLS-1$
unzipDir = true;
preventMediaIndexing = true;
} else if (fileName.endsWith(IndexConstants.TTSVOICE_INDEX_EXT_ZIP)) {
parent = ctx.getAppPath(IndexConstants.VOICE_INDEX_DIR);
toSavePostfix = TTSVOICE_INDEX_EXT_ZIP;
toCheckPostfix = ""; //$NON-NLS-1$
zipStream = true;
extension = ""; //$NON-NLS-1$
unzipDir = true;
}
if (type == DownloadActivityType.ROADS_FILE) {
toSavePostfix = "-roads" + toSavePostfix;
toCheckPostfix = "-roads" + toCheckPostfix;
extension = "-roads" + extension;
}
if (parent != null) {
parent.mkdirs();
@ -193,8 +186,8 @@ public class IndexItem implements Comparable<IndexItem> {
url += "hillshade=yes&";
}
entry.urlToDownload = url + "file=" + fileName;
entry.fileToSave = new File(parent, entry.baseName + toSavePostfix);
entry.unzip = unzipDir;
entry.zipStream = zipStream;
entry.unzipFolder = unzipDir;
try {
Date d = Algorithms.getDateFormat().parse(date);
entry.dateModified = d.getTime();
@ -210,8 +203,8 @@ public class IndexItem implements Comparable<IndexItem> {
if (parts != null) {
entry.parts = Integer.parseInt(parts);
}
entry.fileToUnzip = new File(parent, entry.baseName + toCheckPostfix);
File backup = new File(ctx.getAppPath(IndexConstants.BACKUP_INDEX_DIR), entry.fileToUnzip.getName());
entry.targetFile = new File(parent, entry.baseName + extension);
File backup = new File(ctx.getAppPath(IndexConstants.BACKUP_INDEX_DIR), entry.targetFile.getName());
if (backup.exists()) {
entry.existingBackupFile = backup;
}

View file

@ -83,12 +83,11 @@ public class SrtmIndexItem extends IndexItem {
String fullName = fileToDownload + "_" + IndexConstants.BINARY_MAP_VERSION + IndexConstants.BINARY_MAP_INDEX_EXT_ZIP;
entry.urlToDownload = url +"file=" + fullName;
// url + "file=" + fileName;
entry.fileToSave = new File(parent, fullName);
entry.unzip = false;
entry.unzipFolder = false;
entry.dateModified = System.currentTimeMillis();
entry.sizeMB = 10;
entry.parts = 1;
entry.fileToUnzip = new File(parent, entry.baseName + IndexConstants.BINARY_MAP_INDEX_EXT);
entry.targetFile = new File(parent, entry.baseName + IndexConstants.BINARY_MAP_INDEX_EXT);
downloadEntries.add(entry);
toDownload.size();
}