From 1a20301cbdf06c0e737ef9d3ce2607179a7f00eb Mon Sep 17 00:00:00 2001 From: Dmitry Yunitsky Date: Tue, 11 Aug 2015 17:48:09 +0300 Subject: [android] Refactoring and fixes. --- .../mapswithme/maps/DownloadResourcesActivity.java | 537 ++++---- .../src/com/mapswithme/maps/IntentProcessor.java | 4 +- android/src/com/mapswithme/maps/MWMActivity.java | 1420 -------------------- .../src/com/mapswithme/maps/MWMApplication.java | 346 ----- android/src/com/mapswithme/maps/MwmActivity.java | 1417 +++++++++++++++++++ .../src/com/mapswithme/maps/MwmApplication.java | 346 +++++ .../src/com/mapswithme/maps/ads/LikesManager.java | 14 +- .../maps/ads/RateStoreDialogFragment.java | 4 +- .../com/mapswithme/maps/background/Notifier.java | 37 +- .../maps/base/BaseMwmFragmentActivity.java | 4 +- .../maps/bookmarks/BookmarksListFragment.java | 4 +- .../maps/location/AndroidNativeProvider.java | 4 +- .../maps/location/GoogleFusedLocationProvider.java | 4 +- .../mapswithme/maps/location/LocationHelper.java | 6 +- .../maps/routing/RoutingResultCodesProcessor.java | 4 +- .../com/mapswithme/maps/search/SearchFragment.java | 4 +- .../maps/search/SearchToolbarController.java | 6 +- .../mapswithme/maps/settings/SettingsActivity.java | 10 +- .../maps/settings/StoragePathManager.java | 14 +- .../src/com/mapswithme/maps/sound/TtsPlayer.java | 4 +- .../com/mapswithme/maps/widget/RoutingLayout.java | 6 +- .../BasePlacePageAnimationController.java | 4 +- 22 files changed, 2076 insertions(+), 2123 deletions(-) delete mode 100644 android/src/com/mapswithme/maps/MWMActivity.java delete mode 100644 android/src/com/mapswithme/maps/MWMApplication.java create mode 100644 android/src/com/mapswithme/maps/MwmActivity.java create mode 100644 android/src/com/mapswithme/maps/MwmApplication.java (limited to 'android/src/com/mapswithme/maps') diff --git a/android/src/com/mapswithme/maps/DownloadResourcesActivity.java b/android/src/com/mapswithme/maps/DownloadResourcesActivity.java index ecef34327f..54653eece4 100644 --- a/android/src/com/mapswithme/maps/DownloadResourcesActivity.java +++ b/android/src/com/mapswithme/maps/DownloadResourcesActivity.java @@ -16,22 +16,22 @@ import android.widget.TextView; import android.widget.Toast; import com.mapswithme.country.StorageOptions; -import com.mapswithme.maps.MWMActivity.MapTask; -import com.mapswithme.maps.MWMActivity.OpenUrlTask; import com.mapswithme.maps.MapStorage.Index; +import com.mapswithme.maps.MwmActivity.MapTask; +import com.mapswithme.maps.MwmActivity.OpenUrlTask; import com.mapswithme.maps.api.Const; import com.mapswithme.maps.api.ParsedMwmRequest; import com.mapswithme.maps.base.BaseMwmFragmentActivity; import com.mapswithme.maps.location.LocationHelper; import com.mapswithme.util.ConnectionState; import com.mapswithme.util.Constants; +import com.mapswithme.util.UiUtils; import com.mapswithme.util.Utils; import com.mapswithme.util.Yota; import com.mapswithme.util.statistics.Statistics; import java.io.File; import java.io.FileOutputStream; -import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -50,16 +50,14 @@ public class DownloadResourcesActivity extends BaseMwmFragmentActivity private static final int ERR_NO_MORE_FILES = -5; private static final int ERR_FILE_IN_PROGRESS = -6; - private MWMApplication mApplication = null; - private MapStorage mMapStorage = null; - private int mSlotId = 0; - private TextView mMsgView = null; - private TextView mLocationMsgView = null; - private ProgressBar mProgress = null; - private Button mButton = null; - private CheckBox mDownloadCountryCheckBox = null; - private Index mCountryIndex = null; + private TextView mTvMessage; + private TextView mTvLocation; + private ProgressBar mProgress; + private Button mBtnDownload; + private CheckBox mChbDownloadCountry; + private int mStorageSlotId; + private Index mCountryIndex; private MapTask mMapTaskToForward; private static final int DOWNLOAD = 0; @@ -69,8 +67,8 @@ public class DownloadResourcesActivity extends BaseMwmFragmentActivity private static final int PROCEED_TO_MAP = 4; private static final int BTN_COUNT = 5; - private View.OnClickListener mBtnListeners[] = null; - private String mBtnNames[] = null; + private View.OnClickListener mBtnListeners[]; + private String mBtnNames[]; private final IntentProcessor[] mIntentProcessors = { new GeoIntentProcessor(), @@ -83,18 +81,174 @@ public class DownloadResourcesActivity extends BaseMwmFragmentActivity }; public static final String EXTRA_COUNTRY_INDEX = ".extra.index"; - public static final String EXTRA_AUTODOWNLOAD_CONTRY = ".extra.autodownload"; + public static final String EXTRA_AUTODOWNLOAD_COUNTRY = ".extra.autodownload"; public static final String EXTRA_UPDATE_COUNTRIES = ".extra.update.countries"; + @Override + protected void onCreate(Bundle savedInstanceState) + { + super.onCreate(savedInstanceState); + + Utils.keepScreenOn(true, getWindow()); + suggestRemoveLiteOrSamsung(); + + final boolean dispatched = dispatchIntent(); + if (!dispatched) + parseIntentForKmzFile(); + + setContentView(R.layout.activity_download_resources); + initViewsAndListeners(); + mStorageSlotId = MapStorage.INSTANCE.subscribe(this); + + if (prepareFilesDownload()) + { + setAction(DOWNLOAD); + + if (ConnectionState.isWifiConnected()) + onDownloadClicked(mBtnDownload); + } + } + + @Override + protected void onResume() + { + super.onResume(); + + LocationHelper.INSTANCE.addLocationListener(this); + } + + @Override + protected void onPause() + { + super.onPause(); + + LocationHelper.INSTANCE.removeLocationListener(this); + } + + @Override + protected void onDestroy() + { + super.onDestroy(); + + mProgress = null; + MapStorage.INSTANCE.unsubscribe(mStorageSlotId); + } + + // TODO change communication with native thread so that it does not send us callbacks after activity destroy + @SuppressWarnings("unused") + public void onDownloadProgress(int currentTotal, int currentProgress, int globalTotal, int globalProgress) + { + if (mProgress != null) + mProgress.setProgress(globalProgress); + } + + // TODO change communication with native thread so that it does not send us callbacks after activity destroy + @SuppressWarnings("unused") + public void onDownloadFinished(int errorCode) + { + if (errorCode == ERR_DOWNLOAD_SUCCESS) + { + final int res = startNextFileDownload(this); + if (res == ERR_NO_MORE_FILES) + finishFilesDownload(res); + } + else + finishFilesDownload(errorCode); + } + + @Override + public void onLocationUpdated(final Location l) + { + if (mCountryIndex != null) + return; + + final double lat = l.getLatitude(); + final double lon = l.getLongitude(); + Log.i(TAG, "Searching for country name at location lat=" + lat + ", lon=" + lon); + + mCountryIndex = Framework.nativeGetCountryIndex(lat, lon); + if (mCountryIndex == null) + return; + + UiUtils.show(mTvLocation); + + final int countryStatus = MapStorage.INSTANCE.countryStatus(mCountryIndex); + final String name = MapStorage.INSTANCE.countryName(mCountryIndex); + + if (countryStatus == MapStorage.ON_DISK) + mTvLocation.setText(String.format(getString(R.string.download_location_map_up_to_date), name)); + else + { + final CheckBox checkBox = (CheckBox) findViewById(R.id.chb__download_country); + UiUtils.show(checkBox); + + String locationText; + String checkBoxText; + + if (countryStatus == MapStorage.ON_DISK_OUT_OF_DATE) + { + locationText = getString(R.string.download_location_update_map_proposal); + checkBoxText = String.format(getString(R.string.update_country_ask), name); + } + else + { + locationText = getString(R.string.download_location_map_proposal); + checkBoxText = String.format(getString(R.string.download_country_ask), name); + } + + mTvLocation.setText(locationText); + checkBox.setText(checkBoxText); + } + + LocationHelper.INSTANCE.removeLocationListener(this); + } + + @Override + public void onCompassUpdated(long time, double magneticNorth, double trueNorth, double accuracy) {} + + @Override + public void onLocationError(int errorCode) {} + + + @Override + public void onCountryStatusChanged(MapStorage.Index idx) + { + final int status = MapStorage.INSTANCE.countryStatus(idx); + + if (status == MapStorage.ON_DISK) + showMap(); + } + + @Override + public void onCountryProgress(MapStorage.Index idx, long current, long total) + { + // Important check - activity can be destroyed + // but notifications from downloading thread are coming. + if (mProgress != null) + mProgress.setProgress((int) current); + } + + private Intent getPackageIntent(String s) + { + return getPackageManager().getLaunchIntentForPackage(s); + } + + private void suggestRemoveLiteOrSamsung() + { + if (!Yota.isFirstYota() && + (Utils.isPackageInstalled(Constants.Package.MWM_LITE_PACKAGE) || Utils.isPackageInstalled(Constants.Package.MWM_SAMSUNG_PACKAGE))) + Toast.makeText(this, R.string.suggest_uninstall_lite, Toast.LENGTH_LONG).show(); + } + private void setDownloadMessage(int bytesToDownload) { Log.d(TAG, "prepareFilesDownload, bytesToDownload:" + bytesToDownload); if (bytesToDownload < Constants.MB) - mMsgView.setText(String.format(getString(R.string.download_resources), + mTvMessage.setText(String.format(getString(R.string.download_resources), (float) bytesToDownload / Constants.KB, getString(R.string.kb))); else - mMsgView.setText(String.format(getString(R.string.download_resources), + mTvMessage.setText(String.format(getString(R.string.download_resources), (float) bytesToDownload / Constants.MB, getString(R.string.mb))); } @@ -103,17 +257,12 @@ public class DownloadResourcesActivity extends BaseMwmFragmentActivity { final int bytes = getBytesToDownload(); - // Show map if no any downloading needed. if (bytes == 0) { - showMapView(); + showMap(); return false; } - // Do initialization once. - if (mMapStorage == null) - initDownloading(); - if (bytes > 0) { setDownloadMessage(bytes); @@ -122,26 +271,19 @@ public class DownloadResourcesActivity extends BaseMwmFragmentActivity mProgress.setProgress(0); } else - { finishFilesDownload(bytes); - } return true; } - private void initDownloading() + private void initViewsAndListeners() { - // Get GUI elements and subscribe to map storage (for country downloading). - mMapStorage = MapStorage.INSTANCE; - mSlotId = mMapStorage.subscribe(this); - - mMsgView = (TextView) findViewById(R.id.download_resources_message); - mProgress = (ProgressBar) findViewById(R.id.download_resources_progress); - mButton = (Button) findViewById(R.id.download_resources_button); - mDownloadCountryCheckBox = (CheckBox) findViewById(R.id.download_country_checkbox); - mLocationMsgView = (TextView) findViewById(R.id.download_resources_location_message); + mTvMessage = (TextView) findViewById(R.id.tv__download_message); + mProgress = (ProgressBar) findViewById(R.id.pb__download_resources); + mBtnDownload = (Button) findViewById(R.id.btn__download_resources); + mChbDownloadCountry = (CheckBox) findViewById(R.id.chb__download_country); + mTvLocation = (TextView) findViewById(R.id.tv__location); - // Initialize button states. mBtnListeners = new View.OnClickListener[BTN_COUNT]; mBtnNames = new String[BTN_COUNT]; @@ -179,15 +321,12 @@ public class DownloadResourcesActivity extends BaseMwmFragmentActivity public void onClick(View v) { onProceedToMapClicked(v); } }; mBtnNames[PROCEED_TO_MAP] = getString(R.string.download_resources_continue); - - // Start listening the location. - LocationHelper.INSTANCE.addLocationListener(this); } private void setAction(int action) { - mButton.setOnClickListener(mBtnListeners[action]); - mButton.setText(mBtnNames[action]); + mBtnDownload.setOnClickListener(mBtnListeners[action]); + mBtnDownload.setText(mBtnNames[action]); } private void doDownload() @@ -196,7 +335,7 @@ public class DownloadResourcesActivity extends BaseMwmFragmentActivity finishFilesDownload(ERR_NO_MORE_FILES); } - public void onDownloadClicked(View v) + private void onDownloadClicked(View v) { setAction(PAUSE); doDownload(); @@ -216,7 +355,6 @@ public class DownloadResourcesActivity extends BaseMwmFragmentActivity private void onTryAgainClicked(View v) { - // Initialize downloading from the beginning. if (prepareFilesDownload()) { setAction(PAUSE); @@ -226,7 +364,7 @@ public class DownloadResourcesActivity extends BaseMwmFragmentActivity private void onProceedToMapClicked(View v) { - showMapView(); + showMap(); } public String getErrorMessage(int res) @@ -255,39 +393,36 @@ public class DownloadResourcesActivity extends BaseMwmFragmentActivity return getString(id); } - public void showMapView() + private void showMap() { - // Continue with Main UI initialization (MWMActivity) - final Intent mwmActivityIntent = new Intent(this, MWMActivity.class); + final Intent intent = new Intent(this, MwmActivity.class); - // Disable animation because MWMActivity should appear exactly over this one - // Intent.FLAG_ACTIVITY_REORDER_TO_FRONT - mwmActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION | Intent.FLAG_ACTIVITY_CLEAR_TOP); + // Disable animation because MwmActivity should appear exactly over this one + intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION | Intent.FLAG_ACTIVITY_CLEAR_TOP); // Add saved task to forward to map activity. if (mMapTaskToForward != null) { - mwmActivityIntent.putExtra(MWMActivity.EXTRA_TASK, mMapTaskToForward); + intent.putExtra(MwmActivity.EXTRA_TASK, mMapTaskToForward); mMapTaskToForward = null; } - startActivity(mwmActivityIntent); + startActivity(intent); finish(); } - public void finishFilesDownload(int result) + private void finishFilesDownload(int result) { if (result == ERR_NO_MORE_FILES) { - if (mCountryIndex != null && mDownloadCountryCheckBox.isChecked()) + if (mCountryIndex != null && mChbDownloadCountry.isChecked()) { - mDownloadCountryCheckBox.setVisibility(View.GONE); - mLocationMsgView.setVisibility(View.GONE); - mMsgView.setText(String.format(getString(R.string.downloading_country_can_proceed), - mMapStorage.countryName(mCountryIndex))); + UiUtils.hide(mChbDownloadCountry, mTvLocation); + mTvMessage.setText(String.format(getString(R.string.downloading_country_can_proceed), + MapStorage.INSTANCE.countryName(mCountryIndex))); - mProgress.setMax((int) mMapStorage.countryRemoteSizeInBytes(mCountryIndex, StorageOptions.MAP_OPTION_MAP_ONLY)); + mProgress.setMax((int) MapStorage.INSTANCE.countryRemoteSizeInBytes(mCountryIndex, StorageOptions.MAP_OPTION_MAP_ONLY)); mProgress.setProgress(0); Framework.downloadCountry(mCountryIndex); @@ -295,78 +430,17 @@ public class DownloadResourcesActivity extends BaseMwmFragmentActivity setAction(PROCEED_TO_MAP); } else - showMapView(); + showMap(); } else { - mMsgView.setText(getErrorMessage(result)); - mMsgView.setTextColor(Color.RED); + mTvMessage.setText(getErrorMessage(result)); + mTvMessage.setTextColor(Color.RED); setAction(TRY_AGAIN); } } - @Override - public void onCountryStatusChanged(MapStorage.Index idx) - { - final int status = mMapStorage.countryStatus(idx); - - if (status == MapStorage.ON_DISK) - showMapView(); - } - - @Override - public void onCountryProgress(MapStorage.Index idx, long current, long total) - { - // Important check - activity can be destroyed - // but notifications from downloading thread are coming. - if (mProgress != null) - mProgress.setProgress((int) current); - } - - private Intent getPackageIntent(String s) - { - return getPackageManager().getLaunchIntentForPackage(s); - } - - private boolean checkLiteProPackages() - { - if (!Yota.isFirstYota() && - (getPackageIntent(Constants.Package.MWM_LITE_PACKAGE) != null || - getPackageIntent(Constants.Package.MWM_SAMSUNG_PACKAGE) != null)) - Toast.makeText(this, R.string.suggest_uninstall_lite, Toast.LENGTH_LONG).show(); - - return false; - } - - @Override - protected void onCreate(Bundle savedInstanceState) - { - super.onCreate(savedInstanceState); - - // Do not turn off the screen while downloading needed resources - getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); - - mApplication = (MWMApplication) getApplication(); - - if (checkLiteProPackages()) - return; - - final boolean dispatched = dispatchIntent(); - if (!dispatched) - parseIntentForKMZFile(); - - setContentView(R.layout.download_resources); - - if (prepareFilesDownload()) - { - setAction(DOWNLOAD); - - if (ConnectionState.isWifiConnected()) - onDownloadClicked(mButton); - } - } - private boolean dispatchIntent() { final Intent intent = getIntent(); @@ -400,180 +474,71 @@ public class DownloadResourcesActivity extends BaseMwmFragmentActivity return null; } - private void parseIntentForKMZFile() + private void parseIntentForKmzFile() { final Intent intent = getIntent(); - if (intent != null) + if (intent == null) + return; + + final Uri data = intent.getData(); + if (data == null) + return; + + String path = null; + File tmpFile = null; + final String scheme = data.getScheme(); + if (scheme != null && !scheme.equalsIgnoreCase(Constants.Url.DATA_SCHEME_FILE)) { - final Uri data = intent.getData(); - if (data != null) + // scheme is "content" or "http" - need to download file first + InputStream input = null; + OutputStream output = null; + + try { - String path = null; - File tmpFile = null; - final String scheme = data.getScheme(); - if (scheme != null && !scheme.equalsIgnoreCase(Constants.Url.DATA_SCHEME_FILE)) + final ContentResolver resolver = getContentResolver(); + final String ext = getExtensionFromMime(resolver.getType(data)); + if (ext != null) { - // scheme is "content" or "http" - need to download file first - InputStream input = null; - OutputStream output = null; - - try - { - final ContentResolver resolver = getContentResolver(); - final String ext = getExtensionFromMime(resolver.getType(data)); - if (ext != null) - { - final String filePath = mApplication.getTempPath() + "Attachment" + ext; - - tmpFile = new File(filePath); - output = new FileOutputStream(tmpFile); - input = resolver.openInputStream(data); - - final byte buffer[] = new byte[Constants.MB / 2]; - int read; - while ((read = input.read(buffer)) != -1) - output.write(buffer, 0, read); - output.flush(); - - path = filePath; - } - } catch (final Exception ex) - { - Log.w(TAG, "Attachment not found or io error: " + ex); - } finally - { - try - { - if (input != null) - input.close(); - if (output != null) - output.close(); - } catch (final IOException ex) - { - Log.w(TAG, "Close stream error: " + ex); - } - } - } - else - path = data.getPath(); + final String filePath = MwmApplication.get().getTempPath() + "Attachment" + ext; - boolean success = false; - if (path != null) - { - Log.d(TAG, "Loading bookmarks file from: " + path); - success = loadKMZFile(path); - } - else - Log.w(TAG, "Can't get bookmarks file from URI: " + data); + tmpFile = new File(filePath); + output = new FileOutputStream(tmpFile); + input = resolver.openInputStream(data); - if (tmpFile != null) - tmpFile.delete(); + final byte buffer[] = new byte[Constants.MB / 2]; + int read; + while ((read = input.read(buffer)) != -1) + output.write(buffer, 0, read); + output.flush(); - Utils.toastShortcut(this, success ? R.string.load_kmz_successful : R.string.load_kmz_failed); + path = filePath; + } + } catch (final Exception ex) + { + Log.w(TAG, "Attachment not found or io error: " + ex); + } finally + { + Utils.closeStream(input); + Utils.closeStream(output); } } - } - - @Override - protected void onDestroy() - { - super.onDestroy(); - - LocationHelper.INSTANCE.removeLocationListener(this); - - if (mMapStorage != null) - mMapStorage.unsubscribe(mSlotId); - } - - @Override - protected void onPause() - { - super.onPause(); - - LocationHelper.INSTANCE.removeLocationListener(this); - } - - @Override - protected void onResume() - { - super.onResume(); - - LocationHelper.INSTANCE.addLocationListener(this); - } - - public void onDownloadProgress(int currentTotal, int currentProgress, int globalTotal, int globalProgress) - { - if (mProgress != null) - mProgress.setProgress(globalProgress); - } - - public void onDownloadFinished(int errorCode) - { - if (errorCode == ERR_DOWNLOAD_SUCCESS) - { - final int res = startNextFileDownload(this); - if (res == ERR_NO_MORE_FILES) - finishFilesDownload(res); - } else - finishFilesDownload(errorCode); - } + path = data.getPath(); - @Override - public void onLocationUpdated(final Location l) - { - if (mCountryIndex == null) + boolean success = false; + if (path != null) { - final double lat = l.getLatitude(); - final double lon = l.getLongitude(); - Log.i(TAG, "Searching for country name at location lat=" + lat + ", lon=" + lon); - - mCountryIndex = Framework.nativeGetCountryIndex(lat, lon); - if (mCountryIndex != null) - { - mLocationMsgView.setVisibility(View.VISIBLE); - - final int countryStatus = mMapStorage.countryStatus(mCountryIndex); - final String name = mMapStorage.countryName(mCountryIndex); - - if (countryStatus == MapStorage.ON_DISK) - mLocationMsgView.setText(String.format(getString(R.string.download_location_map_up_to_date), name)); - else - { - final CheckBox checkBox = (CheckBox) findViewById(R.id.download_country_checkbox); - checkBox.setVisibility(View.VISIBLE); - - String msgViewText; - String checkBoxText; - - if (countryStatus == MapStorage.ON_DISK_OUT_OF_DATE) - { - msgViewText = getString(R.string.download_location_update_map_proposal); - checkBoxText = String.format(getString(R.string.update_country_ask), name); - } - else - { - msgViewText = getString(R.string.download_location_map_proposal); - checkBoxText = String.format(getString(R.string.download_country_ask), name); - } - - mLocationMsgView.setText(msgViewText); - checkBox.setText(checkBoxText); - } - - LocationHelper.INSTANCE.removeLocationListener(this); - } + Log.d(TAG, "Loading bookmarks file from: " + path); + success = loadKmzFile(path); } - } + else + Log.w(TAG, "Can't get bookmarks file from URI: " + data); - @Override - public void onCompassUpdated(long time, double magneticNorth, double trueNorth, double accuracy) - { - } + if (tmpFile != null) + //noinspection ResultOfMethodCallIgnored + tmpFile.delete(); - @Override - public void onLocationError(int errorCode) - { + Utils.toastShortcut(this, success ? R.string.load_kmz_successful : R.string.load_kmz_failed); } private class GeoIntentProcessor implements IntentProcessor @@ -666,7 +631,7 @@ public class DownloadResourcesActivity extends BaseMwmFragmentActivity ParsedMwmRequest.setCurrentRequest(request); Statistics.INSTANCE.trackApiCall(request); - if (!request.isPickPointMode()) + if (!ParsedMwmRequest.isPickPointMode()) mMapTaskToForward = new OpenUrlTask(apiUrl); return true; } @@ -707,10 +672,10 @@ public class DownloadResourcesActivity extends BaseMwmFragmentActivity public boolean processIntent(Intent intent) { final Index index = (Index) intent.getSerializableExtra(EXTRA_COUNTRY_INDEX); - final boolean autoDownload = intent.getBooleanExtra(EXTRA_AUTODOWNLOAD_CONTRY, false); + final boolean autoDownload = intent.getBooleanExtra(EXTRA_AUTODOWNLOAD_COUNTRY, false); if (autoDownload) Statistics.INSTANCE.trackDownloadCountryNotificationClicked(); - mMapTaskToForward = new MWMActivity.ShowCountryTask(index, autoDownload); + mMapTaskToForward = new MwmActivity.ShowCountryTask(index, autoDownload); org.alohalytics.Statistics.logEvent("OpenCountryTaskProcessor::processIntent", new String[]{"autoDownload", String.valueOf(autoDownload)}, LocationHelper.INSTANCE.getLastLocation()); return true; } @@ -728,7 +693,7 @@ public class DownloadResourcesActivity extends BaseMwmFragmentActivity public boolean processIntent(Intent intent) { org.alohalytics.Statistics.logEvent("UpdateCountryProcessor::processIntent"); - mMapTaskToForward = new MWMActivity.UpdateCountryTask(); + mMapTaskToForward = new MwmActivity.UpdateCountryTask(); return true; } } @@ -739,5 +704,5 @@ public class DownloadResourcesActivity extends BaseMwmFragmentActivity private native void cancelCurrentFile(); - private native boolean loadKMZFile(String path); + private native boolean loadKmzFile(String path); } diff --git a/android/src/com/mapswithme/maps/IntentProcessor.java b/android/src/com/mapswithme/maps/IntentProcessor.java index 5a490bde6d..b82c25fb7e 100644 --- a/android/src/com/mapswithme/maps/IntentProcessor.java +++ b/android/src/com/mapswithme/maps/IntentProcessor.java @@ -4,7 +4,7 @@ import android.content.Intent; public interface IntentProcessor { - public boolean isIntentSupported(Intent intent); + boolean isIntentSupported(Intent intent); - public boolean processIntent(Intent intent); + boolean processIntent(Intent intent); } diff --git a/android/src/com/mapswithme/maps/MWMActivity.java b/android/src/com/mapswithme/maps/MWMActivity.java deleted file mode 100644 index 0a530ce1a0..0000000000 --- a/android/src/com/mapswithme/maps/MWMActivity.java +++ /dev/null @@ -1,1420 +0,0 @@ -package com.mapswithme.maps; - -import android.app.Dialog; -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.content.res.Configuration; -import android.graphics.Point; -import android.location.Location; -import android.os.Build; -import android.os.Bundle; -import android.os.Environment; -import android.os.Handler; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.support.v4.app.Fragment; -import android.support.v4.app.FragmentManager; -import android.support.v4.app.FragmentTransaction; -import android.support.v7.app.AlertDialog; -import android.util.Log; -import android.view.KeyEvent; -import android.view.MotionEvent; -import android.view.View; -import android.view.View.OnClickListener; -import android.view.ViewGroup; -import android.view.ViewTreeObserver; -import android.widget.ImageButton; -import android.widget.Toast; - -import com.mapswithme.country.ActiveCountryTree; -import com.mapswithme.country.DownloadActivity; -import com.mapswithme.country.DownloadFragment; -import com.mapswithme.country.StorageOptions; -import com.mapswithme.maps.Framework.OnBalloonListener; -import com.mapswithme.maps.MapStorage.Index; -import com.mapswithme.maps.activity.CustomNavigateUpListener; -import com.mapswithme.maps.ads.LikesManager; -import com.mapswithme.maps.api.ParsedMwmRequest; -import com.mapswithme.maps.base.BaseMwmFragmentActivity; -import com.mapswithme.maps.bookmarks.BookmarkCategoriesActivity; -import com.mapswithme.maps.bookmarks.ChooseBookmarkCategoryActivity; -import com.mapswithme.maps.bookmarks.data.Bookmark; -import com.mapswithme.maps.bookmarks.data.BookmarkManager; -import com.mapswithme.maps.bookmarks.data.MapObject; -import com.mapswithme.maps.bookmarks.data.MapObject.ApiPoint; -import com.mapswithme.maps.bookmarks.data.ParcelablePoint; -import com.mapswithme.maps.dialog.RoutingErrorDialogFragment; -import com.mapswithme.maps.location.LocationHelper; -import com.mapswithme.maps.location.LocationPredictor; -import com.mapswithme.maps.routing.RoutingInfo; -import com.mapswithme.maps.routing.RoutingResultCodesProcessor; -import com.mapswithme.maps.search.SearchActivity; -import com.mapswithme.maps.search.SearchFragment; -import com.mapswithme.maps.search.SearchToolbarController; -import com.mapswithme.maps.settings.SettingsActivity; -import com.mapswithme.maps.settings.StoragePathManager; -import com.mapswithme.maps.settings.StoragePathManager.MoveFilesListener; -import com.mapswithme.maps.settings.UnitLocale; -import com.mapswithme.maps.sound.TtsPlayer; -import com.mapswithme.maps.widget.BottomButtonsLayout; -import com.mapswithme.maps.widget.FadeView; -import com.mapswithme.maps.widget.RoutingLayout; -import com.mapswithme.maps.widget.placepage.BasePlacePageAnimationController; -import com.mapswithme.maps.widget.placepage.PlacePageView; -import com.mapswithme.maps.widget.placepage.PlacePageView.State; -import com.mapswithme.util.BottomSheetHelper; -import com.mapswithme.util.Constants; -import com.mapswithme.util.InputUtils; -import com.mapswithme.util.LocationUtils; -import com.mapswithme.util.UiUtils; -import com.mapswithme.util.Utils; -import com.mapswithme.util.Yota; -import com.mapswithme.util.sharing.ShareAction; -import com.mapswithme.util.sharing.SharingHelper; -import com.mapswithme.util.statistics.AlohaHelper; -import com.mapswithme.util.statistics.Statistics; - -import java.io.Serializable; -import java.util.Stack; - -public class MWMActivity extends BaseMwmFragmentActivity - implements LocationHelper.LocationListener, OnBalloonListener, View.OnTouchListener, BasePlacePageAnimationController.OnVisibilityChangedListener, - OnClickListener, Framework.RoutingListener, MapFragment.MapRenderingListener, CustomNavigateUpListener, Framework.RoutingProgressListener -{ - public static final String EXTRA_TASK = "map_task"; - private final static String TAG = "MWMActivity"; - private final static String EXTRA_CONSUMED = "mwm.extra.intent.processed"; - private final static String EXTRA_SCREENSHOTS_TASK = "screenshots_task"; - private final static String SCREENSHOTS_TASK_LOCATE = "locate_task"; - private final static String SCREENSHOTS_TASK_PPP = "show_place_page"; - private final static String EXTRA_LAT = "lat"; - private final static String EXTRA_LON = "lon"; - // Need it for change map style - private static final String EXTRA_SET_MAP_STYLE = "set_map_style"; - // Instance state - private static final String STATE_PP_OPENED = "PpOpened"; - private static final String STATE_MAP_OBJECT = "MapObject"; - private static final String STATE_BUTTONS_OPENED = "ButtonsOpened"; - - // Map tasks that we run AFTER rendering initialized - private final Stack mTasks = new Stack<>(); - private BroadcastReceiver mExternalStorageReceiver; - private final StoragePathManager mPathManager = new StoragePathManager(); - private AlertDialog mStorageDisconnectedDialog; - private ImageButton mBtnLocation; - // map - private MapFragment mMapFragment; - // Place page - private PlacePageView mPlacePage; - // Routing - private RoutingLayout mLayoutRouting; - - private boolean mNeedCheckUpdate = true; - private int mLocationStateModeListenerId = LocationState.SLOT_UNDEFINED; - // These flags are initialized to the invalid combination to force update on the first check - // after launching. - // These flags are static because the MWMActivity is recreated while screen orientation changing - // but they shall not be reinitialized on screen orientation changing. - private static boolean mStorageAvailable = false; - private static boolean mStorageWritable = true; - - private FadeView mFadeView; - - private ViewGroup mNavigationButtons; - private View mToolbarSearch; - private ImageButton mBtnZoomIn; - private ImageButton mBtnZoomOut; - private BottomButtonsLayout mBottomButtons; - - private static final String IS_KML_MOVED = "KmlBeenMoved"; - private static final String IS_KITKAT_MIGRATION_COMPLETED = "KitKatMigrationCompleted"; - - private boolean mIsFragmentContainer; - - private LocationPredictor mLocationPredictor; - private LikesManager mLikesManager; - private SearchToolbarController mSearchController; - - public static Intent createShowMapIntent(Context context, Index index, boolean doAutoDownload) - { - return new Intent(context, DownloadResourcesActivity.class) - .putExtra(DownloadResourcesActivity.EXTRA_COUNTRY_INDEX, index) - .putExtra(DownloadResourcesActivity.EXTRA_AUTODOWNLOAD_CONTRY, doAutoDownload); - } - - public static void setMapStyle(Context context, int mapStyle) - { - final Intent mapIntent = new Intent(context, MWMActivity.class); - mapIntent.putExtra(EXTRA_SET_MAP_STYLE, mapStyle); - context.startActivity(mapIntent); - // Next we need to handle intent - } - - public static void startSearch(Context context, String query) - { - final MWMActivity activity = (MWMActivity) context; - if (activity.mIsFragmentContainer) - activity.showSearch(); - else - SearchActivity.startWithQuery(context, query); - } - - public static Intent createUpdateMapsIntent() - { - return new Intent(MWMApplication.get(), DownloadResourcesActivity.class) - .putExtra(DownloadResourcesActivity.EXTRA_UPDATE_COUNTRIES, true); - } - - private void pauseLocation() - { - LocationHelper.INSTANCE.removeLocationListener(this); - // Enable automatic turning screen off while app is idle - Utils.keepScreenOn(false, getWindow()); - mLocationPredictor.pause(); - } - - private void listenLocationUpdates() - { - LocationHelper.INSTANCE.addLocationListener(this); - // Do not turn off the screen while displaying position - Utils.keepScreenOn(true, getWindow()); - mLocationPredictor.resume(); - } - - /** - * Invalidates location state in core. - * Updates location button accordingly. - */ - public void invalidateLocationState() - { - final int currentLocationMode = LocationState.INSTANCE.getLocationStateMode(); - refreshLocationState(currentLocationMode); - LocationState.INSTANCE.invalidatePosition(); - } - - private void checkUserMarkActivation() - { - final Intent intent = getIntent(); - if (intent != null && intent.hasExtra(EXTRA_SCREENSHOTS_TASK)) - { - final String value = intent.getStringExtra(EXTRA_SCREENSHOTS_TASK); - if (value.equals(SCREENSHOTS_TASK_PPP)) - { - final double lat = Double.parseDouble(intent.getStringExtra(EXTRA_LAT)); - final double lon = Double.parseDouble(intent.getStringExtra(EXTRA_LON)); - mFadeView.getHandler().postDelayed(new Runnable() - { - @Override - public void run() - { - Framework.nativeActivateUserMark(lat, lon); - } - }, 1000); - } - } - } - - @Override - public void onRenderingInitialized() - { - runOnUiThread(new Runnable() - { - @Override - public void run() - { - // Run all checks in main thread after rendering is initialized. - checkMeasurementSystem(); - checkUpdateMapsWithoutSearchIndex(); - checkKitkatMigrationMove(); - checkLiteMapsInPro(); - checkUserMarkActivation(); - } - }); - - runTasks(); - } - - private void runTasks() - { - // Task are not UI-thread bounded, - // if any task need UI-thread it should implicitly - // use Activity.runOnUiThread(). - while (!mTasks.isEmpty()) - mTasks.pop().run(this); - } - - private void checkMeasurementSystem() - { - UnitLocale.initializeCurrentUnits(); - } - - private void checkKitkatMigrationMove() - { - mPathManager.checkKitkatMigration(this); - } - - private void checkLiteMapsInPro() - { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && - (Utils.isPackageInstalled(Constants.Package.MWM_LITE_PACKAGE) || Utils.isPackageInstalled(Constants.Package.MWM_SAMSUNG_PACKAGE))) - { - if (!mPathManager.containsLiteMapsOnSdcard()) - return; - - mPathManager.moveMapsLiteToPro(this, - new MoveFilesListener() - { - @Override - public void moveFilesFinished(String newPath) - { - UiUtils.showAlertDialog(MWMActivity.this, R.string.move_lite_maps_to_pro_ok); - } - - @Override - public void moveFilesFailed(int errorCode) - { - UiUtils.showAlertDialog(MWMActivity.this, R.string.move_lite_maps_to_pro_failed); - } - } - ); - } - } - - private void checkUpdateMapsWithoutSearchIndex() - { - // do it only once - if (mNeedCheckUpdate) - { - mNeedCheckUpdate = false; - - MapStorage.INSTANCE.updateMapsWithoutSearchIndex(R.string.advise_update_maps, this, new MapStorage.UpdateFunctor() - { - @Override - public void doUpdate() - { - runOnUiThread(new Runnable() - { - @Override - public void run() - { - showDownloader(false); - } - }); - } - - @Override - public void doCancel() - { - } - }); - } - } - - private void showBookmarks() - { - popAllFragments(); - startActivity(new Intent(this, BookmarkCategoriesActivity.class)); - } - - private void showSearchIfContainsSearchIndex() - { - if (!MapStorage.INSTANCE.updateMapsWithoutSearchIndex(R.string.search_update_maps, this, new MapStorage.UpdateFunctor() - { - @Override - public void doUpdate() - { - showDownloader(false); - } - - @Override - public void doCancel() - { - showSearch(); - } - })) - { - showSearch(); - } - } - - private void showSearch() - { - if (mIsFragmentContainer) - { - if (getSupportFragmentManager().findFragmentByTag(SearchFragment.class.getName()) != null) // search is already shown - return; - hidePlacePage(); - Framework.deactivatePopup(); - popFragment(); - replaceFragment(SearchFragment.class.getName(), true, getIntent().getExtras()); - } - else - startActivity(new Intent(this, SearchActivity.class)); - } - - @Override - public void replaceFragment(String fragmentClassName, boolean addToBackStack, Bundle args) - { - FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); - Fragment fragment = Fragment.instantiate(this, fragmentClassName, args); - transaction.setCustomAnimations(R.anim.fragment_slide_in_bottom, R.anim.fragment_slide_out_bottom, - R.anim.fragment_slide_in_bottom, R.anim.fragment_slide_out_bottom); - transaction.replace(R.id.fragment_container, fragment, fragment.getClass().getName()); - if (addToBackStack) - transaction.addToBackStack(null); - - transaction.commit(); - } - - private void shareMyLocation() - { - final Location loc = LocationHelper.INSTANCE.getLastLocation(); - if (loc != null) - { - final String geoUrl = Framework.nativeGetGe0Url(loc.getLatitude(), loc.getLongitude(), Framework.getDrawScale(), ""); - final String httpUrl = Framework.getHttpGe0Url(loc.getLatitude(), loc.getLongitude(), Framework.getDrawScale(), ""); - final String body = getString(R.string.my_position_share_sms, geoUrl, httpUrl); - ShareAction.ANY_SHARE.share(this, body); - } - else - { - new AlertDialog.Builder(MWMActivity.this) - .setMessage(R.string.unknown_current_position) - .setCancelable(true) - .setPositiveButton(android.R.string.ok, new Dialog.OnClickListener() - { - @Override - public void onClick(DialogInterface dialog, int which) - { - dialog.dismiss(); - } - }) - .create() - .show(); - } - } - - private void showDownloader(boolean openDownloadedList) - { - if (mIsFragmentContainer) - { - if (getSupportFragmentManager().findFragmentByTag(DownloadFragment.class.getName()) != null) // downloader is already shown - return; - popFragment(); - hidePlacePage(); - SearchToolbarController.cancelSearch(); - mSearchController.refreshToolbar(); - replaceFragment(DownloadFragment.class.getName(), true, new Bundle()); - mFadeView.fadeIn(false); - } - else - { - final Intent intent = new Intent(this, DownloadActivity.class).putExtra(DownloadActivity.EXTRA_OPEN_DOWNLOADED_LIST, openDownloadedList); - startActivity(intent); - } - } - - @Override - public void onCreate(@Nullable Bundle savedInstanceState) - { - super.onCreate(savedInstanceState); - - setContentView(R.layout.activity_map); - initViews(); - - TtsPlayer.INSTANCE.init(); - - if (MWMApplication.get().nativeIsBenchmarking()) - Utils.keepScreenOn(true, getWindow()); - - // TODO consider implementing other model of listeners connection, without activities being bound - Framework.nativeSetRoutingListener(this); - Framework.nativeSetRouteProgressListener(this); - Framework.nativeSetBalloonListener(this); - - final Intent intent = getIntent(); - // We need check for tasks both in onCreate and onNewIntent - // because of bug in OS: https://code.google.com/p/android/issues/detail?id=38629 - addTask(intent); - - if (intent != null && intent.hasExtra(EXTRA_SCREENSHOTS_TASK)) - { - String value = intent.getStringExtra(EXTRA_SCREENSHOTS_TASK); - if (value.equals(SCREENSHOTS_TASK_LOCATE)) - switchNextLocationState(); - } - - mLocationPredictor = new LocationPredictor(new Handler(), this); - mLikesManager = new LikesManager(this); - mSearchController = new SearchToolbarController(this); - - SharingHelper.prepare(); - } - - private void initViews() - { - initMap(); - initYota(); - initPlacePage(); - initRoutingBox(); - initNavigationButtons(); - if (findViewById(R.id.fragment_container) != null) - mIsFragmentContainer = true; - } - - private void initRoutingBox() - { - mLayoutRouting = (RoutingLayout) findViewById(R.id.layout__routing); - mLayoutRouting.setListener(new RoutingLayout.ActionListener() - { - @Override - public void onCloseRouting() - { - refreshZoomButtonsVisibility(); - } - - @Override - public void onStartRouteFollow() {} - - @Override - public void onRouteTypeChange(int type) {} - }); - } - - private void initMap() - { - mFadeView = (FadeView) findViewById(R.id.fade_view); - mFadeView.setFadeListener(new FadeView.FadeListener() - { - @Override - public void onFadeOut() - { - if (mBottomButtons.areButtonsVisible()) - mBottomButtons.slideButtonsOut(); - } - - @Override - public void onFadeIn() - { - - } - }); - mMapFragment = (MapFragment) getSupportFragmentManager().findFragmentByTag(MapFragment.FRAGMENT_TAG); - if (mMapFragment == null) - { - mMapFragment = (MapFragment) MapFragment.instantiate(this, MapFragment.class.getName(), null); - getSupportFragmentManager().beginTransaction(). - replace(R.id.map_fragment_container, mMapFragment, MapFragment.FRAGMENT_TAG).commit(); - } - findViewById(R.id.map_fragment_container).setOnTouchListener(this); - } - - @SuppressWarnings("deprecation") - private void initNavigationButtons() - { - mBottomButtons = (BottomButtonsLayout) findViewById(R.id.map_bottom_buttons); - mBottomButtons.hideButtons(); - mBottomButtons.findViewById(R.id.btn__open_menu).setOnClickListener(this); - mBottomButtons.findViewById(R.id.ll__share).setOnClickListener(this); - mBottomButtons.findViewById(R.id.ll__search).setOnClickListener(this); - mBottomButtons.findViewById(R.id.ll__download_maps).setOnClickListener(this); - mBottomButtons.findViewById(R.id.ll__bookmarks).setOnClickListener(this); - mBottomButtons.findViewById(R.id.ll__settings).setOnClickListener(this); - - mNavigationButtons = (ViewGroup) findViewById(R.id.navigation_buttons); - mBtnZoomIn = (ImageButton) mNavigationButtons.findViewById(R.id.map_button_plus); - mBtnZoomIn.setOnClickListener(this); - mBtnZoomOut = (ImageButton) mNavigationButtons.findViewById(R.id.map_button_minus); - mBtnZoomOut.setOnClickListener(this); - mBtnLocation = (ImageButton) mNavigationButtons.findViewById(R.id.btn__myposition); - mBtnLocation.setOnClickListener(this); - - mToolbarSearch = findViewById(R.id.toolbar_search); - } - - private void initPlacePage() - { - mPlacePage = (PlacePageView) findViewById(R.id.info_box); - mPlacePage.setOnVisibilityChangedListener(this); - mPlacePage.findViewById(R.id.ll__route).setOnClickListener(this); - } - - private void initYota() - { - final View yopmeButton = findViewById(R.id.yop_it); - if (Yota.isFirstYota()) - yopmeButton.setOnClickListener(this); - else - yopmeButton.setVisibility(View.INVISIBLE); - } - - @Override - public void onDestroy() - { - Framework.nativeRemoveBalloonListener(); - BottomSheetHelper.free(); - super.onDestroy(); - } - - @Override - protected void onSaveInstanceState(Bundle outState) - { - if (mPlacePage.getState() != State.HIDDEN) - { - outState.putBoolean(STATE_PP_OPENED, true); - outState.putParcelable(STATE_MAP_OBJECT, mPlacePage.getMapObject()); - } - else if (mBottomButtons.areButtonsVisible()) - outState.putBoolean(STATE_BUTTONS_OPENED, true); - - super.onSaveInstanceState(outState); - } - - @Override - protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) - { - if (savedInstanceState.getBoolean(STATE_PP_OPENED)) - { - mPlacePage.setMapObject((MapObject) savedInstanceState.getParcelable(STATE_MAP_OBJECT)); - mPlacePage.setState(State.PREVIEW); - } - - if (savedInstanceState.getBoolean(STATE_BUTTONS_OPENED)) - { - mFadeView.fadeInInstantly(); - mBottomButtons.showButtons(); - } - - super.onRestoreInstanceState(savedInstanceState); - } - - @Override - protected void onNewIntent(Intent intent) - { - super.onNewIntent(intent); - - if (intent != null) - { - if (intent.hasExtra(EXTRA_TASK)) - addTask(intent); - else if (intent.hasExtra(EXTRA_SET_MAP_STYLE)) - { - final int mapStyle = intent.getIntExtra(EXTRA_SET_MAP_STYLE, Framework.MAP_STYLE_LIGHT); - Framework.setMapStyle(mapStyle); - } - } - } - - private void addTask(Intent intent) - { - if (intent != null - && !intent.getBooleanExtra(EXTRA_CONSUMED, false) - && intent.hasExtra(EXTRA_TASK) - && ((intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0)) - { - final MapTask mapTask = (MapTask) intent.getSerializableExtra(EXTRA_TASK); - mTasks.add(mapTask); - intent.removeExtra(EXTRA_TASK); - - if (mMapFragment.isRenderingInitialized()) - runTasks(); - - // mark intent as consumed - intent.putExtra(EXTRA_CONSUMED, true); - } - } - - @Override - public void onLocationError(int errorCode) - { - mMapFragment.nativeOnLocationError(errorCode); - - // Notify user about turned off location services - if (errorCode == LocationHelper.ERROR_DENIED) - { - LocationState.INSTANCE.turnOff(); - - // Do not show this dialog on Kindle Fire - it doesn't have location services - // and even wifi settings can't be opened programmatically - if (!Utils.isAmazonDevice()) - { - new AlertDialog.Builder(this).setTitle(R.string.location_is_disabled_long_text) - .setPositiveButton(R.string.connection_settings, new DialogInterface.OnClickListener() - { - @Override - public void onClick(DialogInterface dialog, int which) - { - try - { - startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)); - } catch (final Exception e1) - { - // On older Android devices location settings are merged with security - try - { - startActivity(new Intent(android.provider.Settings.ACTION_SECURITY_SETTINGS)); - } catch (final Exception e2) - { - Log.w(TAG, "Can't run activity" + e2); - } - } - - dialog.dismiss(); - } - }) - .setNegativeButton(R.string.close, new DialogInterface.OnClickListener() - { - @Override - public void onClick(DialogInterface dialog, int which) - { - dialog.dismiss(); - } - }) - .create() - .show(); - } - } - else if (errorCode == LocationHelper.ERROR_GPS_OFF) - { - Toast.makeText(this, R.string.gps_is_disabled_long_text, Toast.LENGTH_LONG).show(); - } - } - - @Override - public void onLocationUpdated(final Location l) - { - if (!l.getProvider().equals(LocationHelper.LOCATION_PREDICTOR_PROVIDER)) - mLocationPredictor.reset(l); - - mMapFragment.nativeLocationUpdated( - l.getTime(), - l.getLatitude(), - l.getLongitude(), - l.getAccuracy(), - l.getAltitude(), - l.getSpeed(), - l.getBearing()); - - if (mPlacePage.getState() != State.HIDDEN) - mPlacePage.refreshLocation(l); - - RoutingLayout.State state = mLayoutRouting.getState(); - if (state != RoutingLayout.State.HIDDEN) - { - mLayoutRouting.updateRouteInfo(); - - // TODO think about moving TtsPlayer logic to RoutingLayout to minimize native calls. - if (state == RoutingLayout.State.TURN_INSTRUCTIONS) - { - final String[] turnNotifications = Framework.nativeGenerateTurnSound(); - if (turnNotifications != null) - TtsPlayer.INSTANCE.speakNotifications(turnNotifications); - } - } - } - - @Override - public void onCompassUpdated(long time, double magneticNorth, double trueNorth, double accuracy) - { - final int rotation = getWindowManager().getDefaultDisplay().getRotation(); - magneticNorth = LocationUtils.correctCompassAngle(rotation, magneticNorth); - trueNorth = LocationUtils.correctCompassAngle(rotation, trueNorth); - final double north = (trueNorth >= 0.0) ? trueNorth : magneticNorth; - - mMapFragment.nativeCompassUpdated(time, magneticNorth, trueNorth, accuracy); - if (mPlacePage.getState() != State.HIDDEN) - mPlacePage.refreshAzimuth(north); - - if (mLayoutRouting.getState() != RoutingLayout.State.HIDDEN) - mLayoutRouting.refreshAzimuth(north); - } - - // Callback from native location state mode element processing. - public void onLocationStateModeChangedCallback(final int newMode) - { - runOnUiThread(new Runnable() - { - @Override - public void run() - { - refreshLocationState(newMode); - } - }); - } - - private void refreshLocationState(int newMode) - { - LocationButtonImageSetter.setButtonViewFromState(newMode, mBtnLocation); - switch (newMode) - { - case LocationState.UNKNOWN_POSITION: - pauseLocation(); - break; - case LocationState.PENDING_POSITION: - listenLocationUpdates(); - break; - default: - break; - } - } - - private void listenLocationStateModeUpdates() - { - mLocationStateModeListenerId = LocationState.INSTANCE.addLocationStateModeListener(this); - } - - private void stopWatchingCompassStatusUpdate() - { - LocationState.INSTANCE.removeLocationStateModeListener(mLocationStateModeListenerId); - } - - @Override - protected void onResume() - { - super.onResume(); - - listenLocationStateModeUpdates(); - invalidateLocationState(); - startWatchingExternalStorage(); - mSearchController.refreshToolbar(); - mPlacePage.onResume(); - mLikesManager.showLikeDialogForCurrentSession(); - refreshZoomButtonsAfterLayout(); - } - - private void refreshZoomButtonsAfterLayout() - { - mFadeView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() - { - @SuppressWarnings("deprecation") - @Override - public void onGlobalLayout() - { - refreshZoomButtonsVisibility(); - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) - mFadeView.getViewTreeObserver().removeGlobalOnLayoutListener(this); - else - mFadeView.getViewTreeObserver().removeOnGlobalLayoutListener(this); - } - }); - } - - private void refreshZoomButtonsVisibility() - { - final boolean showZoomSetting = MWMApplication.get().nativeGetBoolean(SettingsActivity.ZOOM_BUTTON_ENABLED, true) || Framework.nativeIsRoutingActive(); - UiUtils.showIf(showZoomSetting && - !UiUtils.areViewsIntersecting(mToolbarSearch, mBtnZoomIn) && - !UiUtils.areViewsIntersecting(mLayoutRouting, mBtnZoomIn), - mBtnZoomIn, mBtnZoomOut); - } - - @Override - protected void onPause() - { - pauseLocation(); - stopWatchingExternalStorage(); - stopWatchingCompassStatusUpdate(); - TtsPlayer.INSTANCE.stop(); - super.onPause(); - mLikesManager.cancelLikeDialog(); - } - - private void updateExternalStorageState() - { - boolean available = false, writable = false; - final String state = Environment.getExternalStorageState(); - if (Environment.MEDIA_MOUNTED.equals(state)) - available = writable = true; - else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) - available = true; - - if (mStorageAvailable != available || mStorageWritable != writable) - { - mStorageAvailable = available; - mStorageWritable = writable; - handleExternalStorageState(available, writable); - } - } - - private void handleExternalStorageState(boolean available, boolean writeable) - { - if (available && writeable) - { - // Add local maps to the model - mMapFragment.nativeStorageConnected(); - - // @TODO enable downloader button and dismiss blocking popup - - if (mStorageDisconnectedDialog != null) - mStorageDisconnectedDialog.dismiss(); - } - else if (available) - { - // Add local maps to the model - mMapFragment.nativeStorageConnected(); - - // @TODO disable downloader button and dismiss blocking popup - - if (mStorageDisconnectedDialog != null) - mStorageDisconnectedDialog.dismiss(); - } - else - { - // Remove local maps from the model - mMapFragment.nativeStorageDisconnected(); - - // @TODO enable downloader button and show blocking popup - - if (mStorageDisconnectedDialog == null) - { - mStorageDisconnectedDialog = new AlertDialog.Builder(this) - .setTitle(R.string.external_storage_is_not_available) - .setMessage(getString(R.string.disconnect_usb_cable)) - .setCancelable(false) - .create(); - } - mStorageDisconnectedDialog.show(); - } - } - - private void startWatchingExternalStorage() - { - mExternalStorageReceiver = new BroadcastReceiver() - { - @Override - public void onReceive(Context context, Intent intent) - { - updateExternalStorageState(); - } - }; - - registerReceiver(mExternalStorageReceiver, StoragePathManager.getMediaChangesIntentFilter()); - updateExternalStorageState(); - } - - private void stopWatchingExternalStorage() - { - mPathManager.stopExternalStorageWatching(); - if (mExternalStorageReceiver != null) - { - unregisterReceiver(mExternalStorageReceiver); - mExternalStorageReceiver = null; - } - } - - @Override - public void onBackPressed() - { - if (mPlacePage.getState() != State.HIDDEN) - { - hidePlacePage(); - Framework.deactivatePopup(); - } - else if (mBottomButtons.areButtonsVisible()) - { - mBottomButtons.toggle(); - mFadeView.fadeOut(false); - } - else if (canFragmentInterceptBackPress()) - return; - else if (popFragment()) - { - InputUtils.hideKeyboard(mFadeView); - mFadeView.fadeOut(false); - } - else - super.onBackPressed(); - } - - private boolean isMapFaded() - { - return mFadeView.getVisibility() == View.VISIBLE; - } - - private boolean canFragmentInterceptBackPress() - { - final FragmentManager manager = getSupportFragmentManager(); - DownloadFragment fragment = (DownloadFragment) manager.findFragmentByTag(DownloadFragment.class.getName()); - return fragment != null && fragment.isResumed() && fragment.onBackPressed(); - } - - private boolean popFragment() - { - for (String tag : new String[]{SearchFragment.class.getName(), DownloadFragment.class.getName()}) - if (popFragment(tag)) - return true; - - return false; - } - - private void popAllFragments() - { - for (String tag : new String[]{SearchFragment.class.getName(), DownloadFragment.class.getName()}) - popFragment(tag); - } - - private boolean popFragment(String className) - { - final FragmentManager manager = getSupportFragmentManager(); - Fragment fragment = manager.findFragmentByTag(className); - // TODO d.yunitsky - // we cant pop fragment, if it isn't resumed, cause of 'at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1375)' - if (fragment != null && fragment.isResumed()) - { - manager.popBackStackImmediate(); - return true; - } - - return false; - } - - // Callbacks from native map objects touch event. - @Override - public void onApiPointActivated(final double lat, final double lon, final String name, final String id) - { - if (ParsedMwmRequest.hasRequest()) - { - final ParsedMwmRequest request = ParsedMwmRequest.getCurrentRequest(); - request.setPointData(lat, lon, name, id); - - runOnUiThread(new Runnable() - { - @Override - public void run() - { - final String poiType = ParsedMwmRequest.getCurrentRequest().getCallerName(MWMApplication.get()).toString(); - activateMapObject(new ApiPoint(name, id, poiType, lat, lon)); - } - }); - } - } - - @Override - public void onPoiActivated(final String name, final String type, final String address, final double lat, final double lon, - final int[] metaTypes, final String[] metaValues) - { - final MapObject poi = new MapObject.Poi(name, lat, lon, type); - poi.addMetadata(metaTypes, metaValues); - - runOnUiThread(new Runnable() - { - @Override - public void run() - { - activateMapObject(poi); - } - }); - } - - @Override - public void onBookmarkActivated(final int category, final int bookmarkIndex) - { - runOnUiThread(new Runnable() - { - @Override - public void run() - { - activateMapObject(BookmarkManager.INSTANCE.getBookmark(category, bookmarkIndex)); - } - }); - } - - @Override - public void onMyPositionActivated(final double lat, final double lon) - { - final MapObject mypos = new MapObject.MyPosition(getString(R.string.my_position), lat, lon); - - runOnUiThread(new Runnable() - { - @Override - public void run() - { - if (!Framework.nativeIsRoutingActive()) - { - activateMapObject(mypos); - } - } - }); - } - - @Override - public void onAdditionalLayerActivated(final String name, final String type, final double lat, final double lon, final int[] metaTypes, final String[] metaValues) - { - runOnUiThread(new Runnable() - { - @Override - public void run() - { - final MapObject sr = new MapObject.SearchResult(name, type, lat, lon); - sr.addMetadata(metaTypes, metaValues); - activateMapObject(sr); - } - }); - } - - private void activateMapObject(MapObject object) - { - mPlacePage.bringToFront(); - if (!mPlacePage.hasMapObject(object)) - { - mPlacePage.setMapObject(object); - mPlacePage.setState(State.PREVIEW); - popAllFragments(); - if (isMapFaded()) - mFadeView.fadeOut(false); - } - } - - private void hidePlacePage() - { - mPlacePage.setState(State.HIDDEN); - mPlacePage.setMapObject(null); - } - - @Override - public void onDismiss() - { - if (!mPlacePage.hasMapObject(null)) - { - runOnUiThread(new Runnable() - { - @Override - public void run() - { - hidePlacePage(); - Framework.deactivatePopup(); - } - }); - } - } - - @Override - public void onPreviewVisibilityChanged(boolean isVisible) - { - if (isVisible) - { - if (previewIntersectsBottomMenu()) - mBottomButtons.setVisibility(View.GONE); - if (previewIntersectsZoomButtons()) - UiUtils.hide(mBtnZoomIn, mBtnZoomOut); - } - else - { - Framework.deactivatePopup(); - mPlacePage.setMapObject(null); - refreshZoomButtonsVisibility(); - mBottomButtons.setVisibility(View.VISIBLE); - } - } - - private boolean previewIntersectsBottomMenu() - { - return !(UiUtils.isBigTablet() || (UiUtils.isSmallTablet() && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)); - } - - private boolean previewIntersectsZoomButtons() - { - return !(UiUtils.isBigTablet() || UiUtils.isSmallTablet()); - } - - @Override - public void onPlacePageVisibilityChanged(boolean isVisible) - { - if (isVisible) - { - AlohaHelper.logClick(AlohaHelper.PP_OPEN); - if (placePageIntersectsZoomButtons()) - UiUtils.hide(mBtnZoomIn, mBtnZoomOut); - else - refreshZoomButtonsVisibility(); - } - else - AlohaHelper.logClick(AlohaHelper.PP_CLOSE); - } - - private boolean placePageIntersectsZoomButtons() - { - return !(UiUtils.isBigTablet() || (UiUtils.isSmallTablet() && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)); - } - - @Override - public void onClick(View v) - { - switch (v.getId()) - { - case R.id.ll__share: - AlohaHelper.logClick(AlohaHelper.MENU_SHARE); - shareMyLocation(); - mBottomButtons.hideButtons(); - UiUtils.hide(mFadeView); - UiUtils.clearAnimationAfterAlpha(mFadeView); - break; - case R.id.ll__settings: - AlohaHelper.logClick(AlohaHelper.MENU_SETTINGS); - startActivity(new Intent(this, SettingsActivity.class)); - mBottomButtons.hideButtons(); - UiUtils.hide(mFadeView); - UiUtils.clearAnimationAfterAlpha(mFadeView); - break; - case R.id.ll__download_maps: - AlohaHelper.logClick(AlohaHelper.MENU_DOWNLOADER); - showDownloader(false); - mBottomButtons.hideButtons(); - UiUtils.hide(mFadeView); - UiUtils.clearAnimationAfterAlpha(mFadeView); - break; - case R.id.ll__route: - AlohaHelper.logClick(AlohaHelper.PP_ROUTE); - mLayoutRouting.setEndPoint(mPlacePage.getMapObject()); - mLayoutRouting.setState(RoutingLayout.State.PREPARING, true); - mPlacePage.setState(PlacePageView.State.HIDDEN); - break; - case R.id.map_button_plus: - AlohaHelper.logClick(AlohaHelper.ZOOM_IN); - mMapFragment.nativeScale(3.0 / 2); - break; - case R.id.map_button_minus: - AlohaHelper.logClick(AlohaHelper.ZOOM_OUT); - mMapFragment.nativeScale(2 / 3.0); - break; - case R.id.btn__open_menu: - AlohaHelper.logClick(AlohaHelper.TOOLBAR_MENU); - mFadeView.fadeIn(false); - mBottomButtons.toggle(); - break; - case R.id.ll__search: - AlohaHelper.logClick(AlohaHelper.TOOLBAR_SEARCH); - showSearchIfContainsSearchIndex(); - mBottomButtons.hideButtons(); - UiUtils.hide(mFadeView); - UiUtils.clearAnimationAfterAlpha(mFadeView); - break; - case R.id.ll__bookmarks: - AlohaHelper.logClick(AlohaHelper.TOOLBAR_BOOKMARKS); - showBookmarks(); - mBottomButtons.hideButtons(); - UiUtils.hide(mFadeView); - UiUtils.clearAnimationAfterAlpha(mFadeView); - break; - case R.id.btn__myposition: - switchNextLocationState(); - break; - case R.id.yop_it: - final double[] latLon = Framework.getScreenRectCenter(); - final double zoom = Framework.getDrawScale(); - - final int locationStateMode = LocationState.INSTANCE.getLocationStateMode(); - - if (locationStateMode > LocationState.NOT_FOLLOW) - Yota.showLocation(getApplicationContext(), zoom); - else - Yota.showMap(getApplicationContext(), latLon[0], latLon[1], zoom, null, locationStateMode == LocationState.NOT_FOLLOW); - - Statistics.INSTANCE.trackBackscreenCall("Map"); - break; - default: - break; - } - } - - private void closeRouting() - { - - mLayoutRouting.setState(RoutingLayout.State.HIDDEN, true); - } - - private static void switchNextLocationState() - { - LocationState.INSTANCE.switchToNextMode(); - } - - @Override - public boolean onTouch(View view, MotionEvent event) - { - boolean result = false; - if (mPlacePage.getState() == State.DETAILS || mPlacePage.getState() == State.BOOKMARK) - { - Framework.deactivatePopup(); - hidePlacePage(); - result = true; - } - - return result || mMapFragment.onTouch(view, event); - } - - @Override - public boolean onKeyUp(int keyCode, @NonNull KeyEvent event) - { - if (keyCode == KeyEvent.KEYCODE_MENU) - { - if (mBottomButtons.areButtonsVisible()) - mFadeView.fadeOut(false); - else - mFadeView.fadeIn(false); - mBottomButtons.toggle(); - return true; - } - return super.onKeyUp(keyCode, event); - } - - @Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) - { - if (resultCode == RESULT_OK && requestCode == ChooseBookmarkCategoryActivity.REQUEST_CODE_BOOKMARK_SET) - { - final Point bookmarkAndCategory = ((ParcelablePoint) data.getParcelableExtra(ChooseBookmarkCategoryActivity.BOOKMARK)).getPoint(); - final Bookmark bookmark = BookmarkManager.INSTANCE.getBookmark(bookmarkAndCategory.x, bookmarkAndCategory.y); - mPlacePage.setMapObject(bookmark); - } - super.onActivityResult(requestCode, resultCode, data); - } - - @Override - public void onRoutingEvent(final int resultCode, final Index[] missingCountries) - { - runOnUiThread(new Runnable() - { - @Override - public void run() - { - if (resultCode == RoutingResultCodesProcessor.NO_ERROR) - { - mLayoutRouting.setState(RoutingLayout.State.ROUTE_BUILT, true); - } - else - { - mLayoutRouting.setState(RoutingLayout.State.ROUTE_BUILD_ERROR, true); - final Bundle args = new Bundle(); - args.putInt(RoutingErrorDialogFragment.EXTRA_RESULT_CODE, resultCode); - args.putSerializable(RoutingErrorDialogFragment.EXTRA_MISSING_COUNTRIES, missingCountries); - final RoutingErrorDialogFragment fragment = (RoutingErrorDialogFragment) Fragment.instantiate(MWMActivity.this, RoutingErrorDialogFragment.class.getName()); - fragment.setArguments(args); - fragment.setListener(new RoutingErrorDialogFragment.RoutingDialogListener() - { - @Override - public void onDownload() - { - mLayoutRouting.setState(RoutingLayout.State.HIDDEN, false); - refreshZoomButtonsVisibility(); - ActiveCountryTree.downloadMapsForIndex(missingCountries, StorageOptions.MAP_OPTION_MAP_AND_CAR_ROUTING); - showDownloader(true); - } - - @Override - public void onCancel() - { - refreshZoomButtonsVisibility(); - } - - @Override - public void onOk() - { - if (RoutingResultCodesProcessor.isDownloadable(resultCode)) - { - mLayoutRouting.setState(RoutingLayout.State.HIDDEN, false); - refreshZoomButtonsVisibility(); - showDownloader(false); - } - } - }); - fragment.show(getSupportFragmentManager(), RoutingErrorDialogFragment.class.getName()); - } - - refreshZoomButtonsVisibility(); - } - }); - } - - @Override - public void onRouteBuildingProgress(final float progress) - { - runOnUiThread(new Runnable() - { - @Override - public void run() - { - mLayoutRouting.setRouteBuildingProgress(progress); - } - }); - } - - @Override - public void customOnNavigateUp() - { - if (popFragment()) - { - InputUtils.hideKeyboard(mBottomButtons); - mSearchController.refreshToolbar(); - } - } - - public interface MapTask extends Serializable - { - boolean run(MWMActivity target); - } - - public static class OpenUrlTask implements MapTask - { - private static final long serialVersionUID = 1L; - private final String mUrl; - - public OpenUrlTask(String url) - { - Utils.checkNotNull(url); - mUrl = url; - } - - @Override - public boolean run(MWMActivity target) - { - return target.mMapFragment.showMapForUrl(mUrl); - } - } - - public static class ShowCountryTask implements MapTask - { - private static final long serialVersionUID = 1L; - private final Index mIndex; - private final boolean mDoAutoDownload; - - public ShowCountryTask(Index index, boolean doAutoDownload) - { - mIndex = index; - mDoAutoDownload = doAutoDownload; - } - - @Override - public boolean run(MWMActivity target) - { - if (mDoAutoDownload) - { - Framework.downloadCountry(mIndex); - // set zoom level so that download process is visible - Framework.nativeShowCountry(mIndex, true); - } - else - Framework.nativeShowCountry(mIndex, false); - - return true; - } - } - - public static class UpdateCountryTask implements MapTask - { - @Override - public boolean run(final MWMActivity target) - { - target.runOnUiThread(new Runnable() - { - @Override - public void run() - { - target.showDownloader(true); - } - }); - return true; - } - } -} diff --git a/android/src/com/mapswithme/maps/MWMApplication.java b/android/src/com/mapswithme/maps/MWMApplication.java deleted file mode 100644 index f3341b4cdd..0000000000 --- a/android/src/com/mapswithme/maps/MWMApplication.java +++ /dev/null @@ -1,346 +0,0 @@ -package com.mapswithme.maps; - -import android.content.SharedPreferences; -import android.content.pm.PackageManager.NameNotFoundException; -import android.os.Environment; -import android.preference.PreferenceManager; -import android.text.TextUtils; -import android.text.format.DateUtils; -import android.util.Log; - -import com.google.gsonaltered.Gson; -import com.mapswithme.country.ActiveCountryTree; -import com.mapswithme.country.CountryItem; -import com.mapswithme.maps.background.Notifier; -import com.mapswithme.maps.bookmarks.data.BookmarkManager; -import com.mapswithme.util.Constants; -import com.mapswithme.util.UiUtils; -import com.mapswithme.util.Yota; -import com.mapswithme.util.statistics.AlohaHelper; -import com.parse.Parse; -import com.parse.ParseException; -import com.parse.ParseInstallation; -import com.parse.SaveCallback; - -import java.io.File; -import java.util.HashMap; -import java.util.Map; - -import ru.mail.android.mytracker.MRMyTracker; -import ru.mail.android.mytracker.MRMyTrackerParams; - -public class MWMApplication extends android.app.Application implements ActiveCountryTree.ActiveCountryListener -{ - private final static String TAG = "MWMApplication"; - private static final String FOREGROUND_TIME_SETTING = "AllForegroundTime"; - private static final String LAUNCH_NUMBER_SETTING = "LaunchNumber"; // total number of app launches - private static final String SESSION_NUMBER_SETTING = "SessionNumber"; // session = number of days, when app was launched - private static final String LAST_SESSION_TIMESTAMP_SETTING = "LastSessionTimestamp"; // timestamp of last session - private static final String FIRST_INSTALL_VERSION = "FirstInstallVersion"; - private static final String FIRST_INSTALL_FLAVOR = "FirstInstallFlavor"; - // for myTracker - private static final String MY_MAP_DOWNLOAD = "DownloadMap"; - private static final String MY_MAP_UPDATE = "UpdateMap"; - private static final String MY_TOTAL_COUNT = "Count"; - // Parse - private static final String PREF_PARSE_DEVICE_TOKEN = "ParseDeviceToken"; - private static final String PREF_PARSE_INSTALLATION_ID = "ParseInstallationId"; - - private static MWMApplication mSelf; - private final Gson mGson = new Gson(); - - private boolean mAreStatsInitialised; - - public MWMApplication() - { - super(); - mSelf = this; - } - - public static MWMApplication get() - { - return mSelf; - } - - public static Gson gson() - { - return mSelf.mGson; - } - - @Override - public void onCountryProgressChanged(int group, int position, long[] sizes) {} - - @Override - public void onCountryStatusChanged(int group, int position, int oldStatus, int newStatus) - { - Notifier.cancelDownloadSuggest(); - if (newStatus == MapStorage.DOWNLOAD_FAILED) - { - CountryItem item = ActiveCountryTree.getCountryItem(group, position); - Notifier.placeDownloadFailed(ActiveCountryTree.getCoreIndex(group, position), item.getName()); - } - } - - @Override - public void onCountryGroupChanged(int oldGroup, int oldPosition, int newGroup, int newPosition) - { - if (oldGroup == ActiveCountryTree.GROUP_NEW && newGroup == ActiveCountryTree.GROUP_UP_TO_DATE) - myTrackerTrackMapChange(MY_MAP_DOWNLOAD); - else if (oldGroup == ActiveCountryTree.GROUP_OUT_OF_DATE && newGroup == ActiveCountryTree.GROUP_UP_TO_DATE) - myTrackerTrackMapChange(MY_MAP_UPDATE); - } - - private void myTrackerTrackMapChange(String eventType) - { - final Map params = new HashMap<>(); - params.put(MY_TOTAL_COUNT, String.valueOf(ActiveCountryTree.getTotalDownloadedCount())); - MRMyTracker.trackEvent(eventType, params); - } - - @Override - public void onCountryOptionsChanged(int group, int position, int newOptions, int requestOptions) - { - CountryItem item = ActiveCountryTree.getCountryItem(group, position); - if (item.getStatus() != MapStorage.ON_DISK) - return; - - if (newOptions == requestOptions) - Notifier.placeDownloadCompleted(ActiveCountryTree.getCoreIndex(group, position), item.getName()); - } - - @Override - public void onCreate() - { - super.onCreate(); - - final String extStoragePath = getDataStoragePath(); - final String extTmpPath = getTempPath(); - - // Create folders if they don't exist - new File(extStoragePath).mkdirs(); - new File(extTmpPath).mkdirs(); - - // init native framework - nativeInit(getApkPath(), extStoragePath, extTmpPath, getOBBGooglePath(), - BuildConfig.FLAVOR, BuildConfig.BUILD_TYPE, - Yota.isFirstYota(), UiUtils.isSmallTablet() || UiUtils.isBigTablet()); - - ActiveCountryTree.addListener(this); - - // init cross-platform strings bundle - nativeAddLocalization("country_status_added_to_queue", getString(R.string.country_status_added_to_queue)); - nativeAddLocalization("country_status_downloading", getString(R.string.country_status_downloading)); - nativeAddLocalization("country_status_download", getString(R.string.country_status_download)); - nativeAddLocalization("country_status_download_without_routing", getString(R.string.country_status_download_without_routing)); - nativeAddLocalization("country_status_download_failed", getString(R.string.country_status_download_failed)); - nativeAddLocalization("try_again", getString(R.string.try_again)); - nativeAddLocalization("not_enough_free_space_on_sdcard", getString(R.string.not_enough_free_space_on_sdcard)); - nativeAddLocalization("dropped_pin", getString(R.string.dropped_pin)); - nativeAddLocalization("my_places", getString(R.string.my_places)); - nativeAddLocalization("my_position", getString(R.string.my_position)); - nativeAddLocalization("routes", getString(R.string.routes)); - - nativeAddLocalization("routing_failed_unknown_my_position", getString(R.string.routing_failed_unknown_my_position)); - nativeAddLocalization("routing_failed_has_no_routing_file", getString(R.string.routing_failed_has_no_routing_file)); - nativeAddLocalization("routing_failed_start_point_not_found", getString(R.string.routing_failed_start_point_not_found)); - nativeAddLocalization("routing_failed_dst_point_not_found", getString(R.string.routing_failed_dst_point_not_found)); - nativeAddLocalization("routing_failed_cross_mwm_building", getString(R.string.routing_failed_cross_mwm_building)); - nativeAddLocalization("routing_failed_route_not_found", getString(R.string.routing_failed_route_not_found)); - nativeAddLocalization("routing_failed_internal_error", getString(R.string.routing_failed_internal_error)); - - // init BookmarkManager (automatically loads bookmarks) - BookmarkManager.getIcons(); - - initParse(); - } - - private void initMyTracker() - { - MRMyTracker.setDebugMode(BuildConfig.DEBUG); - - MRMyTracker.createTracker(getString(R.string.my_tracker_app_id), this); - - final MRMyTrackerParams myParams = MRMyTracker.getTrackerParams(); - myParams.setTrackingPreinstallsEnabled(true); - myParams.setTrackingLaunchEnabled(true); - - MRMyTracker.initTracker(); - } - - public String getApkPath() - { - try - { - return getPackageManager().getApplicationInfo(BuildConfig.APPLICATION_ID, 0).sourceDir; - } catch (final NameNotFoundException e) - { - Log.e(TAG, "Can't get apk path from PackageManager"); - return ""; - } - } - - public String getDataStoragePath() - { - return Environment.getExternalStorageDirectory().getAbsolutePath() + Constants.MWM_DIR_POSTFIX; - } - - public String getTempPath() - { - // TODO refactor - // Can't use getExternalCacheDir() here because of API level = 7. - return getExtAppDirectoryPath(Constants.CACHE_DIR); - } - - public String getExtAppDirectoryPath(String folder) - { - final String storagePath = Environment.getExternalStorageDirectory().getAbsolutePath(); - return storagePath.concat(String.format(Constants.STORAGE_PATH, BuildConfig.APPLICATION_ID, folder)); - } - - private String getOBBGooglePath() - { - final String storagePath = Environment.getExternalStorageDirectory().getAbsolutePath(); - return storagePath.concat(String.format(Constants.OBB_PATH, BuildConfig.APPLICATION_ID)); - } - - // Check if we have free space on storage (writable path). - public native boolean hasFreeSpace(long size); - - public double getForegroundTime() - { - return nativeGetDouble(FOREGROUND_TIME_SETTING, 0); - } - - static - { - System.loadLibrary("mapswithme"); - } - - private native void nativeInit(String apkPath, String storagePath, - String tmpPath, String obbGooglePath, - String flavorName, String buildType, - boolean isYota, boolean isTablet); - - public native boolean nativeIsBenchmarking(); - - private native void nativeAddLocalization(String name, String value); - - // Dealing with Settings - public native boolean nativeGetBoolean(String name, boolean defaultValue); - - public native void nativeSetBoolean(String name, boolean value); - - public native int nativeGetInt(String name, int defaultValue); - - public native void nativeSetInt(String name, int value); - - public native long nativeGetLong(String name, long defaultValue); - - public native void nativeSetLong(String name, long value); - - public native double nativeGetDouble(String name, double defaultValue); - - public native void nativeSetDouble(String name, double value); - - public native String nativeGetString(String name, String defaultValue); - - public native void nativeSetString(String name, String value); - - /* - * init Parse SDK - */ - private void initParse() - { - Parse.initialize(this, "***REMOVED***", "***REMOVED***"); - ParseInstallation.getCurrentInstallation().saveInBackground(new SaveCallback() - { - @Override - public void done(ParseException e) - { - SharedPreferences prefs = getSharedPreferences(getString(R.string.pref_file_name), MODE_PRIVATE); - String previousId = prefs.getString(PREF_PARSE_INSTALLATION_ID, ""); - String previousToken = prefs.getString(PREF_PARSE_DEVICE_TOKEN, ""); - - String newId = ParseInstallation.getCurrentInstallation().getInstallationId(); - String newToken = ParseInstallation.getCurrentInstallation().getString("deviceToken"); - if (previousId.equals(newId) || previousToken.equals(newToken)) - { - org.alohalytics.Statistics.logEvent(AlohaHelper.PARSE_INSTALLATION_ID, newId); - org.alohalytics.Statistics.logEvent(AlohaHelper.PARSE_DEVICE_TOKEN, newToken); - prefs.edit() - .putString(PREF_PARSE_INSTALLATION_ID, newId) - .putString(PREF_PARSE_DEVICE_TOKEN, newToken).apply(); - } - } - }); - } - - public void initStats() - { - if (!mAreStatsInitialised) - { - mAreStatsInitialised = true; - updateLaunchNumbers(); - updateSessionsNumber(); - initMyTracker(); - PreferenceManager.setDefaultValues(this, R.xml.preferences, false); - - org.alohalytics.Statistics.setDebugMode(BuildConfig.DEBUG); - org.alohalytics.Statistics.setup(BuildConfig.STATISTICS_URL, this); - } - } - - private void updateLaunchNumbers() - { - final int currentLaunches = nativeGetInt(LAUNCH_NUMBER_SETTING, 0); - if (currentLaunches == 0) - { - nativeSetInt(FIRST_INSTALL_VERSION, BuildConfig.VERSION_CODE); - - final String installedFlavor = getFirstInstallFlavor(); - if (TextUtils.isEmpty(installedFlavor)) - nativeSetString(FIRST_INSTALL_FLAVOR, BuildConfig.FLAVOR); - } - - nativeSetInt(LAUNCH_NUMBER_SETTING, currentLaunches + 1); - } - - private void updateSessionsNumber() - { - final int sessionNum = nativeGetInt(SESSION_NUMBER_SETTING, 0); - final long lastSessionTimestamp = nativeGetLong(LAST_SESSION_TIMESTAMP_SETTING, 0); - if (!DateUtils.isToday(lastSessionTimestamp)) - { - nativeSetInt(SESSION_NUMBER_SETTING, sessionNum + 1); - nativeSetLong(LAST_SESSION_TIMESTAMP_SETTING, System.currentTimeMillis()); - } - } - - /** - * @return total number of application launches - */ - public int getLaunchesNumber() - { - return nativeGetInt(LAUNCH_NUMBER_SETTING, 0); - } - - /** - * Session = single day, when app was started any number of times. - * - * @return number of sessions. - */ - public int getSessionsNumber() - { - return nativeGetInt(SESSION_NUMBER_SETTING, 0); - } - - public int getFirstInstallVersion() - { - return nativeGetInt(FIRST_INSTALL_VERSION, 0); - } - - public String getFirstInstallFlavor() - { - return nativeGetString(FIRST_INSTALL_FLAVOR, ""); - } -} diff --git a/android/src/com/mapswithme/maps/MwmActivity.java b/android/src/com/mapswithme/maps/MwmActivity.java new file mode 100644 index 0000000000..b36d0ef110 --- /dev/null +++ b/android/src/com/mapswithme/maps/MwmActivity.java @@ -0,0 +1,1417 @@ +package com.mapswithme.maps; + +import android.app.Dialog; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.res.Configuration; +import android.graphics.Point; +import android.location.Location; +import android.os.Build; +import android.os.Bundle; +import android.os.Environment; +import android.os.Handler; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; +import android.support.v4.app.Fragment; +import android.support.v4.app.FragmentManager; +import android.support.v4.app.FragmentTransaction; +import android.support.v7.app.AlertDialog; +import android.util.Log; +import android.view.KeyEvent; +import android.view.MotionEvent; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.ViewGroup; +import android.view.ViewTreeObserver; +import android.widget.ImageButton; +import android.widget.Toast; + +import com.mapswithme.country.ActiveCountryTree; +import com.mapswithme.country.DownloadActivity; +import com.mapswithme.country.DownloadFragment; +import com.mapswithme.country.StorageOptions; +import com.mapswithme.maps.Framework.OnBalloonListener; +import com.mapswithme.maps.MapStorage.Index; +import com.mapswithme.maps.activity.CustomNavigateUpListener; +import com.mapswithme.maps.ads.LikesManager; +import com.mapswithme.maps.api.ParsedMwmRequest; +import com.mapswithme.maps.base.BaseMwmFragmentActivity; +import com.mapswithme.maps.bookmarks.BookmarkCategoriesActivity; +import com.mapswithme.maps.bookmarks.ChooseBookmarkCategoryActivity; +import com.mapswithme.maps.bookmarks.data.Bookmark; +import com.mapswithme.maps.bookmarks.data.BookmarkManager; +import com.mapswithme.maps.bookmarks.data.MapObject; +import com.mapswithme.maps.bookmarks.data.MapObject.ApiPoint; +import com.mapswithme.maps.bookmarks.data.ParcelablePoint; +import com.mapswithme.maps.dialog.RoutingErrorDialogFragment; +import com.mapswithme.maps.location.LocationHelper; +import com.mapswithme.maps.location.LocationPredictor; +import com.mapswithme.maps.routing.RoutingInfo; +import com.mapswithme.maps.routing.RoutingResultCodesProcessor; +import com.mapswithme.maps.search.SearchActivity; +import com.mapswithme.maps.search.SearchFragment; +import com.mapswithme.maps.search.SearchToolbarController; +import com.mapswithme.maps.settings.SettingsActivity; +import com.mapswithme.maps.settings.StoragePathManager; +import com.mapswithme.maps.settings.StoragePathManager.MoveFilesListener; +import com.mapswithme.maps.settings.UnitLocale; +import com.mapswithme.maps.sound.TtsPlayer; +import com.mapswithme.maps.widget.BottomButtonsLayout; +import com.mapswithme.maps.widget.FadeView; +import com.mapswithme.maps.widget.RoutingLayout; +import com.mapswithme.maps.widget.placepage.BasePlacePageAnimationController; +import com.mapswithme.maps.widget.placepage.PlacePageView; +import com.mapswithme.maps.widget.placepage.PlacePageView.State; +import com.mapswithme.util.BottomSheetHelper; +import com.mapswithme.util.Constants; +import com.mapswithme.util.InputUtils; +import com.mapswithme.util.LocationUtils; +import com.mapswithme.util.UiUtils; +import com.mapswithme.util.Utils; +import com.mapswithme.util.Yota; +import com.mapswithme.util.sharing.ShareAction; +import com.mapswithme.util.sharing.SharingHelper; +import com.mapswithme.util.statistics.AlohaHelper; +import com.mapswithme.util.statistics.Statistics; + +import java.io.Serializable; +import java.util.Stack; + +public class MwmActivity extends BaseMwmFragmentActivity + implements LocationHelper.LocationListener, OnBalloonListener, View.OnTouchListener, BasePlacePageAnimationController.OnVisibilityChangedListener, + OnClickListener, Framework.RoutingListener, MapFragment.MapRenderingListener, CustomNavigateUpListener, Framework.RoutingProgressListener +{ + public static final String EXTRA_TASK = "map_task"; + private final static String TAG = "MwmActivity"; + private final static String EXTRA_CONSUMED = "mwm.extra.intent.processed"; + private final static String EXTRA_SCREENSHOTS_TASK = "screenshots_task"; + private final static String SCREENSHOTS_TASK_LOCATE = "locate_task"; + private final static String SCREENSHOTS_TASK_PPP = "show_place_page"; + private final static String EXTRA_LAT = "lat"; + private final static String EXTRA_LON = "lon"; + // Need it for change map style + private static final String EXTRA_SET_MAP_STYLE = "set_map_style"; + // Instance state + private static final String STATE_PP_OPENED = "PpOpened"; + private static final String STATE_MAP_OBJECT = "MapObject"; + private static final String STATE_BUTTONS_OPENED = "ButtonsOpened"; + + // Map tasks that we run AFTER rendering initialized + private final Stack mTasks = new Stack<>(); + private BroadcastReceiver mExternalStorageReceiver; + private final StoragePathManager mPathManager = new StoragePathManager(); + private AlertDialog mStorageDisconnectedDialog; + private ImageButton mBtnLocation; + // map + private MapFragment mMapFragment; + // Place page + private PlacePageView mPlacePage; + // Routing + private RoutingLayout mLayoutRouting; + + private boolean mNeedCheckUpdate = true; + private int mLocationStateModeListenerId = LocationState.SLOT_UNDEFINED; + // These flags are initialized to the invalid combination to force update on the first check + // after launching. + // These flags are static because the MwmActivity is recreated while screen orientation changing + // but they shall not be reinitialized on screen orientation changing. + private static boolean mStorageAvailable = false; + private static boolean mStorageWritable = true; + + private FadeView mFadeView; + + private ViewGroup mNavigationButtons; + private View mToolbarSearch; + private ImageButton mBtnZoomIn; + private ImageButton mBtnZoomOut; + private BottomButtonsLayout mBottomButtons; + + private boolean mIsFragmentContainer; + + private LocationPredictor mLocationPredictor; + private LikesManager mLikesManager; + private SearchToolbarController mSearchController; + + public static Intent createShowMapIntent(Context context, Index index, boolean doAutoDownload) + { + return new Intent(context, DownloadResourcesActivity.class) + .putExtra(DownloadResourcesActivity.EXTRA_COUNTRY_INDEX, index) + .putExtra(DownloadResourcesActivity.EXTRA_AUTODOWNLOAD_COUNTRY, doAutoDownload); + } + + public static void setMapStyle(Context context, int mapStyle) + { + final Intent mapIntent = new Intent(context, MwmActivity.class); + mapIntent.putExtra(EXTRA_SET_MAP_STYLE, mapStyle); + context.startActivity(mapIntent); + // Next we need to handle intent + } + + public static void startSearch(Context context, String query) + { + final MwmActivity activity = (MwmActivity) context; + if (activity.mIsFragmentContainer) + activity.showSearch(); + else + SearchActivity.startWithQuery(context, query); + } + + public static Intent createUpdateMapsIntent() + { + return new Intent(MwmApplication.get(), DownloadResourcesActivity.class) + .putExtra(DownloadResourcesActivity.EXTRA_UPDATE_COUNTRIES, true); + } + + private void pauseLocation() + { + LocationHelper.INSTANCE.removeLocationListener(this); + // Enable automatic turning screen off while app is idle + Utils.keepScreenOn(false, getWindow()); + mLocationPredictor.pause(); + } + + private void listenLocationUpdates() + { + LocationHelper.INSTANCE.addLocationListener(this); + // Do not turn off the screen while displaying position + Utils.keepScreenOn(true, getWindow()); + mLocationPredictor.resume(); + } + + /** + * Invalidates location state in core. + * Updates location button accordingly. + */ + public void invalidateLocationState() + { + final int currentLocationMode = LocationState.INSTANCE.getLocationStateMode(); + refreshLocationState(currentLocationMode); + LocationState.INSTANCE.invalidatePosition(); + } + + private void checkUserMarkActivation() + { + final Intent intent = getIntent(); + if (intent != null && intent.hasExtra(EXTRA_SCREENSHOTS_TASK)) + { + final String value = intent.getStringExtra(EXTRA_SCREENSHOTS_TASK); + if (value.equals(SCREENSHOTS_TASK_PPP)) + { + final double lat = Double.parseDouble(intent.getStringExtra(EXTRA_LAT)); + final double lon = Double.parseDouble(intent.getStringExtra(EXTRA_LON)); + mFadeView.getHandler().postDelayed(new Runnable() + { + @Override + public void run() + { + Framework.nativeActivateUserMark(lat, lon); + } + }, 1000); + } + } + } + + @Override + public void onRenderingInitialized() + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { + // Run all checks in main thread after rendering is initialized. + checkMeasurementSystem(); + checkUpdateMapsWithoutSearchIndex(); + checkKitkatMigrationMove(); + checkLiteMapsInPro(); + checkUserMarkActivation(); + } + }); + + runTasks(); + } + + private void runTasks() + { + // Task are not UI-thread bounded, + // if any task need UI-thread it should implicitly + // use Activity.runOnUiThread(). + while (!mTasks.isEmpty()) + mTasks.pop().run(this); + } + + private void checkMeasurementSystem() + { + UnitLocale.initializeCurrentUnits(); + } + + private void checkKitkatMigrationMove() + { + mPathManager.checkKitkatMigration(this); + } + + private void checkLiteMapsInPro() + { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && + (Utils.isPackageInstalled(Constants.Package.MWM_LITE_PACKAGE) || Utils.isPackageInstalled(Constants.Package.MWM_SAMSUNG_PACKAGE))) + { + if (!mPathManager.containsLiteMapsOnSdcard()) + return; + + mPathManager.moveMapsLiteToPro(this, + new MoveFilesListener() + { + @Override + public void moveFilesFinished(String newPath) + { + UiUtils.showAlertDialog(MwmActivity.this, R.string.move_lite_maps_to_pro_ok); + } + + @Override + public void moveFilesFailed(int errorCode) + { + UiUtils.showAlertDialog(MwmActivity.this, R.string.move_lite_maps_to_pro_failed); + } + } + ); + } + } + + private void checkUpdateMapsWithoutSearchIndex() + { + // do it only once + if (mNeedCheckUpdate) + { + mNeedCheckUpdate = false; + + MapStorage.INSTANCE.updateMapsWithoutSearchIndex(R.string.advise_update_maps, this, new MapStorage.UpdateFunctor() + { + @Override + public void doUpdate() + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { + showDownloader(false); + } + }); + } + + @Override + public void doCancel() + { + } + }); + } + } + + private void showBookmarks() + { + popAllFragments(); + startActivity(new Intent(this, BookmarkCategoriesActivity.class)); + } + + private void showSearchIfContainsSearchIndex() + { + if (!MapStorage.INSTANCE.updateMapsWithoutSearchIndex(R.string.search_update_maps, this, new MapStorage.UpdateFunctor() + { + @Override + public void doUpdate() + { + showDownloader(false); + } + + @Override + public void doCancel() + { + showSearch(); + } + })) + { + showSearch(); + } + } + + private void showSearch() + { + if (mIsFragmentContainer) + { + if (getSupportFragmentManager().findFragmentByTag(SearchFragment.class.getName()) != null) // search is already shown + return; + hidePlacePage(); + Framework.deactivatePopup(); + popFragment(); + replaceFragment(SearchFragment.class.getName(), true, getIntent().getExtras()); + } + else + startActivity(new Intent(this, SearchActivity.class)); + } + + @Override + public void replaceFragment(String fragmentClassName, boolean addToBackStack, Bundle args) + { + FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); + Fragment fragment = Fragment.instantiate(this, fragmentClassName, args); + transaction.setCustomAnimations(R.anim.fragment_slide_in_bottom, R.anim.fragment_slide_out_bottom, + R.anim.fragment_slide_in_bottom, R.anim.fragment_slide_out_bottom); + transaction.replace(R.id.fragment_container, fragment, fragment.getClass().getName()); + if (addToBackStack) + transaction.addToBackStack(null); + + transaction.commit(); + } + + private void shareMyLocation() + { + final Location loc = LocationHelper.INSTANCE.getLastLocation(); + if (loc != null) + { + final String geoUrl = Framework.nativeGetGe0Url(loc.getLatitude(), loc.getLongitude(), Framework.getDrawScale(), ""); + final String httpUrl = Framework.getHttpGe0Url(loc.getLatitude(), loc.getLongitude(), Framework.getDrawScale(), ""); + final String body = getString(R.string.my_position_share_sms, geoUrl, httpUrl); + ShareAction.ANY_SHARE.share(this, body); + } + else + { + new AlertDialog.Builder(MwmActivity.this) + .setMessage(R.string.unknown_current_position) + .setCancelable(true) + .setPositiveButton(android.R.string.ok, new Dialog.OnClickListener() + { + @Override + public void onClick(DialogInterface dialog, int which) + { + dialog.dismiss(); + } + }) + .create() + .show(); + } + } + + private void showDownloader(boolean openDownloadedList) + { + if (mIsFragmentContainer) + { + if (getSupportFragmentManager().findFragmentByTag(DownloadFragment.class.getName()) != null) // downloader is already shown + return; + popFragment(); + hidePlacePage(); + SearchToolbarController.cancelSearch(); + mSearchController.refreshToolbar(); + replaceFragment(DownloadFragment.class.getName(), true, new Bundle()); + mFadeView.fadeIn(false); + } + else + { + final Intent intent = new Intent(this, DownloadActivity.class).putExtra(DownloadActivity.EXTRA_OPEN_DOWNLOADED_LIST, openDownloadedList); + startActivity(intent); + } + } + + @Override + public void onCreate(@Nullable Bundle savedInstanceState) + { + super.onCreate(savedInstanceState); + + setContentView(R.layout.activity_map); + initViews(); + + TtsPlayer.INSTANCE.init(); + + if (MwmApplication.get().nativeIsBenchmarking()) + Utils.keepScreenOn(true, getWindow()); + + // TODO consider implementing other model of listeners connection, without activities being bound + Framework.nativeSetRoutingListener(this); + Framework.nativeSetRouteProgressListener(this); + Framework.nativeSetBalloonListener(this); + + final Intent intent = getIntent(); + // We need check for tasks both in onCreate and onNewIntent + // because of bug in OS: https://code.google.com/p/android/issues/detail?id=38629 + addTask(intent); + + if (intent != null && intent.hasExtra(EXTRA_SCREENSHOTS_TASK)) + { + String value = intent.getStringExtra(EXTRA_SCREENSHOTS_TASK); + if (value.equals(SCREENSHOTS_TASK_LOCATE)) + switchNextLocationState(); + } + + mLocationPredictor = new LocationPredictor(new Handler(), this); + mLikesManager = new LikesManager(this); + mSearchController = new SearchToolbarController(this); + + SharingHelper.prepare(); + } + + private void initViews() + { + initMap(); + initYota(); + initPlacePage(); + initRoutingBox(); + initNavigationButtons(); + if (findViewById(R.id.fragment_container) != null) + mIsFragmentContainer = true; + } + + private void initRoutingBox() + { + mLayoutRouting = (RoutingLayout) findViewById(R.id.layout__routing); + mLayoutRouting.setListener(new RoutingLayout.ActionListener() + { + @Override + public void onCloseRouting() + { + refreshZoomButtonsVisibility(); + } + + @Override + public void onStartRouteFollow() {} + + @Override + public void onRouteTypeChange(int type) {} + }); + } + + private void initMap() + { + mFadeView = (FadeView) findViewById(R.id.fade_view); + mFadeView.setFadeListener(new FadeView.FadeListener() + { + @Override + public void onFadeOut() + { + if (mBottomButtons.areButtonsVisible()) + mBottomButtons.slideButtonsOut(); + } + + @Override + public void onFadeIn() + { + + } + }); + mMapFragment = (MapFragment) getSupportFragmentManager().findFragmentByTag(MapFragment.FRAGMENT_TAG); + if (mMapFragment == null) + { + mMapFragment = (MapFragment) MapFragment.instantiate(this, MapFragment.class.getName(), null); + getSupportFragmentManager().beginTransaction(). + replace(R.id.map_fragment_container, mMapFragment, MapFragment.FRAGMENT_TAG).commit(); + } + findViewById(R.id.map_fragment_container).setOnTouchListener(this); + } + + @SuppressWarnings("deprecation") + private void initNavigationButtons() + { + mBottomButtons = (BottomButtonsLayout) findViewById(R.id.map_bottom_buttons); + mBottomButtons.hideButtons(); + mBottomButtons.findViewById(R.id.btn__open_menu).setOnClickListener(this); + mBottomButtons.findViewById(R.id.ll__share).setOnClickListener(this); + mBottomButtons.findViewById(R.id.ll__search).setOnClickListener(this); + mBottomButtons.findViewById(R.id.ll__download_maps).setOnClickListener(this); + mBottomButtons.findViewById(R.id.ll__bookmarks).setOnClickListener(this); + mBottomButtons.findViewById(R.id.ll__settings).setOnClickListener(this); + + mNavigationButtons = (ViewGroup) findViewById(R.id.navigation_buttons); + mBtnZoomIn = (ImageButton) mNavigationButtons.findViewById(R.id.map_button_plus); + mBtnZoomIn.setOnClickListener(this); + mBtnZoomOut = (ImageButton) mNavigationButtons.findViewById(R.id.map_button_minus); + mBtnZoomOut.setOnClickListener(this); + mBtnLocation = (ImageButton) mNavigationButtons.findViewById(R.id.btn__myposition); + mBtnLocation.setOnClickListener(this); + + mToolbarSearch = findViewById(R.id.toolbar_search); + } + + private void initPlacePage() + { + mPlacePage = (PlacePageView) findViewById(R.id.info_box); + mPlacePage.setOnVisibilityChangedListener(this); + mPlacePage.findViewById(R.id.ll__route).setOnClickListener(this); + } + + private void initYota() + { + final View yopmeButton = findViewById(R.id.yop_it); + if (Yota.isFirstYota()) + yopmeButton.setOnClickListener(this); + else + yopmeButton.setVisibility(View.INVISIBLE); + } + + @Override + public void onDestroy() + { + Framework.nativeRemoveBalloonListener(); + BottomSheetHelper.free(); + super.onDestroy(); + } + + @Override + protected void onSaveInstanceState(Bundle outState) + { + if (mPlacePage.getState() != State.HIDDEN) + { + outState.putBoolean(STATE_PP_OPENED, true); + outState.putParcelable(STATE_MAP_OBJECT, mPlacePage.getMapObject()); + } + else if (mBottomButtons.areButtonsVisible()) + outState.putBoolean(STATE_BUTTONS_OPENED, true); + + super.onSaveInstanceState(outState); + } + + @Override + protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) + { + if (savedInstanceState.getBoolean(STATE_PP_OPENED)) + { + mPlacePage.setMapObject((MapObject) savedInstanceState.getParcelable(STATE_MAP_OBJECT)); + mPlacePage.setState(State.PREVIEW); + } + + if (savedInstanceState.getBoolean(STATE_BUTTONS_OPENED)) + { + mFadeView.fadeInInstantly(); + mBottomButtons.showButtons(); + } + + super.onRestoreInstanceState(savedInstanceState); + } + + @Override + protected void onNewIntent(Intent intent) + { + super.onNewIntent(intent); + + if (intent != null) + { + if (intent.hasExtra(EXTRA_TASK)) + addTask(intent); + else if (intent.hasExtra(EXTRA_SET_MAP_STYLE)) + { + final int mapStyle = intent.getIntExtra(EXTRA_SET_MAP_STYLE, Framework.MAP_STYLE_LIGHT); + Framework.setMapStyle(mapStyle); + } + } + } + + private void addTask(Intent intent) + { + if (intent != null + && !intent.getBooleanExtra(EXTRA_CONSUMED, false) + && intent.hasExtra(EXTRA_TASK) + && ((intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0)) + { + final MapTask mapTask = (MapTask) intent.getSerializableExtra(EXTRA_TASK); + mTasks.add(mapTask); + intent.removeExtra(EXTRA_TASK); + + if (mMapFragment.isRenderingInitialized()) + runTasks(); + + // mark intent as consumed + intent.putExtra(EXTRA_CONSUMED, true); + } + } + + @Override + public void onLocationError(int errorCode) + { + mMapFragment.nativeOnLocationError(errorCode); + + // Notify user about turned off location services + if (errorCode == LocationHelper.ERROR_DENIED) + { + LocationState.INSTANCE.turnOff(); + + // Do not show this dialog on Kindle Fire - it doesn't have location services + // and even wifi settings can't be opened programmatically + if (!Utils.isAmazonDevice()) + { + new AlertDialog.Builder(this).setTitle(R.string.location_is_disabled_long_text) + .setPositiveButton(R.string.connection_settings, new DialogInterface.OnClickListener() + { + @Override + public void onClick(DialogInterface dialog, int which) + { + try + { + startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)); + } catch (final Exception e1) + { + // On older Android devices location settings are merged with security + try + { + startActivity(new Intent(android.provider.Settings.ACTION_SECURITY_SETTINGS)); + } catch (final Exception e2) + { + Log.w(TAG, "Can't run activity" + e2); + } + } + + dialog.dismiss(); + } + }) + .setNegativeButton(R.string.close, new DialogInterface.OnClickListener() + { + @Override + public void onClick(DialogInterface dialog, int which) + { + dialog.dismiss(); + } + }) + .create() + .show(); + } + } + else if (errorCode == LocationHelper.ERROR_GPS_OFF) + { + Toast.makeText(this, R.string.gps_is_disabled_long_text, Toast.LENGTH_LONG).show(); + } + } + + @Override + public void onLocationUpdated(final Location l) + { + if (!l.getProvider().equals(LocationHelper.LOCATION_PREDICTOR_PROVIDER)) + mLocationPredictor.reset(l); + + mMapFragment.nativeLocationUpdated( + l.getTime(), + l.getLatitude(), + l.getLongitude(), + l.getAccuracy(), + l.getAltitude(), + l.getSpeed(), + l.getBearing()); + + if (mPlacePage.getState() != State.HIDDEN) + mPlacePage.refreshLocation(l); + + RoutingLayout.State state = mLayoutRouting.getState(); + if (state != RoutingLayout.State.HIDDEN) + { + mLayoutRouting.updateRouteInfo(); + + // TODO think about moving TtsPlayer logic to RoutingLayout to minimize native calls. + if (state == RoutingLayout.State.TURN_INSTRUCTIONS) + { + final String[] turnNotifications = Framework.nativeGenerateTurnSound(); + if (turnNotifications != null) + TtsPlayer.INSTANCE.speakNotifications(turnNotifications); + } + } + } + + @Override + public void onCompassUpdated(long time, double magneticNorth, double trueNorth, double accuracy) + { + final int rotation = getWindowManager().getDefaultDisplay().getRotation(); + magneticNorth = LocationUtils.correctCompassAngle(rotation, magneticNorth); + trueNorth = LocationUtils.correctCompassAngle(rotation, trueNorth); + final double north = (trueNorth >= 0.0) ? trueNorth : magneticNorth; + + mMapFragment.nativeCompassUpdated(time, magneticNorth, trueNorth, accuracy); + if (mPlacePage.getState() != State.HIDDEN) + mPlacePage.refreshAzimuth(north); + + if (mLayoutRouting.getState() != RoutingLayout.State.HIDDEN) + mLayoutRouting.refreshAzimuth(north); + } + + // Callback from native location state mode element processing. + public void onLocationStateModeChangedCallback(final int newMode) + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { + refreshLocationState(newMode); + } + }); + } + + private void refreshLocationState(int newMode) + { + LocationButtonImageSetter.setButtonViewFromState(newMode, mBtnLocation); + switch (newMode) + { + case LocationState.UNKNOWN_POSITION: + pauseLocation(); + break; + case LocationState.PENDING_POSITION: + listenLocationUpdates(); + break; + default: + break; + } + } + + private void listenLocationStateModeUpdates() + { + mLocationStateModeListenerId = LocationState.INSTANCE.addLocationStateModeListener(this); + } + + private void stopWatchingCompassStatusUpdate() + { + LocationState.INSTANCE.removeLocationStateModeListener(mLocationStateModeListenerId); + } + + @Override + protected void onResume() + { + super.onResume(); + + listenLocationStateModeUpdates(); + invalidateLocationState(); + startWatchingExternalStorage(); + mSearchController.refreshToolbar(); + mPlacePage.onResume(); + mLikesManager.showLikeDialogForCurrentSession(); + refreshZoomButtonsAfterLayout(); + } + + private void refreshZoomButtonsAfterLayout() + { + mFadeView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() + { + @SuppressWarnings("deprecation") + @Override + public void onGlobalLayout() + { + refreshZoomButtonsVisibility(); + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) + mFadeView.getViewTreeObserver().removeGlobalOnLayoutListener(this); + else + mFadeView.getViewTreeObserver().removeOnGlobalLayoutListener(this); + } + }); + } + + private void refreshZoomButtonsVisibility() + { + final boolean showZoomSetting = MwmApplication.get().nativeGetBoolean(SettingsActivity.ZOOM_BUTTON_ENABLED, true) || Framework.nativeIsRoutingActive(); + UiUtils.showIf(showZoomSetting && + !UiUtils.areViewsIntersecting(mToolbarSearch, mBtnZoomIn) && + !UiUtils.areViewsIntersecting(mLayoutRouting, mBtnZoomIn), + mBtnZoomIn, mBtnZoomOut); + } + + @Override + protected void onPause() + { + pauseLocation(); + stopWatchingExternalStorage(); + stopWatchingCompassStatusUpdate(); + TtsPlayer.INSTANCE.stop(); + super.onPause(); + mLikesManager.cancelLikeDialog(); + } + + private void updateExternalStorageState() + { + boolean available = false, writable = false; + final String state = Environment.getExternalStorageState(); + if (Environment.MEDIA_MOUNTED.equals(state)) + available = writable = true; + else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) + available = true; + + if (mStorageAvailable != available || mStorageWritable != writable) + { + mStorageAvailable = available; + mStorageWritable = writable; + handleExternalStorageState(available, writable); + } + } + + private void handleExternalStorageState(boolean available, boolean writeable) + { + if (available && writeable) + { + // Add local maps to the model + mMapFragment.nativeStorageConnected(); + + // @TODO enable downloader button and dismiss blocking popup + + if (mStorageDisconnectedDialog != null) + mStorageDisconnectedDialog.dismiss(); + } + else if (available) + { + // Add local maps to the model + mMapFragment.nativeStorageConnected(); + + // @TODO disable downloader button and dismiss blocking popup + + if (mStorageDisconnectedDialog != null) + mStorageDisconnectedDialog.dismiss(); + } + else + { + // Remove local maps from the model + mMapFragment.nativeStorageDisconnected(); + + // @TODO enable downloader button and show blocking popup + + if (mStorageDisconnectedDialog == null) + { + mStorageDisconnectedDialog = new AlertDialog.Builder(this) + .setTitle(R.string.external_storage_is_not_available) + .setMessage(getString(R.string.disconnect_usb_cable)) + .setCancelable(false) + .create(); + } + mStorageDisconnectedDialog.show(); + } + } + + private void startWatchingExternalStorage() + { + mExternalStorageReceiver = new BroadcastReceiver() + { + @Override + public void onReceive(Context context, Intent intent) + { + updateExternalStorageState(); + } + }; + + registerReceiver(mExternalStorageReceiver, StoragePathManager.getMediaChangesIntentFilter()); + updateExternalStorageState(); + } + + private void stopWatchingExternalStorage() + { + mPathManager.stopExternalStorageWatching(); + if (mExternalStorageReceiver != null) + { + unregisterReceiver(mExternalStorageReceiver); + mExternalStorageReceiver = null; + } + } + + @Override + public void onBackPressed() + { + if (mPlacePage.getState() != State.HIDDEN) + { + hidePlacePage(); + Framework.deactivatePopup(); + } + else if (mBottomButtons.areButtonsVisible()) + { + mBottomButtons.toggle(); + mFadeView.fadeOut(false); + } + else if (canFragmentInterceptBackPress()) + return; + else if (popFragment()) + { + InputUtils.hideKeyboard(mFadeView); + mFadeView.fadeOut(false); + } + else + super.onBackPressed(); + } + + private boolean isMapFaded() + { + return mFadeView.getVisibility() == View.VISIBLE; + } + + private boolean canFragmentInterceptBackPress() + { + final FragmentManager manager = getSupportFragmentManager(); + DownloadFragment fragment = (DownloadFragment) manager.findFragmentByTag(DownloadFragment.class.getName()); + return fragment != null && fragment.isResumed() && fragment.onBackPressed(); + } + + private boolean popFragment() + { + for (String tag : new String[]{SearchFragment.class.getName(), DownloadFragment.class.getName()}) + if (popFragment(tag)) + return true; + + return false; + } + + private void popAllFragments() + { + for (String tag : new String[]{SearchFragment.class.getName(), DownloadFragment.class.getName()}) + popFragment(tag); + } + + private boolean popFragment(String className) + { + final FragmentManager manager = getSupportFragmentManager(); + Fragment fragment = manager.findFragmentByTag(className); + // TODO d.yunitsky + // we cant pop fragment, if it isn't resumed, cause of 'at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1375)' + if (fragment != null && fragment.isResumed()) + { + manager.popBackStackImmediate(); + return true; + } + + return false; + } + + // Callbacks from native map objects touch event. + @Override + public void onApiPointActivated(final double lat, final double lon, final String name, final String id) + { + if (ParsedMwmRequest.hasRequest()) + { + final ParsedMwmRequest request = ParsedMwmRequest.getCurrentRequest(); + request.setPointData(lat, lon, name, id); + + runOnUiThread(new Runnable() + { + @Override + public void run() + { + final String poiType = ParsedMwmRequest.getCurrentRequest().getCallerName(MwmApplication.get()).toString(); + activateMapObject(new ApiPoint(name, id, poiType, lat, lon)); + } + }); + } + } + + @Override + public void onPoiActivated(final String name, final String type, final String address, final double lat, final double lon, + final int[] metaTypes, final String[] metaValues) + { + final MapObject poi = new MapObject.Poi(name, lat, lon, type); + poi.addMetadata(metaTypes, metaValues); + + runOnUiThread(new Runnable() + { + @Override + public void run() + { + activateMapObject(poi); + } + }); + } + + @Override + public void onBookmarkActivated(final int category, final int bookmarkIndex) + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { + activateMapObject(BookmarkManager.INSTANCE.getBookmark(category, bookmarkIndex)); + } + }); + } + + @Override + public void onMyPositionActivated(final double lat, final double lon) + { + final MapObject mypos = new MapObject.MyPosition(getString(R.string.my_position), lat, lon); + + runOnUiThread(new Runnable() + { + @Override + public void run() + { + if (!Framework.nativeIsRoutingActive()) + { + activateMapObject(mypos); + } + } + }); + } + + @Override + public void onAdditionalLayerActivated(final String name, final String type, final double lat, final double lon, final int[] metaTypes, final String[] metaValues) + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { + final MapObject sr = new MapObject.SearchResult(name, type, lat, lon); + sr.addMetadata(metaTypes, metaValues); + activateMapObject(sr); + } + }); + } + + private void activateMapObject(MapObject object) + { + mPlacePage.bringToFront(); + if (!mPlacePage.hasMapObject(object)) + { + mPlacePage.setMapObject(object); + mPlacePage.setState(State.PREVIEW); + popAllFragments(); + if (isMapFaded()) + mFadeView.fadeOut(false); + } + } + + private void hidePlacePage() + { + mPlacePage.setState(State.HIDDEN); + mPlacePage.setMapObject(null); + } + + @Override + public void onDismiss() + { + if (!mPlacePage.hasMapObject(null)) + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { + hidePlacePage(); + Framework.deactivatePopup(); + } + }); + } + } + + @Override + public void onPreviewVisibilityChanged(boolean isVisible) + { + if (isVisible) + { + if (previewIntersectsBottomMenu()) + mBottomButtons.setVisibility(View.GONE); + if (previewIntersectsZoomButtons()) + UiUtils.hide(mBtnZoomIn, mBtnZoomOut); + } + else + { + Framework.deactivatePopup(); + mPlacePage.setMapObject(null); + refreshZoomButtonsVisibility(); + mBottomButtons.setVisibility(View.VISIBLE); + } + } + + private boolean previewIntersectsBottomMenu() + { + return !(UiUtils.isBigTablet() || (UiUtils.isSmallTablet() && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)); + } + + private boolean previewIntersectsZoomButtons() + { + return !(UiUtils.isBigTablet() || UiUtils.isSmallTablet()); + } + + @Override + public void onPlacePageVisibilityChanged(boolean isVisible) + { + if (isVisible) + { + AlohaHelper.logClick(AlohaHelper.PP_OPEN); + if (placePageIntersectsZoomButtons()) + UiUtils.hide(mBtnZoomIn, mBtnZoomOut); + else + refreshZoomButtonsVisibility(); + } + else + AlohaHelper.logClick(AlohaHelper.PP_CLOSE); + } + + private boolean placePageIntersectsZoomButtons() + { + return !(UiUtils.isBigTablet() || (UiUtils.isSmallTablet() && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)); + } + + @Override + public void onClick(View v) + { + switch (v.getId()) + { + case R.id.ll__share: + AlohaHelper.logClick(AlohaHelper.MENU_SHARE); + shareMyLocation(); + mBottomButtons.hideButtons(); + UiUtils.hide(mFadeView); + UiUtils.clearAnimationAfterAlpha(mFadeView); + break; + case R.id.ll__settings: + AlohaHelper.logClick(AlohaHelper.MENU_SETTINGS); + startActivity(new Intent(this, SettingsActivity.class)); + mBottomButtons.hideButtons(); + UiUtils.hide(mFadeView); + UiUtils.clearAnimationAfterAlpha(mFadeView); + break; + case R.id.ll__download_maps: + AlohaHelper.logClick(AlohaHelper.MENU_DOWNLOADER); + showDownloader(false); + mBottomButtons.hideButtons(); + UiUtils.hide(mFadeView); + UiUtils.clearAnimationAfterAlpha(mFadeView); + break; + case R.id.ll__route: + AlohaHelper.logClick(AlohaHelper.PP_ROUTE); + mLayoutRouting.setEndPoint(mPlacePage.getMapObject()); + mLayoutRouting.setState(RoutingLayout.State.PREPARING, true); + mPlacePage.setState(PlacePageView.State.HIDDEN); + break; + case R.id.map_button_plus: + AlohaHelper.logClick(AlohaHelper.ZOOM_IN); + mMapFragment.nativeScale(3.0 / 2); + break; + case R.id.map_button_minus: + AlohaHelper.logClick(AlohaHelper.ZOOM_OUT); + mMapFragment.nativeScale(2 / 3.0); + break; + case R.id.btn__open_menu: + AlohaHelper.logClick(AlohaHelper.TOOLBAR_MENU); + mFadeView.fadeIn(false); + mBottomButtons.toggle(); + break; + case R.id.ll__search: + AlohaHelper.logClick(AlohaHelper.TOOLBAR_SEARCH); + showSearchIfContainsSearchIndex(); + mBottomButtons.hideButtons(); + UiUtils.hide(mFadeView); + UiUtils.clearAnimationAfterAlpha(mFadeView); + break; + case R.id.ll__bookmarks: + AlohaHelper.logClick(AlohaHelper.TOOLBAR_BOOKMARKS); + showBookmarks(); + mBottomButtons.hideButtons(); + UiUtils.hide(mFadeView); + UiUtils.clearAnimationAfterAlpha(mFadeView); + break; + case R.id.btn__myposition: + switchNextLocationState(); + break; + case R.id.yop_it: + final double[] latLon = Framework.getScreenRectCenter(); + final double zoom = Framework.getDrawScale(); + + final int locationStateMode = LocationState.INSTANCE.getLocationStateMode(); + + if (locationStateMode > LocationState.NOT_FOLLOW) + Yota.showLocation(getApplicationContext(), zoom); + else + Yota.showMap(getApplicationContext(), latLon[0], latLon[1], zoom, null, locationStateMode == LocationState.NOT_FOLLOW); + + Statistics.INSTANCE.trackBackscreenCall("Map"); + break; + default: + break; + } + } + + private void closeRouting() + { + + mLayoutRouting.setState(RoutingLayout.State.HIDDEN, true); + } + + private static void switchNextLocationState() + { + LocationState.INSTANCE.switchToNextMode(); + } + + @Override + public boolean onTouch(View view, MotionEvent event) + { + boolean result = false; + if (mPlacePage.getState() == State.DETAILS || mPlacePage.getState() == State.BOOKMARK) + { + Framework.deactivatePopup(); + hidePlacePage(); + result = true; + } + + return result || mMapFragment.onTouch(view, event); + } + + @Override + public boolean onKeyUp(int keyCode, @NonNull KeyEvent event) + { + if (keyCode == KeyEvent.KEYCODE_MENU) + { + if (mBottomButtons.areButtonsVisible()) + mFadeView.fadeOut(false); + else + mFadeView.fadeIn(false); + mBottomButtons.toggle(); + return true; + } + return super.onKeyUp(keyCode, event); + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) + { + if (resultCode == RESULT_OK && requestCode == ChooseBookmarkCategoryActivity.REQUEST_CODE_BOOKMARK_SET) + { + final Point bookmarkAndCategory = ((ParcelablePoint) data.getParcelableExtra(ChooseBookmarkCategoryActivity.BOOKMARK)).getPoint(); + final Bookmark bookmark = BookmarkManager.INSTANCE.getBookmark(bookmarkAndCategory.x, bookmarkAndCategory.y); + mPlacePage.setMapObject(bookmark); + } + super.onActivityResult(requestCode, resultCode, data); + } + + @Override + public void onRoutingEvent(final int resultCode, final Index[] missingCountries) + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { + if (resultCode == RoutingResultCodesProcessor.NO_ERROR) + { + mLayoutRouting.setState(RoutingLayout.State.ROUTE_BUILT, true); + } + else + { + mLayoutRouting.setState(RoutingLayout.State.ROUTE_BUILD_ERROR, true); + final Bundle args = new Bundle(); + args.putInt(RoutingErrorDialogFragment.EXTRA_RESULT_CODE, resultCode); + args.putSerializable(RoutingErrorDialogFragment.EXTRA_MISSING_COUNTRIES, missingCountries); + final RoutingErrorDialogFragment fragment = (RoutingErrorDialogFragment) Fragment.instantiate(MwmActivity.this, RoutingErrorDialogFragment.class.getName()); + fragment.setArguments(args); + fragment.setListener(new RoutingErrorDialogFragment.RoutingDialogListener() + { + @Override + public void onDownload() + { + mLayoutRouting.setState(RoutingLayout.State.HIDDEN, false); + refreshZoomButtonsVisibility(); + ActiveCountryTree.downloadMapsForIndex(missingCountries, StorageOptions.MAP_OPTION_MAP_AND_CAR_ROUTING); + showDownloader(true); + } + + @Override + public void onCancel() + { + refreshZoomButtonsVisibility(); + } + + @Override + public void onOk() + { + if (RoutingResultCodesProcessor.isDownloadable(resultCode)) + { + mLayoutRouting.setState(RoutingLayout.State.HIDDEN, false); + refreshZoomButtonsVisibility(); + showDownloader(false); + } + } + }); + fragment.show(getSupportFragmentManager(), RoutingErrorDialogFragment.class.getName()); + } + + refreshZoomButtonsVisibility(); + } + }); + } + + @Override + public void onRouteBuildingProgress(final float progress) + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { + mLayoutRouting.setRouteBuildingProgress(progress); + } + }); + } + + @Override + public void customOnNavigateUp() + { + if (popFragment()) + { + InputUtils.hideKeyboard(mBottomButtons); + mSearchController.refreshToolbar(); + } + } + + public interface MapTask extends Serializable + { + boolean run(MwmActivity target); + } + + public static class OpenUrlTask implements MapTask + { + private static final long serialVersionUID = 1L; + private final String mUrl; + + public OpenUrlTask(String url) + { + Utils.checkNotNull(url); + mUrl = url; + } + + @Override + public boolean run(MwmActivity target) + { + return target.mMapFragment.showMapForUrl(mUrl); + } + } + + public static class ShowCountryTask implements MapTask + { + private static final long serialVersionUID = 1L; + private final Index mIndex; + private final boolean mDoAutoDownload; + + public ShowCountryTask(Index index, boolean doAutoDownload) + { + mIndex = index; + mDoAutoDownload = doAutoDownload; + } + + @Override + public boolean run(MwmActivity target) + { + if (mDoAutoDownload) + { + Framework.downloadCountry(mIndex); + // set zoom level so that download process is visible + Framework.nativeShowCountry(mIndex, true); + } + else + Framework.nativeShowCountry(mIndex, false); + + return true; + } + } + + public static class UpdateCountryTask implements MapTask + { + @Override + public boolean run(final MwmActivity target) + { + target.runOnUiThread(new Runnable() + { + @Override + public void run() + { + target.showDownloader(true); + } + }); + return true; + } + } +} diff --git a/android/src/com/mapswithme/maps/MwmApplication.java b/android/src/com/mapswithme/maps/MwmApplication.java new file mode 100644 index 0000000000..949805c664 --- /dev/null +++ b/android/src/com/mapswithme/maps/MwmApplication.java @@ -0,0 +1,346 @@ +package com.mapswithme.maps; + +import android.content.SharedPreferences; +import android.content.pm.PackageManager.NameNotFoundException; +import android.os.Environment; +import android.preference.PreferenceManager; +import android.text.TextUtils; +import android.text.format.DateUtils; +import android.util.Log; + +import com.google.gsonaltered.Gson; +import com.mapswithme.country.ActiveCountryTree; +import com.mapswithme.country.CountryItem; +import com.mapswithme.maps.background.Notifier; +import com.mapswithme.maps.bookmarks.data.BookmarkManager; +import com.mapswithme.util.Constants; +import com.mapswithme.util.UiUtils; +import com.mapswithme.util.Yota; +import com.mapswithme.util.statistics.AlohaHelper; +import com.parse.Parse; +import com.parse.ParseException; +import com.parse.ParseInstallation; +import com.parse.SaveCallback; + +import java.io.File; +import java.util.HashMap; +import java.util.Map; + +import ru.mail.android.mytracker.MRMyTracker; +import ru.mail.android.mytracker.MRMyTrackerParams; + +public class MwmApplication extends android.app.Application implements ActiveCountryTree.ActiveCountryListener +{ + private final static String TAG = "MwmApplication"; + private static final String FOREGROUND_TIME_SETTING = "AllForegroundTime"; + private static final String LAUNCH_NUMBER_SETTING = "LaunchNumber"; // total number of app launches + private static final String SESSION_NUMBER_SETTING = "SessionNumber"; // session = number of days, when app was launched + private static final String LAST_SESSION_TIMESTAMP_SETTING = "LastSessionTimestamp"; // timestamp of last session + private static final String FIRST_INSTALL_VERSION = "FirstInstallVersion"; + private static final String FIRST_INSTALL_FLAVOR = "FirstInstallFlavor"; + // for myTracker + private static final String MY_MAP_DOWNLOAD = "DownloadMap"; + private static final String MY_MAP_UPDATE = "UpdateMap"; + private static final String MY_TOTAL_COUNT = "Count"; + // Parse + private static final String PREF_PARSE_DEVICE_TOKEN = "ParseDeviceToken"; + private static final String PREF_PARSE_INSTALLATION_ID = "ParseInstallationId"; + + private static MwmApplication mSelf; + private final Gson mGson = new Gson(); + + private boolean mAreStatsInitialised; + + public MwmApplication() + { + super(); + mSelf = this; + } + + public static MwmApplication get() + { + return mSelf; + } + + public static Gson gson() + { + return mSelf.mGson; + } + + @Override + public void onCountryProgressChanged(int group, int position, long[] sizes) {} + + @Override + public void onCountryStatusChanged(int group, int position, int oldStatus, int newStatus) + { + Notifier.cancelDownloadSuggest(); + if (newStatus == MapStorage.DOWNLOAD_FAILED) + { + CountryItem item = ActiveCountryTree.getCountryItem(group, position); + Notifier.placeDownloadFailed(ActiveCountryTree.getCoreIndex(group, position), item.getName()); + } + } + + @Override + public void onCountryGroupChanged(int oldGroup, int oldPosition, int newGroup, int newPosition) + { + if (oldGroup == ActiveCountryTree.GROUP_NEW && newGroup == ActiveCountryTree.GROUP_UP_TO_DATE) + myTrackerTrackMapChange(MY_MAP_DOWNLOAD); + else if (oldGroup == ActiveCountryTree.GROUP_OUT_OF_DATE && newGroup == ActiveCountryTree.GROUP_UP_TO_DATE) + myTrackerTrackMapChange(MY_MAP_UPDATE); + } + + private void myTrackerTrackMapChange(String eventType) + { + final Map params = new HashMap<>(); + params.put(MY_TOTAL_COUNT, String.valueOf(ActiveCountryTree.getTotalDownloadedCount())); + MRMyTracker.trackEvent(eventType, params); + } + + @Override + public void onCountryOptionsChanged(int group, int position, int newOptions, int requestOptions) + { + CountryItem item = ActiveCountryTree.getCountryItem(group, position); + if (item.getStatus() != MapStorage.ON_DISK) + return; + + if (newOptions == requestOptions) + Notifier.placeDownloadCompleted(ActiveCountryTree.getCoreIndex(group, position), item.getName()); + } + + @Override + public void onCreate() + { + super.onCreate(); + + final String extStoragePath = getDataStoragePath(); + final String extTmpPath = getTempPath(); + + // Create folders if they don't exist + new File(extStoragePath).mkdirs(); + new File(extTmpPath).mkdirs(); + + // init native framework + nativeInit(getApkPath(), extStoragePath, extTmpPath, getOBBGooglePath(), + BuildConfig.FLAVOR, BuildConfig.BUILD_TYPE, + Yota.isFirstYota(), UiUtils.isSmallTablet() || UiUtils.isBigTablet()); + + ActiveCountryTree.addListener(this); + + // init cross-platform strings bundle + nativeAddLocalization("country_status_added_to_queue", getString(R.string.country_status_added_to_queue)); + nativeAddLocalization("country_status_downloading", getString(R.string.country_status_downloading)); + nativeAddLocalization("country_status_download", getString(R.string.country_status_download)); + nativeAddLocalization("country_status_download_without_routing", getString(R.string.country_status_download_without_routing)); + nativeAddLocalization("country_status_download_failed", getString(R.string.country_status_download_failed)); + nativeAddLocalization("try_again", getString(R.string.try_again)); + nativeAddLocalization("not_enough_free_space_on_sdcard", getString(R.string.not_enough_free_space_on_sdcard)); + nativeAddLocalization("dropped_pin", getString(R.string.dropped_pin)); + nativeAddLocalization("my_places", getString(R.string.my_places)); + nativeAddLocalization("my_position", getString(R.string.my_position)); + nativeAddLocalization("routes", getString(R.string.routes)); + + nativeAddLocalization("routing_failed_unknown_my_position", getString(R.string.routing_failed_unknown_my_position)); + nativeAddLocalization("routing_failed_has_no_routing_file", getString(R.string.routing_failed_has_no_routing_file)); + nativeAddLocalization("routing_failed_start_point_not_found", getString(R.string.routing_failed_start_point_not_found)); + nativeAddLocalization("routing_failed_dst_point_not_found", getString(R.string.routing_failed_dst_point_not_found)); + nativeAddLocalization("routing_failed_cross_mwm_building", getString(R.string.routing_failed_cross_mwm_building)); + nativeAddLocalization("routing_failed_route_not_found", getString(R.string.routing_failed_route_not_found)); + nativeAddLocalization("routing_failed_internal_error", getString(R.string.routing_failed_internal_error)); + + // init BookmarkManager (automatically loads bookmarks) + BookmarkManager.getIcons(); + + initParse(); + } + + private void initMyTracker() + { + MRMyTracker.setDebugMode(BuildConfig.DEBUG); + + MRMyTracker.createTracker(getString(R.string.my_tracker_app_id), this); + + final MRMyTrackerParams myParams = MRMyTracker.getTrackerParams(); + myParams.setTrackingPreinstallsEnabled(true); + myParams.setTrackingLaunchEnabled(true); + + MRMyTracker.initTracker(); + } + + public String getApkPath() + { + try + { + return getPackageManager().getApplicationInfo(BuildConfig.APPLICATION_ID, 0).sourceDir; + } catch (final NameNotFoundException e) + { + Log.e(TAG, "Can't get apk path from PackageManager"); + return ""; + } + } + + public String getDataStoragePath() + { + return Environment.getExternalStorageDirectory().getAbsolutePath() + Constants.MWM_DIR_POSTFIX; + } + + public String getTempPath() + { + // TODO refactor + // Can't use getExternalCacheDir() here because of API level = 7. + return getExtAppDirectoryPath(Constants.CACHE_DIR); + } + + public String getExtAppDirectoryPath(String folder) + { + final String storagePath = Environment.getExternalStorageDirectory().getAbsolutePath(); + return storagePath.concat(String.format(Constants.STORAGE_PATH, BuildConfig.APPLICATION_ID, folder)); + } + + private String getOBBGooglePath() + { + final String storagePath = Environment.getExternalStorageDirectory().getAbsolutePath(); + return storagePath.concat(String.format(Constants.OBB_PATH, BuildConfig.APPLICATION_ID)); + } + + // Check if we have free space on storage (writable path). + public native boolean hasFreeSpace(long size); + + public double getForegroundTime() + { + return nativeGetDouble(FOREGROUND_TIME_SETTING, 0); + } + + static + { + System.loadLibrary("mapswithme"); + } + + private native void nativeInit(String apkPath, String storagePath, + String tmpPath, String obbGooglePath, + String flavorName, String buildType, + boolean isYota, boolean isTablet); + + public native boolean nativeIsBenchmarking(); + + private native void nativeAddLocalization(String name, String value); + + // Dealing with Settings + public native boolean nativeGetBoolean(String name, boolean defaultValue); + + public native void nativeSetBoolean(String name, boolean value); + + public native int nativeGetInt(String name, int defaultValue); + + public native void nativeSetInt(String name, int value); + + public native long nativeGetLong(String name, long defaultValue); + + public native void nativeSetLong(String name, long value); + + public native double nativeGetDouble(String name, double defaultValue); + + public native void nativeSetDouble(String name, double value); + + public native String nativeGetString(String name, String defaultValue); + + public native void nativeSetString(String name, String value); + + /* + * init Parse SDK + */ + private void initParse() + { + Parse.initialize(this, "***REMOVED***", "***REMOVED***"); + ParseInstallation.getCurrentInstallation().saveInBackground(new SaveCallback() + { + @Override + public void done(ParseException e) + { + SharedPreferences prefs = getSharedPreferences(getString(R.string.pref_file_name), MODE_PRIVATE); + String previousId = prefs.getString(PREF_PARSE_INSTALLATION_ID, ""); + String previousToken = prefs.getString(PREF_PARSE_DEVICE_TOKEN, ""); + + String newId = ParseInstallation.getCurrentInstallation().getInstallationId(); + String newToken = ParseInstallation.getCurrentInstallation().getString("deviceToken"); + if (previousId.equals(newId) || previousToken.equals(newToken)) + { + org.alohalytics.Statistics.logEvent(AlohaHelper.PARSE_INSTALLATION_ID, newId); + org.alohalytics.Statistics.logEvent(AlohaHelper.PARSE_DEVICE_TOKEN, newToken); + prefs.edit() + .putString(PREF_PARSE_INSTALLATION_ID, newId) + .putString(PREF_PARSE_DEVICE_TOKEN, newToken).apply(); + } + } + }); + } + + public void initStats() + { + if (!mAreStatsInitialised) + { + mAreStatsInitialised = true; + updateLaunchNumbers(); + updateSessionsNumber(); + initMyTracker(); + PreferenceManager.setDefaultValues(this, R.xml.preferences, false); + + org.alohalytics.Statistics.setDebugMode(BuildConfig.DEBUG); + org.alohalytics.Statistics.setup(BuildConfig.STATISTICS_URL, this); + } + } + + private void updateLaunchNumbers() + { + final int currentLaunches = nativeGetInt(LAUNCH_NUMBER_SETTING, 0); + if (currentLaunches == 0) + { + nativeSetInt(FIRST_INSTALL_VERSION, BuildConfig.VERSION_CODE); + + final String installedFlavor = getFirstInstallFlavor(); + if (TextUtils.isEmpty(installedFlavor)) + nativeSetString(FIRST_INSTALL_FLAVOR, BuildConfig.FLAVOR); + } + + nativeSetInt(LAUNCH_NUMBER_SETTING, currentLaunches + 1); + } + + private void updateSessionsNumber() + { + final int sessionNum = nativeGetInt(SESSION_NUMBER_SETTING, 0); + final long lastSessionTimestamp = nativeGetLong(LAST_SESSION_TIMESTAMP_SETTING, 0); + if (!DateUtils.isToday(lastSessionTimestamp)) + { + nativeSetInt(SESSION_NUMBER_SETTING, sessionNum + 1); + nativeSetLong(LAST_SESSION_TIMESTAMP_SETTING, System.currentTimeMillis()); + } + } + + /** + * @return total number of application launches + */ + public int getLaunchesNumber() + { + return nativeGetInt(LAUNCH_NUMBER_SETTING, 0); + } + + /** + * Session = single day, when app was started any number of times. + * + * @return number of sessions. + */ + public int getSessionsNumber() + { + return nativeGetInt(SESSION_NUMBER_SETTING, 0); + } + + public int getFirstInstallVersion() + { + return nativeGetInt(FIRST_INSTALL_VERSION, 0); + } + + public String getFirstInstallFlavor() + { + return nativeGetString(FIRST_INSTALL_FLAVOR, ""); + } +} diff --git a/android/src/com/mapswithme/maps/ads/LikesManager.java b/android/src/com/mapswithme/maps/ads/LikesManager.java index 9edc72331c..ee8c939faf 100644 --- a/android/src/com/mapswithme/maps/ads/LikesManager.java +++ b/android/src/com/mapswithme/maps/ads/LikesManager.java @@ -5,7 +5,7 @@ import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentActivity; import com.mapswithme.maps.BuildConfig; -import com.mapswithme.maps.MWMApplication; +import com.mapswithme.maps.MwmApplication; import com.mapswithme.util.ConnectionState; import java.lang.ref.WeakReference; @@ -65,7 +65,7 @@ public class LikesManager private static final long DIALOG_DELAY_MILLIS = 30000; - private final boolean mIsNewUser = MWMApplication.get().getFirstInstallVersion() == BuildConfig.VERSION_CODE; + private final boolean mIsNewUser = MwmApplication.get().getFirstInstallVersion() == BuildConfig.VERSION_CODE; private final int mSessionNum; private Handler mHandler; @@ -80,7 +80,7 @@ public class LikesManager mHandler = new Handler(activity.getMainLooper()); mActivityRef = new WeakReference<>(activity); - mSessionNum = MWMApplication.get().getSessionsNumber(); + mSessionNum = MwmApplication.get().getSessionsNumber(); } public void showLikeDialogForCurrentSession() @@ -134,21 +134,21 @@ public class LikesManager public static boolean isSessionRated(int sessionNum) { - return MWMApplication.get().nativeGetInt(LAST_RATED_SESSION, 0) >= sessionNum; + return MwmApplication.get().nativeGetInt(LAST_RATED_SESSION, 0) >= sessionNum; } public static void setSessionRated(int sessionNum) { - MWMApplication.get().nativeSetInt(LAST_RATED_SESSION, sessionNum); + MwmApplication.get().nativeSetInt(LAST_RATED_SESSION, sessionNum); } public static boolean isRatingApplied(final Class dialogFragmentClass) { - return MWMApplication.get().nativeGetBoolean(RATED_DIALOG + dialogFragmentClass.getSimpleName(), false); + return MwmApplication.get().nativeGetBoolean(RATED_DIALOG + dialogFragmentClass.getSimpleName(), false); } public static void setRatingApplied(final Class dialogFragmentClass, boolean applied) { - MWMApplication.get().nativeSetBoolean(RATED_DIALOG + dialogFragmentClass.getSimpleName(), applied); + MwmApplication.get().nativeSetBoolean(RATED_DIALOG + dialogFragmentClass.getSimpleName(), applied); } } diff --git a/android/src/com/mapswithme/maps/ads/RateStoreDialogFragment.java b/android/src/com/mapswithme/maps/ads/RateStoreDialogFragment.java index 4db952dd8e..78443fe498 100644 --- a/android/src/com/mapswithme/maps/ads/RateStoreDialogFragment.java +++ b/android/src/com/mapswithme/maps/ads/RateStoreDialogFragment.java @@ -17,7 +17,7 @@ import android.widget.RatingBar; import android.widget.TextView; import com.mapswithme.maps.BuildConfig; -import com.mapswithme.maps.MWMApplication; +import com.mapswithme.maps.MwmApplication; import com.mapswithme.maps.R; import com.mapswithme.maps.base.BaseMwmDialogFragment; import com.mapswithme.util.Constants; @@ -112,7 +112,7 @@ public class RateStoreDialogFragment extends BaseMwmDialogFragment implements Vi long installTime = 0; try { - info = MWMApplication.get().getPackageManager().getPackageInfo(BuildConfig.APPLICATION_ID, 0); + info = MwmApplication.get().getPackageManager().getPackageInfo(BuildConfig.APPLICATION_ID, 0); installTime = info.firstInstallTime; } catch (PackageManager.NameNotFoundException e) { diff --git a/android/src/com/mapswithme/maps/background/Notifier.java b/android/src/com/mapswithme/maps/background/Notifier.java index c124540e10..f4ef441082 100644 --- a/android/src/com/mapswithme/maps/background/Notifier.java +++ b/android/src/com/mapswithme/maps/background/Notifier.java @@ -1,28 +1,19 @@ package com.mapswithme.maps.background; -import android.app.Activity; -import android.app.AlarmManager; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; -import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; -import android.net.Uri; import android.support.v4.app.NotificationCompat; -import com.mapswithme.maps.BuildConfig; -import com.mapswithme.maps.MWMActivity; -import com.mapswithme.maps.MWMApplication; +import com.mapswithme.maps.MwmActivity; +import com.mapswithme.maps.MwmApplication; import com.mapswithme.maps.MapStorage.Index; import com.mapswithme.maps.R; -import com.mapswithme.util.UiUtils; -import com.mapswithme.util.Utils; import com.mapswithme.util.statistics.Statistics; -import java.util.Calendar; - public class Notifier { private final static int ID_UPDATE_AVAIL = 0x1; @@ -42,21 +33,21 @@ public class Notifier public static NotificationCompat.Builder getBuilder() { - return new NotificationCompat.Builder(MWMApplication.get()) + return new NotificationCompat.Builder(MwmApplication.get()) .setAutoCancel(true) .setSmallIcon(R.drawable.ic_notification); } private static NotificationManager getNotificationManager() { - return (NotificationManager) MWMApplication.get().getSystemService(Context.NOTIFICATION_SERVICE); + return (NotificationManager) MwmApplication.get().getSystemService(Context.NOTIFICATION_SERVICE); } public static void placeUpdateAvailable(String forWhat) { - final String title = MWMApplication.get().getString(R.string.advise_update_maps); + final String title = MwmApplication.get().getString(R.string.advise_update_maps); - final PendingIntent pi = PendingIntent.getActivity(MWMApplication.get(), 0, MWMActivity.createUpdateMapsIntent(), + final PendingIntent pi = PendingIntent.getActivity(MwmApplication.get(), 0, MwmActivity.createUpdateMapsIntent(), PendingIntent.FLAG_UPDATE_CURRENT); final Notification notification = Notifier.getBuilder() @@ -72,8 +63,8 @@ public class Notifier public static void placeDownloadCompleted(Index idx, String name) { - final String title = MWMApplication.get().getString(R.string.app_name); - final String content = MWMApplication.get().getString(R.string.download_country_success, name); + final String title = MwmApplication.get().getString(R.string.app_name); + final String content = MwmApplication.get().getString(R.string.download_country_success, name); // TODO add complex stacked notification with progress, number of countries and other info. // placeDownloadNotification(title, content, idx); @@ -81,16 +72,16 @@ public class Notifier public static void placeDownloadFailed(Index idx, String name) { - final String title = MWMApplication.get().getString(R.string.app_name); - final String content = MWMApplication.get().getString(R.string.download_country_failed, name); + final String title = MwmApplication.get().getString(R.string.app_name); + final String content = MwmApplication.get().getString(R.string.download_country_failed, name); placeDownloadNotification(title, content, idx); } private static void placeDownloadNotification(String title, String content, Index idx) { - final PendingIntent pi = PendingIntent.getActivity(MWMApplication.get(), 0, - MWMActivity.createShowMapIntent(MWMApplication.get(), idx, false).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK), + final PendingIntent pi = PendingIntent.getActivity(MwmApplication.get(), 0, + MwmActivity.createShowMapIntent(MwmApplication.get(), idx, false).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK), PendingIntent.FLAG_UPDATE_CURRENT); final Notification notification = getBuilder() @@ -105,8 +96,8 @@ public class Notifier public static void placeDownloadSuggest(String title, String content, Index countryIndex) { - final PendingIntent pi = PendingIntent.getActivity(MWMApplication.get(), 0, - MWMActivity.createShowMapIntent(MWMApplication.get(), countryIndex, true).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK), + final PendingIntent pi = PendingIntent.getActivity(MwmApplication.get(), 0, + MwmActivity.createShowMapIntent(MwmApplication.get(), countryIndex, true).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK), PendingIntent.FLAG_UPDATE_CURRENT); final Notification notification = getBuilder() diff --git a/android/src/com/mapswithme/maps/base/BaseMwmFragmentActivity.java b/android/src/com/mapswithme/maps/base/BaseMwmFragmentActivity.java index 15fdd1d8c5..790fa6f078 100644 --- a/android/src/com/mapswithme/maps/base/BaseMwmFragmentActivity.java +++ b/android/src/com/mapswithme/maps/base/BaseMwmFragmentActivity.java @@ -8,7 +8,7 @@ import android.support.v7.widget.Toolbar; import android.view.MenuItem; import com.mapswithme.util.ViewServer; -import com.mapswithme.maps.MWMApplication; +import com.mapswithme.maps.MwmApplication; import com.mapswithme.maps.R; import com.mapswithme.util.Utils; import com.mapswithme.util.statistics.Statistics; @@ -32,7 +32,7 @@ public class BaseMwmFragmentActivity extends AppCompatActivity getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); } - MWMApplication.get().initStats(); + MwmApplication.get().initStats(); ViewServer.get(this).addWindow(this); attachDefaultFragment(); diff --git a/android/src/com/mapswithme/maps/bookmarks/BookmarksListFragment.java b/android/src/com/mapswithme/maps/bookmarks/BookmarksListFragment.java index e126cf4b01..57baedc204 100644 --- a/android/src/com/mapswithme/maps/bookmarks/BookmarksListFragment.java +++ b/android/src/com/mapswithme/maps/bookmarks/BookmarksListFragment.java @@ -17,7 +17,7 @@ import android.widget.ListView; import com.cocosw.bottomsheet.BottomSheet; import com.mapswithme.maps.Framework; -import com.mapswithme.maps.MWMActivity; +import com.mapswithme.maps.MwmActivity; import com.mapswithme.maps.R; import com.mapswithme.maps.base.BaseMwmListFragment; import com.mapswithme.maps.bookmarks.data.Bookmark; @@ -106,7 +106,7 @@ public class BookmarksListFragment extends BaseMwmListFragment break; } - final Intent i = new Intent(getActivity(), MWMActivity.class); + final Intent i = new Intent(getActivity(), MwmActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(i); } diff --git a/android/src/com/mapswithme/maps/location/AndroidNativeProvider.java b/android/src/com/mapswithme/maps/location/AndroidNativeProvider.java index 5c9563b1d0..fcd00c0814 100644 --- a/android/src/com/mapswithme/maps/location/AndroidNativeProvider.java +++ b/android/src/com/mapswithme/maps/location/AndroidNativeProvider.java @@ -7,7 +7,7 @@ import android.location.LocationManager; import android.os.Build; import android.os.Bundle; -import com.mapswithme.maps.MWMApplication; +import com.mapswithme.maps.MwmApplication; import com.mapswithme.util.ConnectionState; import com.mapswithme.util.LocationUtils; @@ -20,7 +20,7 @@ public class AndroidNativeProvider extends BaseLocationProvider implements andro public AndroidNativeProvider() { - mLocationManager = (LocationManager) MWMApplication.get().getSystemService(Context.LOCATION_SERVICE); + mLocationManager = (LocationManager) MwmApplication.get().getSystemService(Context.LOCATION_SERVICE); } @Override diff --git a/android/src/com/mapswithme/maps/location/GoogleFusedLocationProvider.java b/android/src/com/mapswithme/maps/location/GoogleFusedLocationProvider.java index 9f83589452..b76ae500af 100644 --- a/android/src/com/mapswithme/maps/location/GoogleFusedLocationProvider.java +++ b/android/src/com/mapswithme/maps/location/GoogleFusedLocationProvider.java @@ -8,7 +8,7 @@ import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; -import com.mapswithme.maps.MWMApplication; +import com.mapswithme.maps.MwmApplication; public class GoogleFusedLocationProvider extends BaseLocationProvider implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener @@ -22,7 +22,7 @@ public class GoogleFusedLocationProvider extends BaseLocationProvider public GoogleFusedLocationProvider() { - mGoogleApiClient = new GoogleApiClient.Builder(MWMApplication.get()) + mGoogleApiClient = new GoogleApiClient.Builder(MwmApplication.get()) .addApi(LocationServices.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) diff --git a/android/src/com/mapswithme/maps/location/LocationHelper.java b/android/src/com/mapswithme/maps/location/LocationHelper.java index 8e2d8dbb49..51177ebc09 100644 --- a/android/src/com/mapswithme/maps/location/LocationHelper.java +++ b/android/src/com/mapswithme/maps/location/LocationHelper.java @@ -16,7 +16,7 @@ import android.text.TextUtils; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GoogleApiAvailability; -import com.mapswithme.maps.MWMApplication; +import com.mapswithme.maps.MwmApplication; import com.mapswithme.maps.R; import com.mapswithme.util.LocationUtils; import com.mapswithme.util.log.Logger; @@ -67,7 +67,7 @@ public enum LocationHelper implements SensorEventListener { mLogger = SimpleLogger.get(LocationHelper.class.getName()); initLocationProvider(false); - mSensorManager = (SensorManager) MWMApplication.get().getSystemService(Context.SENSOR_SERVICE); + mSensorManager = (SensorManager) MwmApplication.get().getSystemService(Context.SENSOR_SERVICE); if (mSensorManager != null) { mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); @@ -80,7 +80,7 @@ public enum LocationHelper implements SensorEventListener { boolean isLocationTurnedOn = false; - final MWMApplication application = MWMApplication.get(); + final MwmApplication application = MwmApplication.get(); // If location is turned off(by user in system settings), google client( = fused provider) api doesn't work at all // but external gps receivers still can work. In that case we prefer native provider instead of fused - it works. final ContentResolver resolver = application.getContentResolver(); diff --git a/android/src/com/mapswithme/maps/routing/RoutingResultCodesProcessor.java b/android/src/com/mapswithme/maps/routing/RoutingResultCodesProcessor.java index fa5947fc39..99aafbd487 100644 --- a/android/src/com/mapswithme/maps/routing/RoutingResultCodesProcessor.java +++ b/android/src/com/mapswithme/maps/routing/RoutingResultCodesProcessor.java @@ -4,7 +4,7 @@ import android.content.res.Resources; import android.util.Pair; import com.mapswithme.maps.LocationState; -import com.mapswithme.maps.MWMApplication; +import com.mapswithme.maps.MwmApplication; import com.mapswithme.maps.MapStorage; import com.mapswithme.maps.R; @@ -33,7 +33,7 @@ public class RoutingResultCodesProcessor if (missingCountries != null) missingCount = missingCountries.length; - Resources resources = MWMApplication.get().getResources(); + Resources resources = MwmApplication.get().getResources(); int titleRes = 0; List messages = new ArrayList<>(); switch (errorCode) diff --git a/android/src/com/mapswithme/maps/search/SearchFragment.java b/android/src/com/mapswithme/maps/search/SearchFragment.java index 29030bf1d2..b928d7646c 100644 --- a/android/src/com/mapswithme/maps/search/SearchFragment.java +++ b/android/src/com/mapswithme/maps/search/SearchFragment.java @@ -20,7 +20,7 @@ import android.widget.TextView; import com.mapswithme.country.ActiveCountryTree; import com.mapswithme.country.CountrySuggestFragment; import com.mapswithme.maps.Framework; -import com.mapswithme.maps.MWMActivity; +import com.mapswithme.maps.MwmActivity; import com.mapswithme.maps.R; import com.mapswithme.maps.base.BaseMwmRecyclerFragment; import com.mapswithme.maps.base.OnBackPressListener; @@ -299,7 +299,7 @@ public class SearchFragment extends BaseMwmRecyclerFragment implements View.OnCl // change map style for the Map activity final int mapStyle = isDark ? Framework.MAP_STYLE_DARK : Framework.MAP_STYLE_LIGHT; - MWMActivity.setMapStyle(getActivity(), mapStyle); + MwmActivity.setMapStyle(getActivity(), mapStyle); return true; } diff --git a/android/src/com/mapswithme/maps/search/SearchToolbarController.java b/android/src/com/mapswithme/maps/search/SearchToolbarController.java index fd36261194..cf7122b571 100644 --- a/android/src/com/mapswithme/maps/search/SearchToolbarController.java +++ b/android/src/com/mapswithme/maps/search/SearchToolbarController.java @@ -8,7 +8,7 @@ import android.view.View.OnClickListener; import android.widget.TextView; import com.mapswithme.maps.Framework; -import com.mapswithme.maps.MWMActivity; +import com.mapswithme.maps.MwmActivity; import com.mapswithme.maps.R; import com.mapswithme.maps.api.ParsedMwmRequest; import com.mapswithme.util.UiUtils; @@ -34,7 +34,7 @@ public class SearchToolbarController implements OnClickListener @Override public void onClick(View v) { - MWMActivity.startSearch(mActivity, mSearchQuery.getText().toString()); + MwmActivity.startSearch(mActivity, mSearchQuery.getText().toString()); cancelSearchApiAndHide(); } }); @@ -73,7 +73,7 @@ public class SearchToolbarController implements OnClickListener if (R.id.search_text_query == id) { final String query = mSearchQuery.getText().toString(); - MWMActivity.startSearch(mActivity, query); + MwmActivity.startSearch(mActivity, query); UiUtils.hide(mSearchToolbar); } else if (R.id.search_image_clear == id) diff --git a/android/src/com/mapswithme/maps/settings/SettingsActivity.java b/android/src/com/mapswithme/maps/settings/SettingsActivity.java index 4ab1a4400c..558faac100 100644 --- a/android/src/com/mapswithme/maps/settings/SettingsActivity.java +++ b/android/src/com/mapswithme/maps/settings/SettingsActivity.java @@ -29,7 +29,7 @@ import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GoogleApiAvailability; import com.mapswithme.country.ActiveCountryTree; import com.mapswithme.maps.BuildConfig; -import com.mapswithme.maps.MWMApplication; +import com.mapswithme.maps.MwmApplication; import com.mapswithme.maps.R; import com.mapswithme.util.Constants; import com.mapswithme.util.UiUtils; @@ -58,7 +58,7 @@ public class SettingsActivity extends PreferenceActivity implements OnPreference // TODO remove after refactoring to fragments // this initialisation is necessary hence Activity isn't extended from BaseMwmActivity // try to prevent possible crash if this is the only activity in application - MWMApplication.get().initStats(); + MwmApplication.get().initStats(); addPreferencesFromResource(R.xml.preferences); initPreferences(); yotaSetup(); @@ -87,10 +87,10 @@ public class SettingsActivity extends PreferenceActivity implements OnPreference allowStatsPreference.setOnPreferenceChangeListener(this); final CheckBoxPreference enableZoomButtons = (CheckBoxPreference) findPreference(getString(R.string.pref_zoom_btns_enabled)); - enableZoomButtons.setChecked(MWMApplication.get().nativeGetBoolean(ZOOM_BUTTON_ENABLED, true)); + enableZoomButtons.setChecked(MwmApplication.get().nativeGetBoolean(ZOOM_BUTTON_ENABLED, true)); enableZoomButtons.setOnPreferenceChangeListener(this); - if (GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(MWMApplication.get()) != ConnectionResult.SUCCESS) + if (GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(MwmApplication.get()) != ConnectionResult.SUCCESS) { ((PreferenceScreen) findPreference(getString(R.string.pref_settings))). removePreference(findPreference(getString(R.string.pref_play_services))); @@ -430,7 +430,7 @@ public class SettingsActivity extends PreferenceActivity implements OnPreference else if (key.equals(getString(R.string.pref_allow_stat))) Statistics.INSTANCE.setStatEnabled((Boolean) newValue); else if (key.equals(getString(R.string.pref_zoom_btns_enabled))) - MWMApplication.get().nativeSetBoolean(ZOOM_BUTTON_ENABLED, (Boolean) newValue); + MwmApplication.get().nativeSetBoolean(ZOOM_BUTTON_ENABLED, (Boolean) newValue); return true; } diff --git a/android/src/com/mapswithme/maps/settings/StoragePathManager.java b/android/src/com/mapswithme/maps/settings/StoragePathManager.java index 99e5133c22..260fc9d4cc 100644 --- a/android/src/com/mapswithme/maps/settings/StoragePathManager.java +++ b/android/src/com/mapswithme/maps/settings/StoragePathManager.java @@ -17,7 +17,7 @@ import android.util.Log; import com.mapswithme.maps.BuildConfig; import com.mapswithme.maps.Framework; -import com.mapswithme.maps.MWMApplication; +import com.mapswithme.maps.MwmApplication; import com.mapswithme.maps.MapStorage; import com.mapswithme.maps.R; import com.mapswithme.maps.bookmarks.data.BookmarkManager; @@ -199,8 +199,8 @@ public class StoragePathManager @TargetApi(Build.VERSION_CODES.KITKAT) private static void parseKitkatStorages(List paths) { - File primaryStorage = MWMApplication.get().getExternalFilesDir(null); - File[] storages = MWMApplication.get().getExternalFilesDirs(null); + File primaryStorage = MwmApplication.get().getExternalFilesDir(null); + File[] storages = MwmApplication.get().getExternalFilesDirs(null); if (storages != null) { for (File f : storages) @@ -483,7 +483,7 @@ public class StoragePathManager private void migrateBookmarks(final Activity activity, final MoveFilesListener listener) { - if (MWMApplication.get().nativeGetBoolean(IS_KML_PLACED_IN_MAIN_STORAGE, false)) + if (MwmApplication.get().nativeGetBoolean(IS_KML_PLACED_IN_MAIN_STORAGE, false)) listener.moveFilesFinished(""); else { @@ -501,7 +501,7 @@ public class StoragePathManager { if (res) { - MWMApplication.get().nativeSetBoolean(IS_KML_PLACED_IN_MAIN_STORAGE, true); + MwmApplication.get().nativeSetBoolean(IS_KML_PLACED_IN_MAIN_STORAGE, true); listener.moveFilesFinished(""); } else @@ -515,7 +515,7 @@ public class StoragePathManager private void migrateMaps(final Activity activity) { - if (!MWMApplication.get().nativeGetBoolean(IS_KITKAT_MIGRATION_COMPLETED, false)) + if (!MwmApplication.get().nativeGetBoolean(IS_KITKAT_MIGRATION_COMPLETED, false)) { checkExternalStoragePathOnKitkat(activity, new MoveFilesListener() @@ -523,7 +523,7 @@ public class StoragePathManager @Override public void moveFilesFinished(String newPath) { - MWMApplication.get().nativeSetBoolean(IS_KITKAT_MIGRATION_COMPLETED, true); + MwmApplication.get().nativeSetBoolean(IS_KITKAT_MIGRATION_COMPLETED, true); UiUtils.showAlertDialog(activity, R.string.kitkat_migrate_ok); } diff --git a/android/src/com/mapswithme/maps/sound/TtsPlayer.java b/android/src/com/mapswithme/maps/sound/TtsPlayer.java index df721ec6e6..2bd50e1460 100644 --- a/android/src/com/mapswithme/maps/sound/TtsPlayer.java +++ b/android/src/com/mapswithme/maps/sound/TtsPlayer.java @@ -5,7 +5,7 @@ import android.speech.tts.TextToSpeech; import android.util.Log; import android.widget.Toast; -import com.mapswithme.maps.MWMApplication; +import com.mapswithme.maps.MwmApplication; import java.util.Locale; @@ -22,7 +22,7 @@ public enum TtsPlayer TtsPlayer() { - mContext = MWMApplication.get().getApplicationContext(); + mContext = MwmApplication.get().getApplicationContext(); } public void init() diff --git a/android/src/com/mapswithme/maps/widget/RoutingLayout.java b/android/src/com/mapswithme/maps/widget/RoutingLayout.java index f76dc21c61..fef3ca5be9 100644 --- a/android/src/com/mapswithme/maps/widget/RoutingLayout.java +++ b/android/src/com/mapswithme/maps/widget/RoutingLayout.java @@ -20,7 +20,7 @@ import android.widget.RadioButton; import android.widget.TextView; import com.mapswithme.maps.Framework; -import com.mapswithme.maps.MWMApplication; +import com.mapswithme.maps.MwmApplication; import com.mapswithme.maps.R; import com.mapswithme.maps.bookmarks.data.DistanceAndAzimut; import com.mapswithme.maps.bookmarks.data.MapObject; @@ -336,7 +336,7 @@ public class RoutingLayout extends FrameLayout implements CompoundButton.OnCheck private void buildRoute() { - if (!MWMApplication.get().nativeGetBoolean(IS_ROUTING_DISCLAIMER_APPROVED, false)) + if (!MwmApplication.get().nativeGetBoolean(IS_ROUTING_DISCLAIMER_APPROVED, false)) { showRoutingDisclaimer(); return; @@ -361,7 +361,7 @@ public class RoutingLayout extends FrameLayout implements CompoundButton.OnCheck @Override public void onClick(DialogInterface dlg, int which) { - MWMApplication.get().nativeSetBoolean(IS_ROUTING_DISCLAIMER_APPROVED, true); + MwmApplication.get().nativeSetBoolean(IS_ROUTING_DISCLAIMER_APPROVED, true); dlg.dismiss(); buildRoute(); } diff --git a/android/src/com/mapswithme/maps/widget/placepage/BasePlacePageAnimationController.java b/android/src/com/mapswithme/maps/widget/placepage/BasePlacePageAnimationController.java index c402c8741e..f3bdaf36ca 100644 --- a/android/src/com/mapswithme/maps/widget/placepage/BasePlacePageAnimationController.java +++ b/android/src/com/mapswithme/maps/widget/placepage/BasePlacePageAnimationController.java @@ -9,7 +9,7 @@ import android.view.ViewConfiguration; import android.view.ViewGroup; import android.widget.ScrollView; -import com.mapswithme.maps.MWMApplication; +import com.mapswithme.maps.MwmApplication; import com.mapswithme.maps.R; import com.mapswithme.maps.bookmarks.data.MapObject; import com.mapswithme.maps.widget.placepage.PlacePageView.State; @@ -19,7 +19,7 @@ import com.mapswithme.maps.widget.placepage.PlacePageView.State; */ public abstract class BasePlacePageAnimationController { - protected static final int DURATION = MWMApplication.get().getResources().getInteger(R.integer.anim_duration_default); + protected static final int DURATION = MwmApplication.get().getResources().getInteger(R.integer.anim_duration_default); protected static final boolean NO_ANIMATION = (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB); protected State mState = State.HIDDEN; -- cgit v1.2.3