Live updates. Retry is not yet implemented.

This commit is contained in:
GaidamakUA 2015-12-15 18:46:24 +02:00
parent 0d5f82a757
commit b2924b12bd
4 changed files with 203 additions and 83 deletions

View file

@ -39,15 +39,15 @@ public class DownloadValidationManager {
return downloadThread; return downloadThread;
} }
public void startDownload(FragmentActivity activity, IndexItem... items) { public void startDownload(Context context, IndexItem... items) {
downloadFilesWithAllChecks(activity, items); downloadFilesWithAllChecks(context, items);
} }
public OsmandApplication getMyApplication() { public OsmandApplication getMyApplication() {
return app; return app;
} }
public void downloadFilesCheck_3_ValidateSpace(final FragmentActivity activity, final IndexItem... items) { public void downloadFilesCheck_3_ValidateSpace(final Context context, final IndexItem... items) {
long szLong = 0; long szLong = 0;
int i = 0; int i = 0;
for (IndexItem es : downloadThread.getCurrentDownloadingItems()) { for (IndexItem es : downloadThread.getCurrentDownloadingItems()) {
@ -62,65 +62,68 @@ public class DownloadValidationManager {
// get availabile space // get availabile space
double asz = downloadThread.getAvailableSpace(); double asz = downloadThread.getAvailableSpace();
if (asz != -1 && asz > 0 && sz / asz > 0.4) { if (asz != -1 && asz > 0 && sz / asz > 0.4) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity); AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(MessageFormat.format(activity.getString(R.string.download_files_question_space), i, sz, asz)); builder.setMessage(MessageFormat.format(context.getString(R.string.download_files_question_space), i, sz, asz));
builder.setPositiveButton(R.string.shared_string_yes, new DialogInterface.OnClickListener() { builder.setPositiveButton(R.string.shared_string_yes, new DialogInterface.OnClickListener() {
@Override @Override
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
downloadFileCheck_Final_Run(activity, items); downloadFileCheck_Final_Run(context, items);
} }
}); });
builder.setNegativeButton(R.string.shared_string_no, null); builder.setNegativeButton(R.string.shared_string_no, null);
builder.show(); builder.show();
} else { } else {
downloadFileCheck_Final_Run(activity, items); downloadFileCheck_Final_Run(context, items);
} }
} }
private void downloadFileCheck_Final_Run(FragmentActivity activity, IndexItem[] items) { private void downloadFileCheck_Final_Run(Context context, IndexItem[] items) {
downloadThread.runDownloadFiles(items); downloadThread.runDownloadFiles(items);
if (activity instanceof DownloadEvents) { if (context instanceof DownloadEvents) {
((DownloadEvents) activity).downloadInProgress(); ((DownloadEvents) context).downloadInProgress();
} }
} }
protected void downloadFilesWithAllChecks(FragmentActivity activity, IndexItem[] items) { protected void downloadFilesWithAllChecks(Context context, IndexItem[] items) {
downloadFilesCheck_1_FreeVersion(activity, items); downloadFilesCheck_1_FreeVersion(context, items);
} }
protected void downloadFilesCheck_1_FreeVersion(FragmentActivity activity, IndexItem[] items) { protected void downloadFilesCheck_1_FreeVersion(Context context, IndexItem[] items) {
if (Version.isFreeVersion(getMyApplication())) { if (Version.isFreeVersion(getMyApplication())) {
int total = settings.NUMBER_OF_FREE_DOWNLOADS.get(); int total = settings.NUMBER_OF_FREE_DOWNLOADS.get();
if (total > MAXIMUM_AVAILABLE_FREE_DOWNLOADS) { if (total > MAXIMUM_AVAILABLE_FREE_DOWNLOADS) {
new InstallPaidVersionDialogFragment() if (context instanceof FragmentActivity) {
.show(activity.getSupportFragmentManager(), InstallPaidVersionDialogFragment.TAG); FragmentActivity activity = (FragmentActivity) context;
new InstallPaidVersionDialogFragment()
.show(activity.getSupportFragmentManager(), InstallPaidVersionDialogFragment.TAG);
}
} else { } else {
downloadFilesCheck_2_Internet(activity, items); downloadFilesCheck_2_Internet(context, items);
} }
} else { } else {
downloadFilesCheck_2_Internet(activity, items); downloadFilesCheck_2_Internet(context, items);
} }
} }
protected void downloadFilesCheck_2_Internet(final FragmentActivity activity, final IndexItem[] items) { protected void downloadFilesCheck_2_Internet(final Context context, final IndexItem[] items) {
if (!getMyApplication().getSettings().isWifiConnected()) { if (!getMyApplication().getSettings().isWifiConnected()) {
if (getMyApplication().getSettings().isInternetConnectionAvailable()) { if (getMyApplication().getSettings().isInternetConnectionAvailable()) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity); AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(activity.getString(R.string.download_using_mobile_internet)); builder.setMessage(context.getString(R.string.download_using_mobile_internet));
builder.setPositiveButton(R.string.shared_string_yes, new DialogInterface.OnClickListener() { builder.setPositiveButton(R.string.shared_string_yes, new DialogInterface.OnClickListener() {
@Override @Override
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
downloadFilesCheck_3_ValidateSpace(activity, items); downloadFilesCheck_3_ValidateSpace(context, items);
} }
}); });
builder.setNegativeButton(R.string.shared_string_no, null); builder.setNegativeButton(R.string.shared_string_no, null);
builder.show(); builder.show();
} else { } else {
AccessibleToast.makeText(activity, R.string.no_index_file_to_download, Toast.LENGTH_LONG).show(); AccessibleToast.makeText(context, R.string.no_index_file_to_download, Toast.LENGTH_LONG).show();
} }
} else { } else {
downloadFilesCheck_3_ValidateSpace(activity, items); downloadFilesCheck_3_ValidateSpace(context, items);
} }
} }

View file

@ -3,15 +3,69 @@ package net.osmand.plus.liveupdates;
import android.content.BroadcastReceiver; import android.content.BroadcastReceiver;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.os.AsyncTask;
import android.widget.Toast;
import net.osmand.PlatformUtil; import net.osmand.PlatformUtil;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.R;
import net.osmand.plus.download.DownloadActivityType;
import net.osmand.plus.download.DownloadValidationManager;
import net.osmand.plus.download.IndexItem;
import net.osmand.plus.resources.IncrementalChangesManager;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import java.util.List;
public class LiveUpdatesAlarmReceiver extends BroadcastReceiver { public class LiveUpdatesAlarmReceiver extends BroadcastReceiver {
private static final Log LOG = PlatformUtil.getLog(LiveUpdatesAlarmReceiver.class); private static final Log LOG = PlatformUtil.getLog(LiveUpdatesAlarmReceiver.class);
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
LOG.debug("onReceive"); String localIndexInfo = intent.getAction();
new PerformLiveUpdateAsyncTask(context).execute(localIndexInfo);
}
public static class PerformLiveUpdateAsyncTask
extends AsyncTask<String, Object, IncrementalChangesManager.IncrementalUpdateList> {
private final Context context;
public PerformLiveUpdateAsyncTask(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
@Override
protected IncrementalChangesManager.IncrementalUpdateList doInBackground(String... params) {
final OsmandApplication myApplication = (OsmandApplication) context.getApplicationContext();
IncrementalChangesManager cm = myApplication.getResourceManager().getChangesManager();
return cm.getUpdatesByMonth(params[0]);
}
protected void onPostExecute(IncrementalChangesManager.IncrementalUpdateList result) {
if (result.errorMessage != null) {
Toast.makeText(context, result.errorMessage, Toast.LENGTH_SHORT).show();
} else {
List<IncrementalChangesManager.IncrementalUpdate> ll = result.getItemsForUpdate();
if (ll.isEmpty()) {
Toast.makeText(context, R.string.no_updates_available, Toast.LENGTH_SHORT).show();
} else {
int i = 0;
IndexItem[] is = new IndexItem[ll.size()];
for (IncrementalChangesManager.IncrementalUpdate iu : ll) {
IndexItem ii = new IndexItem(iu.fileName, "Incremental update", iu.timestamp, iu.sizeText,
iu.contentSize, iu.containerSize, DownloadActivityType.LIVE_UPDATES_FILE);
is[i++] = ii;
}
final OsmandApplication application = (OsmandApplication) context.getApplicationContext();
DownloadValidationManager downloadValidationManager =
new DownloadValidationManager(application);
downloadValidationManager.startDownload(context, is);
}
}
}
} }
} }

View file

@ -36,7 +36,9 @@ import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set;
public class LiveUpdatesFragment extends Fragment { public class LiveUpdatesFragment extends Fragment {
public static final String TITILE = "Live Updates"; public static final String TITILE = "Live Updates";
@ -119,22 +121,26 @@ public class LiveUpdatesFragment extends Fragment {
} }
public void notifyLiveUpdatesChanged() { public void notifyLiveUpdatesChanged() {
Set<LocalIndexInfo> changedSet = new HashSet<>();
for (LocalIndexInfo localIndexInfo : dataShouldUpdate) { for (LocalIndexInfo localIndexInfo : dataShouldUpdate) {
OsmandSettings.CommonPreference<Boolean> preference = OsmandSettings.CommonPreference<Boolean> preference =
preferenceForLocalIndex(LIVE_UPDATES_ON_POSTFIX, localIndexInfo); preferenceForLocalIndex(LIVE_UPDATES_ON_POSTFIX, localIndexInfo);
if (!preference.get()) { if (!preference.get()) {
dataShouldUpdate.remove(localIndexInfo); changedSet.add(localIndexInfo);
dataShouldNotUpdate.add(localIndexInfo);
} }
} }
dataShouldUpdate.removeAll(changedSet);
dataShouldNotUpdate.addAll(changedSet);
changedSet.clear();
for (LocalIndexInfo localIndexInfo : dataShouldNotUpdate) { for (LocalIndexInfo localIndexInfo : dataShouldNotUpdate) {
OsmandSettings.CommonPreference<Boolean> preference = OsmandSettings.CommonPreference<Boolean> preference =
preferenceForLocalIndex(LIVE_UPDATES_ON_POSTFIX, localIndexInfo); preferenceForLocalIndex(LIVE_UPDATES_ON_POSTFIX, localIndexInfo);
if (preference.get()) { if (preference.get()) {
dataShouldUpdate.add(localIndexInfo); changedSet.add(localIndexInfo);
dataShouldNotUpdate.remove(localIndexInfo);
} }
} }
dataShouldUpdate.addAll(changedSet);
dataShouldNotUpdate.removeAll(changedSet);
notifyDataSetChanged(); notifyDataSetChanged();
} }
@ -263,43 +269,7 @@ public class LiveUpdatesFragment extends Fragment {
void runLiveUpdate(final LocalIndexInfo info) { void runLiveUpdate(final LocalIndexInfo info) {
final String fnExt = Algorithms.getFileNameWithoutExtension(new File(info.getFileName())); final String fnExt = Algorithms.getFileNameWithoutExtension(new File(info.getFileName()));
new AsyncTask<Object, Object, IncrementalChangesManager.IncrementalUpdateList>() { new PerformLiveUpdateAsyncTask(getMyActivity()).execute(new String[]{fnExt});
protected void onPreExecute() {
getMyActivity().setSupportProgressBarIndeterminateVisibility(true);
}
@Override
protected IncrementalChangesManager.IncrementalUpdateList doInBackground(Object... params) {
final OsmandApplication myApplication = getMyActivity().getMyApplication();
IncrementalChangesManager cm = myApplication.getResourceManager().getChangesManager();
return cm.getUpdatesByMonth(fnExt);
}
protected void onPostExecute(IncrementalChangesManager.IncrementalUpdateList result) {
getMyActivity().setSupportProgressBarIndeterminateVisibility(false);
if (result.errorMessage != null) {
Toast.makeText(getActivity(), result.errorMessage, Toast.LENGTH_SHORT).show();
} else {
List<IncrementalChangesManager.IncrementalUpdate> ll = result.getItemsForUpdate();
if (ll.isEmpty()) {
Toast.makeText(getActivity(), R.string.no_updates_available, Toast.LENGTH_SHORT).show();
} else {
int i = 0;
IndexItem[] is = new IndexItem[ll.size()];
for (IncrementalChangesManager.IncrementalUpdate iu : ll) {
IndexItem ii = new IndexItem(iu.fileName, "Incremental update", iu.timestamp, iu.sizeText,
iu.contentSize, iu.containerSize, DownloadActivityType.LIVE_UPDATES_FILE);
is[i++] = ii;
}
getMyActivity().startDownload(is);
}
}
}
}.execute(new Object[]{fnExt});
} }
LocalIndexInfo getLocalIndexInfo(int groupPosition, int childPosition) { LocalIndexInfo getLocalIndexInfo(int groupPosition, int childPosition) {
@ -330,7 +300,7 @@ public class LiveUpdatesFragment extends Fragment {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
final FragmentManager fragmentManager = fragment.getChildFragmentManager(); final FragmentManager fragmentManager = fragment.getChildFragmentManager();
SettingsDialogFragment.createInstance(item).show(fragmentManager, "settings"); LiveUpdatesSettingsDialogFragment.createInstance(item).show(fragmentManager, "settings");
} }
}); });
} }
@ -378,4 +348,46 @@ public class LiveUpdatesFragment extends Fragment {
adapter.sort(); adapter.sort();
} }
} }
public static class PerformLiveUpdateAsyncTask
extends AsyncTask<String, Object, IncrementalChangesManager.IncrementalUpdateList> {
private final AbstractDownloadActivity activity;
public PerformLiveUpdateAsyncTask(AbstractDownloadActivity activity) {
this.activity = activity;
}
protected void onPreExecute() {
activity.setSupportProgressBarIndeterminateVisibility(true);
}
@Override
protected IncrementalChangesManager.IncrementalUpdateList doInBackground(String... params) {
final OsmandApplication myApplication = activity.getMyApplication();
IncrementalChangesManager cm = myApplication.getResourceManager().getChangesManager();
return cm.getUpdatesByMonth(params[0]);
}
protected void onPostExecute(IncrementalChangesManager.IncrementalUpdateList result) {
activity.setSupportProgressBarIndeterminateVisibility(false);
if (result.errorMessage != null) {
Toast.makeText(activity, result.errorMessage, Toast.LENGTH_SHORT).show();
} else {
List<IncrementalChangesManager.IncrementalUpdate> ll = result.getItemsForUpdate();
if (ll.isEmpty()) {
Toast.makeText(activity, R.string.no_updates_available, Toast.LENGTH_SHORT).show();
} else {
int i = 0;
IndexItem[] is = new IndexItem[ll.size()];
for (IncrementalChangesManager.IncrementalUpdate iu : ll) {
IndexItem ii = new IndexItem(iu.fileName, "Incremental update", iu.timestamp, iu.sizeText,
iu.contentSize, iu.containerSize, DownloadActivityType.LIVE_UPDATES_FILE);
is[i++] = ii;
}
activity.startDownload(is);
}
}
}
}
} }

View file

@ -21,13 +21,23 @@ import net.osmand.plus.OsmandSettings;
import net.osmand.plus.R; import net.osmand.plus.R;
import net.osmand.plus.activities.LocalIndexInfo; import net.osmand.plus.activities.LocalIndexInfo;
import net.osmand.plus.activities.OsmandActionBarActivity; import net.osmand.plus.activities.OsmandActionBarActivity;
import net.osmand.util.Algorithms;
public class SettingsDialogFragment extends DialogFragment { import java.io.File;
public static final String LOCAL_INDEX = "local_index"; import java.util.Calendar;
public static final int UPDATE_HOURLY = 0;
public static final int UPDATE_DAILY = 1; public class LiveUpdatesSettingsDialogFragment extends DialogFragment {
public static final int UPDATE_WEEKLY = 2; public static final String LOCAL_INDEX_INFO = "local_index_info";
public static final String UPDATE_TIMES = "_update_times";
private static final String LOCAL_INDEX = "local_index";
private static final int UPDATE_HOURLY = 0;
private static final int UPDATE_DAILY = 1;
private static final int UPDATE_WEEKLY = 2;
private static final String UPDATE_TIMES = "_update_times";
private static final String TIME_OF_DAY_TO_UPDATE = "_time_of_day_to_update";
private static final int MORNING_UPDATE_TIME = 8;
private static final int NIGHT_UPDATE_TIME = 21;
private static final int SHIFT = 1000;
@NonNull @NonNull
@Override @Override
@ -43,8 +53,10 @@ public class SettingsDialogFragment extends DialogFragment {
final OsmandSettings.CommonPreference<Boolean> liveUpdatePreference = final OsmandSettings.CommonPreference<Boolean> liveUpdatePreference =
preferenceForLocalIndex(localIndexInfo); preferenceForLocalIndex(localIndexInfo);
final OsmandSettings.CommonPreference<Integer> updateFrequencies = final OsmandSettings.CommonPreference<Integer> updateFrequencePreference =
preferenceUpdateTimes(localIndexInfo); preferenceUpdateTimes(localIndexInfo);
final OsmandSettings.CommonPreference<Integer> timeOfDayPreference =
preferenceTimeOfDayToUpdate(localIndexInfo);
liveUpdatesSwitch.setChecked(liveUpdatePreference.get()); liveUpdatesSwitch.setChecked(liveUpdatePreference.get());
builder.setView(view) builder.setView(view)
@ -52,25 +64,47 @@ public class SettingsDialogFragment extends DialogFragment {
@Override @Override
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
final int updateFrequencyInt = updateFrequencySpinner.getSelectedItemPosition(); final int updateFrequencyInt = updateFrequencySpinner.getSelectedItemPosition();
updateFrequencies.set(updateFrequencyInt); updateFrequencePreference.set(updateFrequencyInt);
UpdateFrequencies updateFrequency = UpdateFrequencies.values()[updateFrequencyInt];
AlarmManager alarmMgr = (AlarmManager) getActivity() AlarmManager alarmMgr = (AlarmManager) getActivity()
.getSystemService(Context.ALARM_SERVICE); .getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getActivity(), LiveUpdatesAlarmReceiver.class); Intent intent = new Intent(getActivity(), LiveUpdatesAlarmReceiver.class);
final File file = new File(localIndexInfo.getFileName());
final String fileName = Algorithms.getFileNameWithoutExtension(file);
// intent.putExtra(LOCAL_INDEX_INFO, fileName);
intent.setAction(fileName);
PendingIntent alarmIntent = PendingIntent.getBroadcast(getActivity(), 0, intent, 0); PendingIntent alarmIntent = PendingIntent.getBroadcast(getActivity(), 0, intent, 0);
UpdateFrequencies updateFrequency = UpdateFrequencies.values()[updateFrequencyInt]; final int timeOfDayInt = updateTimesOfDaySpinner.getSelectedItemPosition();
timeOfDayPreference.set(timeOfDayInt);
TimesOfDay timeOfDayToUpdate = TimesOfDay.values()[timeOfDayInt];
long timeOfFirstUpdate;
long updateInterval;
switch (updateFrequency) { switch (updateFrequency) {
case HOURLY: case HOURLY:
alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, timeOfFirstUpdate = System.currentTimeMillis() + SHIFT;
1000, 60 * 60 * 1000, alarmIntent); updateInterval = AlarmManager.INTERVAL_HOUR;
break; break;
case DAILY: case DAILY:
case WEEKLY: timeOfFirstUpdate = getNextUpdateTime(timeOfDayToUpdate);
updateTimesOfDaySpinner.setVisibility(View.VISIBLE); updateInterval = AlarmManager.INTERVAL_DAY;
break; break;
case WEEKLY:
timeOfFirstUpdate = getNextUpdateTime(timeOfDayToUpdate);
updateInterval = AlarmManager.INTERVAL_DAY * 7;
break;
default:
throw new IllegalStateException("Unexpected update frequency:"
+ updateFrequency);
} }
liveUpdatePreference.set(liveUpdatesSwitch.isChecked()); liveUpdatePreference.set(liveUpdatesSwitch.isChecked());
alarmMgr.cancel(alarmIntent);
if (liveUpdatesSwitch.isChecked()) {
alarmMgr.setInexactRepeating(AlarmManager.RTC,
timeOfFirstUpdate, updateInterval, alarmIntent);
}
getLiveUpdatesFragment().notifyLiveUpdatesChanged(); getLiveUpdatesFragment().notifyLiveUpdatesChanged();
} }
}) })
@ -82,7 +116,7 @@ public class SettingsDialogFragment extends DialogFragment {
} }
}); });
updateFrequencySpinner.setSelection(updateFrequencies.get()); updateFrequencySpinner.setSelection(updateFrequencePreference.get());
updateFrequencySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { updateFrequencySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override @Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
@ -107,6 +141,18 @@ public class SettingsDialogFragment extends DialogFragment {
return builder.create(); return builder.create();
} }
private long getNextUpdateTime(TimesOfDay timeOfDayToUpdate) {
Calendar calendar = Calendar.getInstance();
if (timeOfDayToUpdate == TimesOfDay.MORNING) {
calendar.add(Calendar.DATE, 1);
calendar.set(Calendar.HOUR_OF_DAY, MORNING_UPDATE_TIME);
} else if (timeOfDayToUpdate == TimesOfDay.NIGHT) {
calendar.add(Calendar.DATE, 1);
calendar.set(Calendar.HOUR_OF_DAY, NIGHT_UPDATE_TIME);
}
return calendar.getTimeInMillis();
}
private LiveUpdatesFragment getLiveUpdatesFragment() { private LiveUpdatesFragment getLiveUpdatesFragment() {
return (LiveUpdatesFragment) getParentFragment(); return (LiveUpdatesFragment) getParentFragment();
} }
@ -121,6 +167,11 @@ public class SettingsDialogFragment extends DialogFragment {
return getSettings().registerIntPreference(settingId, UpdateFrequencies.HOURLY.ordinal()); return getSettings().registerIntPreference(settingId, UpdateFrequencies.HOURLY.ordinal());
} }
private OsmandSettings.CommonPreference<Integer> preferenceTimeOfDayToUpdate(LocalIndexInfo item) {
final String settingId = item.getFileName() + TIME_OF_DAY_TO_UPDATE;
return getSettings().registerIntPreference(settingId, TimesOfDay.NIGHT.ordinal());
}
private OsmandSettings getSettings() { private OsmandSettings getSettings() {
return getMyApplication().getSettings(); return getMyApplication().getSettings();
} }
@ -129,8 +180,8 @@ public class SettingsDialogFragment extends DialogFragment {
return ((OsmandActionBarActivity) this.getActivity()).getMyApplication(); return ((OsmandActionBarActivity) this.getActivity()).getMyApplication();
} }
public static SettingsDialogFragment createInstance(LocalIndexInfo localIndexInfo) { public static LiveUpdatesSettingsDialogFragment createInstance(LocalIndexInfo localIndexInfo) {
SettingsDialogFragment fragment = new SettingsDialogFragment(); LiveUpdatesSettingsDialogFragment fragment = new LiveUpdatesSettingsDialogFragment();
Bundle args = new Bundle(); Bundle args = new Bundle();
args.putParcelable(LOCAL_INDEX, localIndexInfo); args.putParcelable(LOCAL_INDEX, localIndexInfo);
fragment.setArguments(args); fragment.setArguments(args);