From 1e4aa2091e4439fccbc2bdf4339be7f225262915 Mon Sep 17 00:00:00 2001 From: tomas Date: Tue, 22 Aug 2017 23:29:41 +0200 Subject: [PATCH 1/3] fixed of logging according mnc type change --- .../openbmap/unifiedNlp/services/OpenbmapNlpService.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/org/openbmap/unifiedNlp/services/OpenbmapNlpService.java b/src/org/openbmap/unifiedNlp/services/OpenbmapNlpService.java index 3fb2739..5fc150b 100644 --- a/src/org/openbmap/unifiedNlp/services/OpenbmapNlpService.java +++ b/src/org/openbmap/unifiedNlp/services/OpenbmapNlpService.java @@ -371,7 +371,7 @@ private List getCells() { cell.mcc = mcc; cell.mnc = mnc; cell.technology = TECHNOLOGY_MAP().get(c.getNetworkType()); - Log.d(TAG, String.format("NeighboringCellInfo for %d|%d|%d|%d|%s|%d", cell.mcc, cell.mnc, cell.area, cell.cellId, cell.technology, c.getPsc())); + Log.d(TAG, String.format("NeighboringCellInfo for %d|%s|%d|%d|%s|%d", cell.mcc, cell.mnc, cell.area, cell.cellId, cell.technology, c.getPsc())); cells.add(cell); } } @@ -394,7 +394,7 @@ private List getCells() { cell.mcc = ((CellInfoGsm)c).getCellIdentity().getMcc(); cell.mnc = String.valueOf(((CellInfoGsm)c).getCellIdentity().getMnc()); cell.technology = TECHNOLOGY_MAP().get(mTelephonyManager.getNetworkType()); - Log.d(TAG, String.format("CellInfoGsm for %d|%d|%d|%d|%s", cell.mcc, cell.mnc, cell.area, cell.cellId, cell.technology)); + Log.d(TAG, String.format("CellInfoGsm for %d|%s|%d|%d|%s", cell.mcc, cell.mnc, cell.area, cell.cellId, cell.technology)); } else if (c instanceof CellInfoCdma) { /* object.put("cellId", ((CellInfoCdma)s).getCellIdentity().getBasestationId()); @@ -409,7 +409,7 @@ private List getCells() { cell.mcc = ((CellInfoLte)c).getCellIdentity().getMcc(); cell.mnc = String.valueOf(((CellInfoLte)c).getCellIdentity().getMnc()); cell.technology = TECHNOLOGY_MAP().get(mTelephonyManager.getNetworkType()); - Log.d(TAG, String.format("CellInfoLte for %d|%d|%d|%d|%s|%d", cell.mcc, cell.mnc, cell.area, cell.cellId, cell.technology, ((CellInfoLte)c).getCellIdentity().getPci())); + Log.d(TAG, String.format("CellInfoLte for %d|%s|%d|%d|%s|%d", cell.mcc, cell.mnc, cell.area, cell.cellId, cell.technology, ((CellInfoLte)c).getCellIdentity().getPci())); } else if (c instanceof CellInfoWcdma) { //Log.v(TAG, "CellInfoWcdma cell found"); cell.cellId = ((CellInfoWcdma) c).getCellIdentity().getCid(); @@ -417,7 +417,7 @@ private List getCells() { cell.mcc = ((CellInfoWcdma)c).getCellIdentity().getMcc(); cell.mnc = String.valueOf(((CellInfoWcdma)c).getCellIdentity().getMnc()); cell.technology = TECHNOLOGY_MAP().get(mTelephonyManager.getNetworkType()); - Log.d(TAG, String.format("CellInfoWcdma for %d|%d|%d|%d|%s|%d", cell.mcc, cell.mnc, cell.area, cell.cellId, cell.technology, ((CellInfoWcdma) c).getCellIdentity().getPsc())); + Log.d(TAG, String.format("CellInfoWcdma for %d|%s|%d|%d|%s|%d", cell.mcc, cell.mnc, cell.area, cell.cellId, cell.technology, ((CellInfoWcdma) c).getCellIdentity().getPsc())); } cells.add(cell); } From 1e737496e8828c116c40b93d16ef5f9aff05b57c Mon Sep 17 00:00:00 2001 From: tomas Date: Sun, 1 Oct 2017 22:58:35 +0200 Subject: [PATCH 2/3] Add wake-up procedure to get current cell; add logging to file --- .gitignore | 3 +- AndroidManifest.xml | 7 +- build.gradle | 2 +- .../dialogpreference_catalogs_group.xml | 2 +- res/values-ja/log_file_lasting.xml | 19 ++ res/values-ja/operation_modes.xml | 11 + res/values-ja/sources.xml | 13 + res/values-ja/strings.xml | 15 +- res/values-ja/wake_up_strategy.xml | 13 + res/values/log_file_lasting.xml | 19 ++ res/values/strings.xml | 15 +- res/values/wake_up_strategy.xml | 13 + res/xml/preferences.xml | 31 ++ .../unifiedNlp/Geocoder/OfflineProvider.java | 21 +- src/org/openbmap/unifiedNlp/Preferences.java | 5 + .../openbmap/unifiedNlp/SettingsActivity.java | 140 +++++++-- .../services/OpenbmapNlpService.java | 271 +++++++++++++----- .../openbmap/unifiedNlp/utils/LogToFile.java | 107 +++++++ 18 files changed, 593 insertions(+), 114 deletions(-) create mode 100644 res/values-ja/log_file_lasting.xml create mode 100644 res/values-ja/operation_modes.xml create mode 100644 res/values-ja/sources.xml create mode 100644 res/values-ja/wake_up_strategy.xml create mode 100644 res/values/log_file_lasting.xml create mode 100644 res/values/wake_up_strategy.xml create mode 100644 src/org/openbmap/unifiedNlp/utils/LogToFile.java diff --git a/.gitignore b/.gitignore index 9b6e377..a127fe3 100644 --- a/.gitignore +++ b/.gitignore @@ -8,4 +8,5 @@ /res/raw/build.txt /.settings /local.properties -/.nb-gradle/ \ No newline at end of file +/.nb-gradle/ +/private/ diff --git a/AndroidManifest.xml b/AndroidManifest.xml index 31d8bed..d94c54c 100644 --- a/AndroidManifest.xml +++ b/AndroidManifest.xml @@ -5,11 +5,12 @@ android:versionName="0.2.6"> + @@ -22,11 +23,12 @@ android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme"> + - + + + + + @string/log_file_12_label + @string/log_file_24_label + @string/log_file_48_label + @string/log_file_72_label + @string/log_file_168_label + @string/log_file_720_label + + + 12 + 24 + 48 + 72 + 168 + 720 + + \ No newline at end of file diff --git a/res/values-ja/operation_modes.xml b/res/values-ja/operation_modes.xml new file mode 100644 index 0000000..38d9713 --- /dev/null +++ b/res/values-ja/operation_modes.xml @@ -0,0 +1,11 @@ + + + + Online mode + Offline mode + + + online + offline + + \ No newline at end of file diff --git a/res/values-ja/sources.xml b/res/values-ja/sources.xml new file mode 100644 index 0000000..20fe91a --- /dev/null +++ b/res/values-ja/sources.xml @@ -0,0 +1,13 @@ + + + + Combined (Wifis and Cells) + Wifis only + Cells only + + + combined + wifis + cells + + \ No newline at end of file diff --git a/res/values-ja/strings.xml b/res/values-ja/strings.xml index 045548c..af1ca99 100644 --- a/res/values-ja/strings.xml +++ b/res/values-ja/strings.xml @@ -27,7 +27,7 @@ オペレーションモード ジオロケーションに使用するデータを選択\n(WiFi と基地局、WiFi のみ、基地局のみ) 基地局/WiFiを使用しますか? - ダウンロードに失敗しました! (エラーコード %s) + ダウンロードに失敗しました! (エラーコード %d) 設定 新しいフォルダーを作成 無効なダウンロード @@ -38,4 +38,17 @@ WiFi カタログをダウンロード 現在のサイズ (国に応じて 10–400MB) サーバーの応答を解析中にエラー + When location stucks when phone sleeps you can try to wake up phone when cell is looked for + Wake up strategy + No wake up + Wake up CPU only + Wake up with display + After specified number of time log file will recreated + Rotation of the log file + 12 hours + a day + two days + three days + a week + a month diff --git a/res/values-ja/wake_up_strategy.xml b/res/values-ja/wake_up_strategy.xml new file mode 100644 index 0000000..a9a314a --- /dev/null +++ b/res/values-ja/wake_up_strategy.xml @@ -0,0 +1,13 @@ + + + + @string/nowakeup_label + @string/wakeuppartial_label + @string/wakeupfull_label + + + nowakeup + wakeuppartial + wakeupfull + + \ No newline at end of file diff --git a/res/values/log_file_lasting.xml b/res/values/log_file_lasting.xml new file mode 100644 index 0000000..e4e3c09 --- /dev/null +++ b/res/values/log_file_lasting.xml @@ -0,0 +1,19 @@ + + + + @string/log_file_12_label + @string/log_file_24_label + @string/log_file_48_label + @string/log_file_72_label + @string/log_file_168_label + @string/log_file_720_label + + + 12 + 24 + 48 + 72 + 168 + 720 + + \ No newline at end of file diff --git a/res/values/strings.xml b/res/values/strings.xml index 7f9fe53..09dddab 100644 --- a/res/values/strings.xml +++ b/res/values/strings.xml @@ -28,7 +28,7 @@ Operation mode Select which data is used for geolocation\n(Wifis and Cells, Wifis only, Cells only) Use cells/wifis? - Download failed! (Error code %s) + Download failed! (Error code %d) Preferences Create new folder Invalid download @@ -39,4 +39,17 @@ Download Wifi Catalog Current size (10–400MB depending on country) Error parsing server reply + When location stucks when phone sleeps you can try to wake up phone when cell is looked for + Wake up strategy + No wake up + Wake up CPU only + Wake up with display + After specified number of time log file will recreated + Rotation of the log file + 12 hours + a day + two days + three days + a week + a month diff --git a/res/values/wake_up_strategy.xml b/res/values/wake_up_strategy.xml new file mode 100644 index 0000000..a9a314a --- /dev/null +++ b/res/values/wake_up_strategy.xml @@ -0,0 +1,13 @@ + + + + @string/nowakeup_label + @string/wakeuppartial_label + @string/wakeupfull_label + + + nowakeup + wakeuppartial + wakeupfull + + \ No newline at end of file diff --git a/res/xml/preferences.xml b/res/xml/preferences.xml index ca8839b..cf98693 100644 --- a/res/xml/preferences.xml +++ b/res/xml/preferences.xml @@ -8,6 +8,13 @@ android:key="mode" android:summary="@string/operation_mode_summary" android:title="@string/operation_mode_title"/> + + + + 0)?resultIds[0]:"") + ":" + resultIds.length); + if (resultIds.length == 0) { return null; } else if (resultIds.length == 1) { @@ -507,7 +505,8 @@ private boolean hasWifiTables() { @Override protected void onPostExecute(Location result) { if (result == null) { - Log.w(TAG, "Location was null"); + Log.d(TAG, "Broadcasting location" + result); + mListener.onLocationReceived(result); return; } diff --git a/src/org/openbmap/unifiedNlp/Preferences.java b/src/org/openbmap/unifiedNlp/Preferences.java index 71b08f5..cff99ad 100644 --- a/src/org/openbmap/unifiedNlp/Preferences.java +++ b/src/org/openbmap/unifiedNlp/Preferences.java @@ -30,6 +30,8 @@ public final class Preferences { */ public static final String KEY_OPERATION_MODE = "mode"; + public static final String KEY_WAKE_UP_STRATEGY = "wake.up.strategy"; + public static final String KEY_SOURCE = "source"; /** @@ -41,6 +43,9 @@ public final class Preferences { * Broadcast debug messages? */ public static final String KEY_DEBUG_MESSAGES = "debug.messages"; + public static final String KEY_DEBUG_FILE = "debug.log.file"; + public static final String KEY_DEBUG_TO_FILE = "debug.to.file"; + public static final String KEY_DEBUG_FILE_LASTING_HOURS = "debug.file.lasting.hours"; /* * Default values following .. diff --git a/src/org/openbmap/unifiedNlp/SettingsActivity.java b/src/org/openbmap/unifiedNlp/SettingsActivity.java index f63c101..509dcd1 100644 --- a/src/org/openbmap/unifiedNlp/SettingsActivity.java +++ b/src/org/openbmap/unifiedNlp/SettingsActivity.java @@ -29,9 +29,7 @@ License, or (at your option) any later version. import android.content.pm.PackageManager; import android.database.Cursor; import android.net.Uri; -import android.net.wifi.WifiManager.WifiLock; import android.os.Bundle; -import android.os.PowerManager.WakeLock; import android.preference.ListPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; @@ -49,6 +47,7 @@ License, or (at your option) any later version. import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; +import org.openbmap.unifiedNlp.utils.LogToFile; /** * Preferences activity. @@ -61,18 +60,15 @@ public class SettingsActivity extends PreferenceActivity implements ICatalogChoo private BroadcastReceiver mReceiver = null; - private boolean mIsDownloading; - private WakeLock mWakeLock; - private WifiLock mWifiLock; - - private long mCurrentCatalogDownloadId; - @Override protected final void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); registerDownloadManager(); + + initLogFileChooser(); + initLogFileLasting(); initFolderChooser(); @@ -114,6 +110,8 @@ public void onClick(DialogInterface dialog, int id) { } pref.setSummary(version + " (" + readBuildInfo() + ")"); + + initWakeUpStrategy(); } @Override @@ -125,20 +123,46 @@ public void onResume() { @Override protected final void onDestroy() { - if (mWakeLock != null && mWakeLock.isHeld()) { - mWakeLock.release(); - } - - if (mWifiLock != null && mWifiLock.isHeld()) { - mWifiLock.release(); - } - if (mReceiver != null) { unregisterReceiver(mReceiver); } super.onDestroy(); } - + + private void initWakeUpStrategy() { + Preference wakeUpStrategy = findPreference(Preferences.KEY_WAKE_UP_STRATEGY); + wakeUpStrategy.setSummary( + getWakeUpStrategyLabel( + PreferenceManager.getDefaultSharedPreferences(SettingsActivity.this).getString(Preferences.KEY_WAKE_UP_STRATEGY, "nowakeup") + ) + ); + wakeUpStrategy.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange(Preference wakeUpStrategy, Object value) { + String wakeUpStrategyValue = (String) value; + wakeUpStrategy.setSummary(getString(getWakeUpStrategyLabel(wakeUpStrategyValue))); + return true; + } + }); + } + + private int getWakeUpStrategyLabel(String wakeUpStrategyValue) { + int wakeUpStrategyId; + switch (wakeUpStrategyValue) { + case "wakeuppartial": + wakeUpStrategyId = R.string.wakeuppartial_label; + break; + case "wakeupfull": + wakeUpStrategyId = R.string.wakeupfull_label; + break; + case "nowakeup": + default: + wakeUpStrategyId = R.string.nowakeup_label; + break; + } + return wakeUpStrategyId; + } + private void showCatalogDownloadDialog() { DialogPreferenceCatalogs catalogs = (DialogPreferenceCatalogs) findPreference(Preferences.KEY_CATALOGS_DIALOG); catalogs.showDialog(null); @@ -271,6 +295,84 @@ public void onClick(DialogInterface dialog, int id) { }); } + private void initLogFileChooser() { + Preference logFilePicker = (Preference) findPreference(Preferences.KEY_DEBUG_FILE); + logFilePicker.setSummary(PreferenceManager.getDefaultSharedPreferences(SettingsActivity.this).getString(Preferences.KEY_DEBUG_FILE,"")); + logFilePicker.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { + + @Override + public boolean onPreferenceChange(Preference preference, Object value) { + String newPaths = (String) value; + + int indexOfLastColon = newPaths.indexOf(":"); + + String newLogFileName = newPaths.substring(0, indexOfLastColon) + "/log-openbmapnlpservice.txt"; + + Preference logFilePicker = findPreference(Preferences.KEY_DEBUG_FILE); + logFilePicker.getEditor().putString(Preferences.KEY_DEBUG_FILE, newLogFileName).apply(); + LogToFile.logFilePathname = newLogFileName; + logFilePicker.setSummary(PreferenceManager.getDefaultSharedPreferences(SettingsActivity.this).getString(Preferences.KEY_DEBUG_FILE,"")); + return false; + } + }); + + Preference logToFilePicker = (Preference) findPreference(Preferences.KEY_DEBUG_TO_FILE); + logToFilePicker.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { + + @Override + public boolean onPreferenceChange(Preference preference, Object value) { + boolean logToFile = (Boolean) value; + preference.getEditor().putBoolean(Preferences.KEY_DEBUG_TO_FILE, logToFile).apply(); + LogToFile.logToFileEnabled = logToFile; + return true; + } + }); + } + + private void initLogFileLasting() { + Preference logFileLasting = findPreference(Preferences.KEY_DEBUG_FILE_LASTING_HOURS); + logFileLasting.setSummary( + getLogFileLastingLabel(Integer.parseInt( + PreferenceManager.getDefaultSharedPreferences(SettingsActivity.this).getString(Preferences.KEY_DEBUG_FILE_LASTING_HOURS, "24")) + ) + ); + logFileLasting.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange(Preference logFileLasting, Object value) { + Integer logFileLastingHours = Integer.valueOf((String) value); + logFileLasting.setSummary(getString(getLogFileLastingLabel(logFileLastingHours))); + LogToFile.logFileHoursOfLasting = logFileLastingHours; + return true; + } + }); + } + + private int getLogFileLastingLabel(int logFileLastingValue) { + int logFileLastingId; + switch (logFileLastingValue) { + case 12: + logFileLastingId = R.string.log_file_12_label; + break; + case 48: + logFileLastingId = R.string.log_file_48_label; + break; + case 72: + logFileLastingId = R.string.log_file_72_label; + break; + case 168: + logFileLastingId = R.string.log_file_168_label; + break; + case 720: + logFileLastingId = R.string.log_file_720_label; + break; + case 24: + default: + logFileLastingId = R.string.log_file_24_label; + break; + } + return logFileLastingId; + } + /** * Lets user select source for geolocation (wifis, cells, combined) */ @@ -474,7 +576,7 @@ public void catalogSelected(String url) { // e.g. on second SD card a security exception is thrown final DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); request.setDestinationUri(Uri.fromFile(target)); - mCurrentCatalogDownloadId = dm.enqueue(request); + dm.enqueue(request); } catch (final SecurityException sec) { // download to temp dir and try to move to target later Log.w(TAG, "Security exception, can't write to " + target + ", using " + getExternalCacheDir()); @@ -482,7 +584,7 @@ public void catalogSelected(String url) { final DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); request.setDestinationUri(Uri.fromFile(tempFile)); - mCurrentCatalogDownloadId = dm.enqueue(request); + dm.enqueue(request); } } else { Toast.makeText(this, R.string.error_save_file_failed, Toast.LENGTH_SHORT).show(); diff --git a/src/org/openbmap/unifiedNlp/services/OpenbmapNlpService.java b/src/org/openbmap/unifiedNlp/services/OpenbmapNlpService.java index 5fc150b..7160382 100644 --- a/src/org/openbmap/unifiedNlp/services/OpenbmapNlpService.java +++ b/src/org/openbmap/unifiedNlp/services/OpenbmapNlpService.java @@ -18,6 +18,8 @@ License, or (at your option) any later version. package org.openbmap.unifiedNlp.services; import android.annotation.SuppressLint; +import android.app.AlarmManager; +import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; @@ -27,7 +29,8 @@ License, or (at your option) any later version. import android.net.wifi.WifiManager; import android.net.wifi.WifiManager.WifiLock; import android.os.Build; -import android.os.Handler; +import android.os.PowerManager; +import android.os.SystemClock; import android.preference.PreferenceManager; import android.telephony.CellInfo; import android.telephony.CellInfoCdma; @@ -36,7 +39,6 @@ License, or (at your option) any later version. import android.telephony.CellInfoWcdma; import android.telephony.CellLocation; import android.telephony.NeighboringCellInfo; -import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.telephony.cdma.CdmaCellLocation; import android.telephony.gsm.GsmCellLocation; @@ -55,6 +57,9 @@ License, or (at your option) any later version. import java.util.HashMap; import java.util.List; import java.util.Map; +import org.openbmap.unifiedNlp.utils.LogToFile; + +import static org.openbmap.unifiedNlp.utils.LogToFile.appendLog; @SuppressLint("NewApi") public class OpenbmapNlpService extends LocationBackendService implements ILocationCallback { @@ -84,8 +89,10 @@ public class OpenbmapNlpService extends LocationBackendService implements ILocat * Phone state listeners to receive cell updates */ private TelephonyManager mTelephonyManager; - private PhoneStateListener mPhoneListener; - + private PowerManager powerManager; + private PowerManager.WakeLock wakeLock; + private AlarmManager alarmManager; + WifiLock mWifiLock; /** @@ -99,8 +106,6 @@ public class OpenbmapNlpService extends LocationBackendService implements ILocat private ILocationProvider mGeocoder; - private boolean running; - /** * Time of last geolocation request (millis) */ @@ -111,7 +116,7 @@ public class OpenbmapNlpService extends LocationBackendService implements ILocat /** * Receives location updates as well as wifi scan result updates */ - private BroadcastReceiver mReceiver = new BroadcastReceiver() { + private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(final Context context, final Intent intent) { @@ -165,6 +170,11 @@ public static Map TECHNOLOGY_MAP() { @Override protected void onOpen() { Log.i(TAG, "Opening " + TAG); + + LogToFile.logFilePathname = PreferenceManager.getDefaultSharedPreferences(this).getString(Preferences.KEY_DEBUG_FILE,""); + LogToFile.logToFileEnabled = PreferenceManager.getDefaultSharedPreferences(this).getBoolean(Preferences.KEY_DEBUG_TO_FILE, false); + LogToFile.logFileHoursOfLasting = Integer.valueOf(PreferenceManager.getDefaultSharedPreferences(this).getString(Preferences.KEY_DEBUG_FILE_LASTING_HOURS, "24")); + wifiManager = (WifiManager) getSystemService(WIFI_SERVICE); mWifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_SCAN_ONLY, "SCAN_LOCK"); @@ -173,19 +183,19 @@ protected void onOpen() { } registerReceiver(mReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); - mTelephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE); - + mTelephonyManager = ((TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE)); + powerManager = ((PowerManager) this.getSystemService(Context.POWER_SERVICE)); + alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE); + Log.d(TAG, "[Config] Debug Mode: " + PreferenceManager.getDefaultSharedPreferences(this).getBoolean(Preferences.KEY_DEBUG_MESSAGES, Preferences.VAL_DEBUG_MESSAGES)); mDebug = PreferenceManager.getDefaultSharedPreferences(this).getBoolean(Preferences.KEY_DEBUG_MESSAGES, Preferences.VAL_DEBUG_MESSAGES); Log.d(TAG, "[Config] Operation Mode: " + PreferenceManager.getDefaultSharedPreferences(this).getString(Preferences.KEY_OPERATION_MODE, Preferences.VAL_OPERATION_MODE)); mOnlineMode = PreferenceManager.getDefaultSharedPreferences(this).getString(Preferences.KEY_OPERATION_MODE, Preferences.VAL_OPERATION_MODE).equals("online"); - running = true; } - + @Override protected void onClose() { - running = false; if (mWifiLock != null) { if (mWifiLock.isHeld()) { mWifiLock.release(); @@ -193,32 +203,54 @@ protected void onClose() { } } - unregisterReceiver(mReceiver); + unregisterReceiver(mReceiver); wifiManager = null; } - Handler timerHandler = new Handler(); - Runnable timerRunnable = new Runnable() { - - @Override - public void run() { - if (nextScanningAllowedFrom == null) { - return; - } - nextScanningAllowedFrom = null; - getLocationFromWifisAndCells(new ArrayList()); + @Override + public int onStartCommand(Intent intent, int flags, final int startId) { + int ret = super.onStartCommand(intent, flags, startId); + + if (intent == null) { + return ret; } - }; + + if (null != intent.getAction()) switch (intent.getAction()) { + case "org.openbmap.unifiedNlp.LOCATION_UPDATE_CELLS_ONLY": + appendLog(TAG, "LOCATION_UPDATE_CELLS_ONLY:nextScanningAllowedFrom:" + nextScanningAllowedFrom); + if (nextScanningAllowedFrom == null) { + return ret; + } + nextScanningAllowedFrom = null; + getLocationFromWifisAndCells(null); + break; + + default: + break; + } + return ret; + } + + private PendingIntent getIntentToGetCellsOnly() { + Intent intent = new Intent(getBaseContext(), OpenbmapNlpService.class); + intent.setAction("org.openbmap.unifiedNlp.LOCATION_UPDATE_CELLS_ONLY"); + return PendingIntent.getService(getBaseContext(), + 0, + intent, + PendingIntent.FLAG_CANCEL_CURRENT); + } @Override protected Location update() { + appendLog(TAG, "call update()"); Calendar now = Calendar.getInstance(); - + if ((nextScanningAllowedFrom != null) && (nextScanningAllowedFrom.after(now))) { Log.v(TAG, "Another scan is taking place"); + appendLog(TAG, "update():Another scan is taking place"); return null; } - + appendLog(TAG, "update():mGeocoder:" + mGeocoder); if (mGeocoder == null) { if (mOnlineMode) { Log.i(TAG, "Using online geocoder"); @@ -228,15 +260,21 @@ protected Location update() { mGeocoder = new OfflineProvider(this, this); } } + appendLog(TAG, "update():isWifiSupported():" + isWifiSupported() + ":isWifisSourceSelected():" + isWifisSourceSelected() + ":" + isCellsSourceSelected()); if (isWifiSupported() && isWifisSourceSelected()) { //Log.i(TAG, "Scanning wifis"); + appendLog(TAG, "update():nextScanningAllowedFrom:" + nextScanningAllowedFrom); if(nextScanningAllowedFrom == null) { scanning = wifiManager.startScan(); nextScanningAllowedFrom = Calendar.getInstance(); - nextScanningAllowedFrom.add(Calendar.MINUTE, 5); - timerHandler.postDelayed(timerRunnable, 20000); + nextScanningAllowedFrom.add(Calendar.MINUTE, 1); } - + final PendingIntent intentToCancel = getIntentToGetCellsOnly(); + wakeUp(); + alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, + SystemClock.elapsedRealtime() + 8000, + intentToCancel); + appendLog(TAG, "update():alarm set"); /** * Processes scan results and sends query to geocoding service */ @@ -247,7 +285,9 @@ protected Location update() { public void onWifiResultsAvailable() { //Log.d(TAG, "Wifi results are available now."); nextScanningAllowedFrom = null; - timerHandler.removeCallbacks(timerRunnable); + //timerHandler.removeCallbacks(timerRunnable); + intentToCancel.cancel(); + alarmManager.cancel(intentToCancel); if (scanning) { // TODO pass wifi signal strength to geocoder //Log.i(TAG, "Wifi scan results arrived.."); @@ -268,6 +308,7 @@ public void onWifiResultsAvailable() { getLocationFromWifisAndCells(null); } else { Log.e(TAG, "Neigther cells nor wifis as source selected? Com'on.."); + appendLog(TAG, "update():Neigther cells nor wifis as source selected? Com'on.."); } return null; @@ -277,7 +318,7 @@ private void getLocationFromWifisAndCells(List scans) { final long passed = System.currentTimeMillis() - lastFix; final boolean ok_online = (mOnlineMode && (passed > ONLINE_REFRESH_INTERVAL) || lastFix == 0); final boolean ok_offline = (!mOnlineMode && (passed > OFFLINE_REFRESH_INTERVAL) || lastFix == 0); - + appendLog(TAG, "getLocationFromWifisAndCells():ok_online:" + ok_online + ":ok_offline:" + ok_offline); if (ok_online || ok_offline) { Log.d(TAG, "Scanning wifis & cells"); lastFix = System.currentTimeMillis(); @@ -287,6 +328,7 @@ private void getLocationFromWifisAndCells(List scans) { if (isCellsSourceSelected()) { cells = getCells(); } + appendLog(TAG, "getLocationFromWifisAndCells():mGeocoder:" + mGeocoder); if (mGeocoder != null) { mGeocoder.getLocation(scans, cells); } else { @@ -315,6 +357,45 @@ private boolean isCellsSourceSelected() { return (source.equals(Preferences.SOURCE_CELLS)) || (source.equals(Preferences.SOURCE_COMBINED)); } + private void wakeUp() { + appendLog(TAG, "powerManager:" + powerManager); + + String wakeUpStrategy = PreferenceManager.getDefaultSharedPreferences(this).getString(Preferences.KEY_WAKE_UP_STRATEGY, "nowakeup"); + + appendLog(TAG, "wakeLock:wakeUpStrategy:" + wakeUpStrategy); + + if ("nowakeup".equals(wakeUpStrategy)) { + return; + } + + int powerLockID; + + if ("wakeupfull".equals(wakeUpStrategy)) { + powerLockID = PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP; + } else { + powerLockID = PowerManager.PARTIAL_WAKE_LOCK; + } + + appendLog(TAG, "wakeLock:powerLockID:" + powerLockID); + + boolean isInUse; + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) { + isInUse = powerManager.isInteractive(); + } else { + isInUse = powerManager.isScreenOn(); + } + + if (!isInUse) { + wakeLock = powerManager.newWakeLock(powerLockID, TAG); + appendLog(TAG, "wakeLock:" + wakeLock + ":" + wakeLock.isHeld()); + if (!wakeLock.isHeld()) { + wakeLock.acquire(); + } + appendLog(TAG, "wakeLock acquired"); + } + } + /** * Returns cells phone is currently connected to * @return list of cells @@ -322,6 +403,8 @@ private boolean isCellsSourceSelected() { private List getCells() { List cells = new ArrayList<>(); + wakeUp(); + String operator = mTelephonyManager.getNetworkOperator(); String mnc; int mcc; @@ -335,9 +418,11 @@ private List getCells() { mcc = 0; mnc = ""; } - + CellLocation cellLocation = mTelephonyManager.getCellLocation(); + appendLog(TAG, "getCells():cellLocation:" + cellLocation); + if (cellLocation != null) { if (cellLocation instanceof GsmCellLocation) { Cell cell = new Cell(); @@ -346,23 +431,29 @@ private List getCells() { cell.mcc = mcc; cell.mnc = mnc; cell.technology = TECHNOLOGY_MAP().get(mTelephonyManager.getNetworkType()); + appendLog(TAG, String.format("GsmCellLocation for %d|%s|%d|%d|%s|%d", cell.mcc, cell.mnc, cell.area, cell.cellId, cell.technology, ((GsmCellLocation) cellLocation).getPsc())); Log.d(TAG, String.format("GsmCellLocation for %d|%s|%d|%d|%s|%d", cell.mcc, cell.mnc, cell.area, cell.cellId, cell.technology, ((GsmCellLocation) cellLocation).getPsc())); cells.add(cell); } else if (cellLocation instanceof CdmaCellLocation) { - Log.w(TAG, "CdmaCellLocation: Using CDMA cells for NLP is not yet implemented"); - } else - Log.wtf(TAG, "Got a CellLocation of an unknown class"); + appendLog(TAG, "getCells():cellLocation - CdmaCellLocation: Using CDMA cells for NLP is not yet implemented"); + Log.w(TAG, "CdmaCellLocation: Using CDMA cells for NLP is not yet implemented"); + } else { + appendLog(TAG, "getCells():cellLocation - Got a CellLocation of an unknown class"); + Log.wtf(TAG, "Got a CellLocation of an unknown class"); + } } else { Log.d(TAG, "getCellLocation returned null"); } List neighboringCells = mTelephonyManager.getNeighboringCellInfo(); + appendLog(TAG, "getCells():neighboringCells:" + neighboringCells); if (neighboringCells != null) { + appendLog(TAG, "getCells():neighboringCells.size:" + neighboringCells.size()); Log.d(TAG, "getNeighboringCellInfo found " + neighboringCells.size() + " cells"); } else { Log.d(TAG, "getNeighboringCellInfo returned null"); } - + if (neighboringCells != null) { for (NeighboringCellInfo c : neighboringCells) { Cell cell = new Cell(); @@ -371,6 +462,7 @@ private List getCells() { cell.mcc = mcc; cell.mnc = mnc; cell.technology = TECHNOLOGY_MAP().get(c.getNetworkType()); + appendLog(TAG, String.format("getCells():NeighboringCellInfo for %d|%s|%d|%d|%s|%d", cell.mcc, cell.mnc, cell.area, cell.cellId, cell.technology, c.getPsc())); Log.d(TAG, String.format("NeighboringCellInfo for %d|%s|%d|%d|%s|%d", cell.mcc, cell.mnc, cell.area, cell.cellId, cell.technology, c.getPsc())); cells.add(cell); } @@ -378,56 +470,79 @@ private List getCells() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { List cellsRawList = mTelephonyManager.getAllCellInfo(); + appendLog(TAG, "getCells():getAllCellInfo:cellsRawList:" + cellsRawList); if (cellsRawList != null) { - Log.d(TAG, "getAllCellInfo found " + cellsRawList.size() + " cells"); + appendLog(TAG, "getCells():cellsRawList.size:" + cellsRawList.size()); + Log.d(TAG, "getAllCellInfo found " + cellsRawList.size() + " cells"); } else { - Log.d(TAG, "getAllCellInfo returned null"); + Log.d(TAG, "getAllCellInfo returned null"); } - if (cellsRawList != null) { - for (CellInfo c : cellsRawList) { - Cell cell = new Cell(); - if (c instanceof CellInfoGsm) { - //Log.v(TAG, "GSM cell found"); - cell.cellId = ((CellInfoGsm) c).getCellIdentity().getCid(); - cell.area = ((CellInfoGsm) c).getCellIdentity().getLac(); - cell.mcc = ((CellInfoGsm)c).getCellIdentity().getMcc(); - cell.mnc = String.valueOf(((CellInfoGsm)c).getCellIdentity().getMnc()); - cell.technology = TECHNOLOGY_MAP().get(mTelephonyManager.getNetworkType()); - Log.d(TAG, String.format("CellInfoGsm for %d|%s|%d|%d|%s", cell.mcc, cell.mnc, cell.area, cell.cellId, cell.technology)); - } else if (c instanceof CellInfoCdma) { - /* - object.put("cellId", ((CellInfoCdma)s).getCellIdentity().getBasestationId()); - object.put("locationAreaCode", ((CellInfoCdma)s).getCellIdentity().getLac()); - object.put("mobileCountryCode", ((CellInfoCdma)s).getCellIdentity().get()); - object.put("mobileNetworkCode", ((CellInfoCdma)s).getCellIdentity().getMnc());*/ - Log.wtf(TAG, "Using of CDMA cells for NLP not yet implemented"); - } else if (c instanceof CellInfoLte) { - //Log.v(TAG, "LTE cell found"); - cell.cellId = ((CellInfoLte) c).getCellIdentity().getCi(); - cell.area = ((CellInfoLte) c).getCellIdentity().getTac(); - cell.mcc = ((CellInfoLte)c).getCellIdentity().getMcc(); - cell.mnc = String.valueOf(((CellInfoLte)c).getCellIdentity().getMnc()); - cell.technology = TECHNOLOGY_MAP().get(mTelephonyManager.getNetworkType()); - Log.d(TAG, String.format("CellInfoLte for %d|%s|%d|%d|%s|%d", cell.mcc, cell.mnc, cell.area, cell.cellId, cell.technology, ((CellInfoLte)c).getCellIdentity().getPci())); - } else if (c instanceof CellInfoWcdma) { - //Log.v(TAG, "CellInfoWcdma cell found"); - cell.cellId = ((CellInfoWcdma) c).getCellIdentity().getCid(); - cell.area = ((CellInfoWcdma) c).getCellIdentity().getLac(); - cell.mcc = ((CellInfoWcdma)c).getCellIdentity().getMcc(); - cell.mnc = String.valueOf(((CellInfoWcdma)c).getCellIdentity().getMnc()); - cell.technology = TECHNOLOGY_MAP().get(mTelephonyManager.getNetworkType()); - Log.d(TAG, String.format("CellInfoWcdma for %d|%s|%d|%d|%s|%d", cell.mcc, cell.mnc, cell.area, cell.cellId, cell.technology, ((CellInfoWcdma) c).getCellIdentity().getPsc())); - } - cells.add(cell); - } + if ((cellsRawList != null) && !cellsRawList.isEmpty()) { + processCellInfoList(cellsRawList, cells); } } else { Log.d(TAG, "getAllCellInfo is not available (requires API 17)"); } + + if (wakeLock != null) { + try { + appendLog(TAG, "getCells():releasing wakeLock"); + wakeLock.release(); + } catch (Throwable th) { + // ignoring this exception, probably wakeLock was already released + } + } + + appendLog(TAG, "getCells():return cells.size: " + cells.size()); return cells; } - + + private void processCellInfoList(List cellInfoList, List cells) { + for (CellInfo c : cellInfoList) { + Cell cell = new Cell(); + if (c instanceof CellInfoGsm) { + //Log.v(TAG, "GSM cell found"); + cell.cellId = ((CellInfoGsm) c).getCellIdentity().getCid(); + cell.area = ((CellInfoGsm) c).getCellIdentity().getLac(); + cell.mcc = ((CellInfoGsm)c).getCellIdentity().getMcc(); + cell.mnc = String.valueOf(((CellInfoGsm)c).getCellIdentity().getMnc()); + cell.technology = TECHNOLOGY_MAP().get(mTelephonyManager.getNetworkType()); + appendLog(TAG, String.format("CellInfoGsm for %d|%s|%d|%d|%s", cell.mcc, cell.mnc, cell.area, cell.cellId, cell.technology)); + Log.d(TAG, String.format("CellInfoGsm for %d|%s|%d|%d|%s", cell.mcc, cell.mnc, cell.area, cell.cellId, cell.technology)); + } else if (c instanceof CellInfoCdma) { + /* + object.put("cellId", ((CellInfoCdma)s).getCellIdentity().getBasestationId()); + object.put("locationAreaCode", ((CellInfoCdma)s).getCellIdentity().getLac()); + object.put("mobileCountryCode", ((CellInfoCdma)s).getCellIdentity().get()); + object.put("mobileNetworkCode", ((CellInfoCdma)s).getCellIdentity().getMnc());*/ + appendLog(TAG, ":Using of CDMA cells for NLP not yet implemented"); + Log.wtf(TAG, "Using of CDMA cells for NLP not yet implemented"); + } else if (c instanceof CellInfoLte) { + //Log.v(TAG, "LTE cell found"); + cell.cellId = ((CellInfoLte) c).getCellIdentity().getCi(); + cell.area = ((CellInfoLte) c).getCellIdentity().getTac(); + cell.mcc = ((CellInfoLte)c).getCellIdentity().getMcc(); + cell.mnc = String.valueOf(((CellInfoLte)c).getCellIdentity().getMnc()); + cell.technology = TECHNOLOGY_MAP().get(mTelephonyManager.getNetworkType()); + appendLog(TAG, String.format("CellInfoLte for %d|%s|%d|%d|%s|%d", cell.mcc, cell.mnc, cell.area, cell.cellId, cell.technology, ((CellInfoLte)c).getCellIdentity().getPci())); + Log.d(TAG, String.format("CellInfoLte for %d|%s|%d|%d|%s|%d", cell.mcc, cell.mnc, cell.area, cell.cellId, cell.technology, ((CellInfoLte)c).getCellIdentity().getPci())); + } else if (c instanceof CellInfoWcdma) { + //Log.v(TAG, "CellInfoWcdma cell found"); + cell.cellId = ((CellInfoWcdma) c).getCellIdentity().getCid(); + cell.area = ((CellInfoWcdma) c).getCellIdentity().getLac(); + cell.mcc = ((CellInfoWcdma)c).getCellIdentity().getMcc(); + cell.mnc = String.valueOf(((CellInfoWcdma)c).getCellIdentity().getMnc()); + cell.technology = TECHNOLOGY_MAP().get(mTelephonyManager.getNetworkType()); + appendLog(TAG, String.format("CellInfoWcdma for %d|%s|%d|%d|%s|%d", cell.mcc, cell.mnc, cell.area, cell.cellId, cell.technology, ((CellInfoWcdma) c).getCellIdentity().getPsc())); + Log.d(TAG, String.format("CellInfoWcdma for %d|%s|%d|%d|%s|%d", cell.mcc, cell.mnc, cell.area, cell.cellId, cell.technology, ((CellInfoWcdma) c).getCellIdentity().getPsc())); + } else { + appendLog(TAG, "CellInfo of unexpected type: " + c); + } + cells.add(cell); + } + } + /** * Checks whether we can scan wifis * @return @@ -446,6 +561,8 @@ public boolean isWifiSupported() { public Location onLocationReceived(Location location) { if (location == null) { Log.i(TAG, "Location was null, ignoring"); + appendLog(TAG, " Location is null"); + report(null); return null; } @@ -456,7 +573,7 @@ public Location onLocationReceived(Location location) { Log.d(TAG, "[UnifiedNlp Results]: Est. Speed " + Math.round(location.distanceTo(last) / (location.getTime() - last.getTime() / 1000 / 60)) + " km/h"); } } - + report(location); last = location; diff --git a/src/org/openbmap/unifiedNlp/utils/LogToFile.java b/src/org/openbmap/unifiedNlp/utils/LogToFile.java new file mode 100644 index 0000000..fe796e8 --- /dev/null +++ b/src/org/openbmap/unifiedNlp/utils/LogToFile.java @@ -0,0 +1,107 @@ +package org.openbmap.unifiedNlp.utils; + +import android.util.Log; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; + +public class LogToFile { + + private static final String TAG = LogToFile.class.getName(); + + private static final String TIME_DATE_PATTERN = "yyyy-MM-dd HH:mm:ss.SSS"; + + private static final SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat(TIME_DATE_PATTERN); + + public static String logFilePathname; + public static boolean logToFileEnabled; + public static int logFileHoursOfLasting; + private static Calendar logFileAtTheEndOfLive; + + public static void appendLog(String tag, String text) { + appendLog(tag, text, null); + } + + public static void appendLog(String tag, String text, Throwable throwable) { + + if (!logToFileEnabled || (logFilePathname == null)) { + return; + } + + File logFile = new File(logFilePathname); + + Date now = new Date(); + try { + if (logFile.exists()) { + if (logFileAtTheEndOfLive == null) { + boolean succeeded = initFileLogging(logFile); + if (!succeeded) { + createNewLogFile(logFile, now); + } + } else if(Calendar.getInstance().after(logFileAtTheEndOfLive)) { + logFile.delete(); + createNewLogFile(logFile, now); + } + } else { + createNewLogFile(logFile, now); + } + BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true)); + buf.append(DATE_FORMATTER.format(now)); + buf.append(" "); + buf.append(tag); + buf.append(" - "); + buf.append(text); + if (throwable != null) { + buf.append(" - "); + buf.append(throwable.getMessage()); + for (StackTraceElement ste: throwable.getStackTrace()) { + buf.newLine(); + buf.append(ste.toString()); + } + } + buf.newLine(); + buf.close(); + } catch (IOException e) { + Log.e(TAG, e.getMessage()); + } + } + + private static boolean initFileLogging(File logFile) { + char[] logFileDateCreatedBytes = new char[TIME_DATE_PATTERN.length()]; + Date logFileDateCreated; + FileReader logFileReader = null; + try { + logFileReader = new FileReader(logFile); + logFileReader.read(logFileDateCreatedBytes); + logFileDateCreated = DATE_FORMATTER.parse(new String(logFileDateCreatedBytes)); + } catch (Exception e) { + return false; + } finally { + if (logFileReader != null) { + try { + logFileReader.close(); + } catch (IOException ex) { + + } + } + } + initEndOfLive(logFileDateCreated); + return true; + } + + private static void initEndOfLive(Date logFileDateCreated) { + logFileAtTheEndOfLive = Calendar.getInstance(); + logFileAtTheEndOfLive.setTime(logFileDateCreated); + logFileAtTheEndOfLive.add(Calendar.HOUR_OF_DAY, logFileHoursOfLasting); + } + + private static void createNewLogFile(File logFile, Date dateOfCreation) throws IOException { + logFile.createNewFile(); + initEndOfLive(dateOfCreation); + } +} From 5cd51da3583e4623efa8d9a790242a5e15288603 Mon Sep 17 00:00:00 2001 From: tomas Date: Sun, 8 Oct 2017 20:02:22 +0200 Subject: [PATCH 3/3] Move to commont directory selector for logging --- build.gradle | 3 +- res/values-ja/strings.xml | 2 +- res/values/strings.xml | 3 +- res/xml/preferences.xml | 13 +------ .../openbmap/unifiedNlp/SettingsActivity.java | 39 +++++++++++-------- 5 files changed, 29 insertions(+), 31 deletions(-) diff --git a/build.gradle b/build.gradle index ffc0e9c..114cddd 100644 --- a/build.gradle +++ b/build.gradle @@ -28,13 +28,14 @@ apply plugin: 'com.android.application' repositories { mavenCentral() + jcenter() } dependencies { compile group: 'org.microg', name: 'unifiednlp-api', version: '1.5.4' compile 'ch.acra:acra:4.5.0' compile 'com.android.support:support-v4:25.3.1' - compile 'com.github.angads25:filepicker:1.1.1' + compile 'com.obsez.android.lib.filechooser:filechooser:1.1.5' } android { diff --git a/res/values-ja/strings.xml b/res/values-ja/strings.xml index af1ca99..74770c9 100644 --- a/res/values-ja/strings.xml +++ b/res/values-ja/strings.xml @@ -27,7 +27,7 @@ オペレーションモード ジオロケーションに使用するデータを選択\n(WiFi と基地局、WiFi のみ、基地局のみ) 基地局/WiFiを使用しますか? - ダウンロードに失敗しました! (エラーコード %d) + ダウンロードに失敗しました! (エラーコード %s) 設定 新しいフォルダーを作成 無効なダウンロード diff --git a/res/values/strings.xml b/res/values/strings.xml index 09dddab..2921427 100644 --- a/res/values/strings.xml +++ b/res/values/strings.xml @@ -28,7 +28,7 @@ Operation mode Select which data is used for geolocation\n(Wifis and Cells, Wifis only, Cells only) Use cells/wifis? - Download failed! (Error code %d) + Download failed! (Error code %s) Preferences Create new folder Invalid download @@ -44,6 +44,7 @@ No wake up Wake up CPU only Wake up with display + Select directory for logging After specified number of time log file will recreated Rotation of the log file 12 hours diff --git a/res/xml/preferences.xml b/res/xml/preferences.xml index cf98693..848f56d 100644 --- a/res/xml/preferences.xml +++ b/res/xml/preferences.xml @@ -69,17 +69,8 @@ android:key="debug.file.lasting.hours" android:summary="@string/log_file_lasting_summary" android:title="@string/log_file_lasting_title"/> - +