Back to project page twawm2.
The source code is released under:
Copyright (c) 2014, afnf All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistr...
If you think the Android project twawm2 listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
package com.appspot.afnf4199ga.twawm.app; /*w ww. jav a 2 s. c om*/ import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.appwidget.AppWidgetManager; import android.bluetooth.BluetoothAdapter; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.NetworkInfo.DetailedState; import android.net.wifi.ScanResult; import android.net.wifi.SupplicantState; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Build; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.support.v4.app.NotificationCompat; import com.appspot.afnf4199ga.twawm.BluetoothHelper; import com.appspot.afnf4199ga.twawm.Const; import com.appspot.afnf4199ga.twawm.OnlineChecker; import com.appspot.afnf4199ga.twawm.StateMachine; import com.appspot.afnf4199ga.twawm.StateMachine.STATE; import com.appspot.afnf4199ga.twawm.StateMachine.TRIGGER; import com.appspot.afnf4199ga.twawm.app.MainActivity.ACTIVITY_FLAG; import com.appspot.afnf4199ga.twawm.router.EcoModeControl; import com.appspot.afnf4199ga.twawm.router.RouterControl; import com.appspot.afnf4199ga.twawm.router.RouterControlByHttp; import com.appspot.afnf4199ga.twawm.router.RouterControlByHttp.CTRL; import com.appspot.afnf4199ga.utils.AndroidUtils; import com.appspot.afnf4199ga.utils.Logger; import com.appspot.afnf4199ga.utils.MyStringUtlis; import net.afnf.and.twawm2.R; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; public class BackgroundService extends Service { private static BackgroundService instance; private WifiManager wifi; private ConnectivityManager conn; private PowerManager power; private WakeLock wakelock = null; private Thread watchdogThread; private OnlineChecker onlineCheckerThread; private StateMachine state; private boolean shortIntervalCheck = false; private int shortIntervalCount = 0; private boolean receiverRegisted = false; private BluetoothHelper btHelper = null; private Boolean ecoCharge = null; private int onlineCheckCompleteCount = 0; private String prevNotifyText = ""; private NotificationCompat.Builder notificationBuilder; @Override public IBinder onBind(Intent arg0) { return null; } @Override public void onCreate() { Logger.v("BackgroundService onCreate"); // ??????? super.onCreate(); instance = this; wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); conn = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); power = (PowerManager) getSystemService(Context.POWER_SERVICE); state = new StateMachine(); shortIntervalCheck = false; shortIntervalCount = 0; receiverRegisted = false; btHelper = null; ecoCharge = null; onlineCheckCompleteCount = 0; prevNotifyText = ""; notificationBuilder = null; // ??????? boolean enabled = AndroidUtils.isWifiEnabled(wifi); state.init(enabled); // ?????????? if (Const.getPrefWorking(this)) { // registerReceiver final IntentFilter filter = new IntentFilter(); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION); filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); filter.addAction(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); receiverRegisted = true; registerReceiver(broadcastReceiver, filter); // ?????? state.perform(TRIGGER.BOOT); // ?????????setClickIntent???????????? DefaultWidgetProvider.setClickIntent(this); // ??????????????????????? postNotify(R.drawable.ntficon_wimax_gray_batt_na, getString(R.string.service_started_long)); } // ??????? else { // UIAct??????????????????????? MainActivity.startActivity(this, ACTIVITY_FLAG.NONE); // Toast UIAct.toast(getString(R.string.pausing_long)); // ???????????Activity?????????? } } @Override public int onStartCommand(Intent intent, int flags, int startId) { // ?????????? Logger.setEnableLogging(Const.isPrefLoggingEnabled(this)); Logger.v("BackgroundService onStartCommand intent=" + AndroidUtils.getActionForLog(intent)); if (intent != null) { // ?????????? if (Const.getPrefWorking(this)) { state.reflesh(false); state.resetTextLock(); state.resetRouterSwitchLock(); // ??????CLICK???intent????????????? if (AndroidUtils.isActionEquals(intent, Const.INTENT_WD_CLICKED)) { // ??????????? int widgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1); DefaultWidgetProvider.showClickAnimation(this, widgetId); // ????????????????????? String action; // wifi??? if (isWifiDisabledState()) { action = Const.getPrefWidgetClickActionWifiDisabled(this); } // ?????? else if (state.isOnline()) { action = Const.getPrefWidgetClickActionOnline(this); } // ??????????????????? else { action = Const.getPrefWidgetClickActionOffline(this); } // ??????? doAction(action); } // ?????????? else if (intent.getBooleanExtra(Const.INTENT_EX_TOGGLE_ROUTER, false)) { Logger.v("BackgroundService onStartCommand EX_TOGGLE_ROUTER"); toggleRouterFromUI(false); } // Wifi??? else if (intent.getBooleanExtra(Const.INTENT_EX_TOGGLE_WIFI, false)) { Logger.v("BackgroundService onStartCommand EX_TOGGLE_WIFI"); toggleWifiFromUI(); } // ??????? else { String action = intent.getStringExtra(Const.INTENT_EX_DO_ACTION); if (MyStringUtlis.isEmpty(action) == false) { doAction(action); } } } } return super.onStartCommand(intent, flags, startId); } @Override public void onLowMemory() { // ?????????? Logger.startFlushThread(false); super.onLowMemory(); } @Override public void onDestroy() { // ?????????? Logger.setEnableLogging(Const.isPrefLoggingEnabled(this)); Logger.v("BackgroundService onDestroy"); // ?????? getStateMachine().stopBattCalc(this); releaseWakeLock(); // ????????????????????? if (Const.isStatusBarNotifyNever(this) == false) { // ???????????????? stopForeground(true); } // ???? NotificationManager nman = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); nman.cancel(Const.NOTIF_ID_MAIN); nman.cancel(Const.NOTIF_ID_HEADSUP); if (receiverRegisted) { unregisterReceiver(broadcastReceiver); receiverRegisted = false; } stopWatchdog(); terminateOnlineCheck(); instance = null; notificationBuilder = null; // ?????????? Logger.startFlushThread(true); super.onDestroy(); } public void onBluetoothDisabled() { state.perform(TRIGGER.BT_DISABLED); } public void onBluetoothEnabled() { state.perform(TRIGGER.BT_ENABLED); } public void onBluetoothConnectedBeforeDisabling() { // NetworkSwitcher???? NetworkSwitcher.init(); } public void onBluetoothConnected(boolean success) { // ????????????????? if (success == false) { postNotify(R.drawable.ntficon_wimax_gray_batt_na, getString(R.string.bluetooth_failed_long)); } // ?????? if (btHelper != null) { btHelper.finish(); btHelper = null; } // ?????????????????? state.perform(TRIGGER.BT_CONNECTED); } public void onStandbyComplete(boolean success) { stopWatchdog(); state.perform(success ? TRIGGER.STANDBY_OK : TRIGGER.STANDBY_NG); } public void onOnlineCheckComplete(TRIGGER result, boolean becomeOnline) { releaseWakeLock(); // ???????????????????????????????????????? boolean willstop = false; if (result == TRIGGER.NOT_WM && Const.getPrefNonTargetRouterActionStopService(this)) { willstop = true; // ????????????? stopServiceWithDelay(); } // ???????????????????????WM????????????????? else if (result == TRIGGER.ONLINE || result == TRIGGER.NOT_WM) { // ????????????????????? resetShortInterval(); // ??????????????SSID??? if (result == TRIGGER.ONLINE) { String ssid = wifi.getConnectionInfo().getSSID(); Const.updatePrefLastTargetRouterInfo(this, ssid); } } // ????????????? else { // ?????????????? if (++shortIntervalCount < Const.getPrefOnlineCheckCountAfterOffline(this)) { // ????????????????????? shortIntervalCheck = true; } // ?????????????? else { // ????????????????????? resetShortInterval(); } } // ?????? state.perform(result); // ???????????????????????? if (willstop == false) { // WM?????????? if (RouterControlByHttp.isNad() == false) { // 100????????????????????????????????????????????????????????????? if (++onlineCheckCompleteCount % 100 == 0 || becomeOnline) { EcoModeControl.changeEcoMode(null); } } // ??????????????WM???????????????? if (state.isRouterSwitchLocked() && result == TRIGGER.NOT_WM) { // ???????????????????????????????????????????????? state.lockRouterSwitch(); // ????????????????????????perform???????????? startScan(); } } } private void startScan() { // WM???SSID??????????????????? if (MyStringUtlis.isEmpty(Const.getPrefLastTargetSSID(this)) == false) { // ?? Logger.i("switching started"); postNotify(R.drawable.ntficon_wimax_gray_batt_na, getString(R.string.switching_router)); // 10??????????????? new Thread(new Runnable() { @Override public void run() { AndroidUtils.sleep(Const.WIFI_SCAN_DELAY_AFTER_RESUME); wifi.startScan(); } }).start(); } } private void onScanResultsAvailable() { // ??????????????????NOT_WM??????????????????????? if (state.isRouterSwitchLocked() == false || state.getState() != STATE.NOT_WM) { return; } try { // ????? List<ScanResult> scanResults = wifi.getScanResults(); if (scanResults == null || scanResults.size() == 0) { return; } // ?????????????????????????? List<WifiConfiguration> configuredNetworks = wifi.getConfiguredNetworks(); if (configuredNetworks == null || configuredNetworks.size() == 0) { return; } // ?????????????ID?????????????? final int currentNetworkId = wifi.getConnectionInfo().getNetworkId(); // ??????????????????ID????? Set<Integer> switchTargetNetworkIdSet = getSwitchTargetNetworkIdSet(wifi.getConnectionInfo(), Const.getPrefLastTargetSSID(this), scanResults, configuredNetworks); // ????????????? if (switchTargetNetworkIdSet != null) { Iterator<Integer> ite = switchTargetNetworkIdSet.iterator(); while (ite.hasNext()) { // ????????????????????????????????? Integer switchTargetNetworkId = ite.next(); boolean success = wifi.enableNetwork(switchTargetNetworkId, true); Logger.i("switching network " + (success ? "succeeded" : "failed")); // ??????????????????????????????????????????????? if (success) { // ?????????? state.resetRouterSwitchLock(); // ????IP????????????? if (MyStringUtlis.isEmpty(Const.getPrefApIpAddr(this))) { UIAct.toast(getString(R.string.router_ip_addr_not_set)); } // ???????????????????????????????????20????????? // TODO Thread????????????????????? new Thread(new Runnable() { @Override public void run() { AndroidUtils.sleep(20000); wifi.enableNetwork(currentNetworkId, false); } }).start(); return; } } } } catch (Throwable e) { Logger.w("onScanResultsAvailableWhenNotWM failed", e); } } protected static Set<Integer> getSwitchTargetNetworkIdSet(WifiInfo connectionInfo, String confssid, List<ScanResult> scanResults, List<WifiConfiguration> configuredNetworks) { // ???????SSID?????????????????? if (connectionInfo == null) { return null; } String current_ssid = connectionInfo.getSSID(); if (MyStringUtlis.isEmpty(current_ssid)) { return null; } current_ssid = MyStringUtlis.trimQuote(current_ssid); // ????? if (scanResults == null || scanResults.size() == 0) { return null; } if (configuredNetworks == null || configuredNetworks.size() == 0) { return null; } // ?????SSID?????????????? if (MyStringUtlis.isEmpty(confssid)) { Logger.i("switching terminated : confssid is blank"); return null; } // ???????SSID?????????????????????????????????????????WM????????????????????????????????????? if (MyStringUtlis.eqauls(confssid, current_ssid)) { Logger.i("switching terminated : confssid matched"); return null; } // ???????????????ID Set<Integer> switchTargetNetworkIdList = new LinkedHashSet<Integer>(); // ????????????? boolean found = false; Iterator<ScanResult> ite = scanResults.iterator(); SR: while (ite.hasNext()) { ScanResult scanResult = (ScanResult) ite.next(); // ????????????????????SSID???????????????????? String sssid = MyStringUtlis.trimQuote(scanResult.SSID); if (MyStringUtlis.eqauls(sssid, confssid)) { // ????????????????????? for (WifiConfiguration wc : configuredNetworks) { // ???????????? // ?wifiConfiguration.SSID????????????????????????? String wcssid = MyStringUtlis.trimQuote(wc.SSID); if (MyStringUtlis.eqauls(wcssid, confssid)) { switchTargetNetworkIdList.add(wc.networkId); found = true; break SR; } } } } if (found) { return switchTargetNetworkIdList; } else { Logger.i("switching terminated : target not found"); return null; } } public void onEcoModeControlFinished(Boolean ecoCharge) { //Logger.i("onEcoModeControlFinished : " + ecoMode); this.ecoCharge = ecoCharge; boolean wifiEnabled = AndroidUtils.isWifiEnabled(getWifi()); boolean suppCompleted = wifiEnabled && isSupplicantCompleted(); UIAct.postActivityButton(null, null, wifiEnabled, suppCompleted, ecoCharge, null, null); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public void disableBT() { synchronized (BackgroundService.class) { if (btHelper != null) { btHelper.finish(); } btHelper = new BluetoothHelper(this); } // Bluetooth????????????????????????? if (Const.isPrefBtRestartType(this) == false) { state.perform(TRIGGER.BT_DISABLED); } // ????????????? else { btHelper.disable(); } } public void enableBT() { if (btHelper == null) { Logger.e("btHelper is null on BackgroundService.enableBT"); return; } btHelper.enable(); } public void bluetoothResume() { if (btHelper == null) { Logger.e("btHelper is null on BackgroundService.bluetoothResume"); return; } btHelper.connect(); } public void enableWifi() { stopWatchdog(); if (AndroidUtils.isWifiEnabled(wifi)) { state.perform(TRIGGER.BC_WIFI_ENABLED); } else { startWatchdogOnApConn(); wifi.setWifiEnabled(true); } } public void waitSupplicantComplete() { stopWatchdog(); resetShortInterval(); // ?????????? NetworkSwitcher.disableNetwork(this); // ????????SupplicantState?????? if (getConnectivityState() == ConnectivityState.COMPLETE_WIFI) { state.perform(TRIGGER.BC_SUPPLICANT_COMPLETE); } else { startWatchdogOnApConn(); } } public void checkOnline() { // ?????????? NetworkSwitcher.reEnableWithoutD(); state.resetTextLock(); startOnlineCheck(0); } public void checkOnlineWithDelay() { startOnlineCheck(Const.getPrefOnlineCheckIntervalMs(this)); } public void standby() { // ?????? getStateMachine().stopBattCalc(this); // ??????????????NetState???AP????????? state.setNetStateToNoAP(); // ?????????????? terminateOnlineCheck(); // ???????? RouterControl.execStandby(); startWatchdog(); } public void disableWifi() { terminateOnlineCheck(); if (AndroidUtils.isWifiDisabled(wifi)) { state.perform(TRIGGER.BC_WIFI_DISABLED); } else { startWatchdog(); wifi.setWifiEnabled(false); } } public void wifiDisabled() { stopServiceImmediately(); } public void stopServiceImmediately() { BackgroundService service = BackgroundService.getInstance(); if (service != null) { // ???????? Intent intent = new Intent(this, BackgroundService.class); stopService(intent); instance = null; // ????????????????????????????????????????????????????????? // NetworkSwitcher???? NetworkSwitcher.reset(); } } public void stopServiceWithDelay() { new Thread(new Runnable() { @Override public void run() { AndroidUtils.sleep(Const.SERVICE_STOP_DELAY_MS); stopServiceImmediately(); } }).start(); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// private void doAction(String action) { // NetworkSwitcher???? NetworkSwitcher.reset(); // do nothing if (MyStringUtlis.eqauls(action, getString(R.string.menu_widget_click_action__none))) { } // ?????????? else if (MyStringUtlis.eqauls(action, getString(R.string.menu_widget_click_action__check))) { resetShortInterval(); terminateOnlineCheck(); startOnlineCheck(0); } // ?????? + ?????????? else if (MyStringUtlis.eqauls(action, getString(R.string.menu_widget_click_action__resume_switch))) { state.lockRouterSwitch(); toggleRouterFromUI(true); } // ?????????? else if (MyStringUtlis.eqauls(action, getString(R.string.menu_widget_click_action__switch))) { if (state.getState() == STATE.NOT_WM) { state.lockRouterSwitch(); startScan(); } } // ?????? + WiFi ON else if (MyStringUtlis.eqauls(action, getString(R.string.menu_widget_click_action__resume))) { toggleRouterFromUI(true); } // ?????? else if (MyStringUtlis.eqauls(action, getString(R.string.menu_widget_click_action__standby))) { terminateOnlineCheck(); state.perform(TRIGGER.BUTTON_STANDBY); } // WiFi ON else if (MyStringUtlis.eqauls(action, getString(R.string.menu_widget_click_action__wifi_on))) { state.perform(TRIGGER.BUTTON_WIFI_ON); } // WiFi OFF else if (MyStringUtlis.eqauls(action, getString(R.string.menu_widget_click_action__wifi_off))) { terminateOnlineCheck(); state.perform(TRIGGER.BUTTON_WIFI_OFF); } // WiFi????? else if (MyStringUtlis.eqauls(action, getString(R.string.menu_widget_click_action__restart))) { state.setStateToWifiRestart(); } // WiMAX???? else if (MyStringUtlis.eqauls(action, getString(R.string.menu_widget_click_action__wimax_recn))) { // ???????????????????????????????????????? if (RouterControlByHttp.isWm3800FirmwareVersionOld()) { UIAct.toast(getString(R.string.wimax_recn_failed_frmver)); } else if (state.isWmReachableState()) { terminateOnlineCheck(); RouterControl.execWimaxReconnection(); } } // ???????? else if (MyStringUtlis.eqauls(action, getString(R.string.menu_widget_click_action__reboot_wm))) { if (state.isWmReachableState()) { terminateOnlineCheck(); RouterControl.execRouterCtrl(CTRL.REBOOT_WM); } } // ???????? else if (MyStringUtlis.eqauls(action, getString(R.string.menu_widget_click_action__stop_service))) { MainActivity.updateAsWorkingOrPausing(this, true); stopServiceImmediately(); } // ?????????? else if (MyStringUtlis.eqauls(action, getString(R.string.menu_widget_click_action__choose))) { MainActivity.startActivity(this, ACTIVITY_FLAG.ACTION_DIALOG); } // FIXME NAD11??????? } private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(final Context context, final Intent intent) { //Logger.v("BackgroundService broadcastReceiver intent=" + Utils.getActionForLog(intent)); // ?????????? if (Const.getPrefWorking(context)) { // Bluetooth???? if (AndroidUtils.isActionEquals(intent, BluetoothAdapter.ACTION_STATE_CHANGED)) { int bt_state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_OFF); if (bt_state == BluetoothAdapter.STATE_ON) { state.perform(TRIGGER.BT_ENABLED); } else if (bt_state == BluetoothAdapter.STATE_OFF) { state.perform(TRIGGER.BT_DISABLED); } } // WiFi???? else if (AndroidUtils.isActionEquals(intent, WifiManager.WIFI_STATE_CHANGED_ACTION)) { int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_ENABLING); boolean enabled = wifiState == WifiManager.WIFI_STATE_ENABLED; boolean disabled = wifiState == WifiManager.WIFI_STATE_DISABLED; boolean disabling = wifiState == WifiManager.WIFI_STATE_DISABLING; // ?????????ConnectivityManager??????? if (enabled) { conn = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); } if (enabled || disabled) { boolean byThisApp = stopWatchdog(); // ?????????WiFi?????????????????????????????resetTextLock?????????????????????????????????????????? if (byThisApp == false) { state.resetTextLock(); // ????????????????????????????????????????????????resetAll?????????????????? } } // perform if (enabled) { state.perform(TRIGGER.BC_WIFI_ENABLED); } else if (disabled) { // NetworkSwitcher???? NetworkSwitcher.reset(); state.perform(TRIGGER.BC_WIFI_DISABLED); } else if (disabling) { state.perform(TRIGGER.BC_WIFI_DISABLING); } } // supplicant???? else if (AndroidUtils.isActionEquals(intent, WifiManager.SUPPLICANT_STATE_CHANGED_ACTION) || AndroidUtils.isActionEquals(intent, ConnectivityManager.CONNECTIVITY_ACTION)) { if (state.isSupplicantEnableWaitState() && getConnectivityState() == ConnectivityState.COMPLETE_WIFI) { stopWatchdog(); resetShortInterval(); state.perform(TRIGGER.BC_SUPPLICANT_COMPLETE); } else if (AndroidUtils.isActionEquals(intent, WifiManager.SUPPLICANT_STATE_CHANGED_ACTION)) { SupplicantState newstate = intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE); if (newstate != null && (newstate == SupplicantState.DISCONNECTED || newstate == SupplicantState.DORMANT)) { state.perform(TRIGGER.BC_SUPPLICANT_DISCONNECTED); } } } // ??????? else if (AndroidUtils.isActionEquals(intent, WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) { onScanResultsAvailable(); } // SCREEN_ON else if (AndroidUtils.isActionEquals(intent, Intent.ACTION_SCREEN_ON)) { resetShortInterval(); state.resetTextLock(); state.startBattCalc(context); // WiFi??????????????????????????OFF???????noAP?????????????????????????????????????????????????????????? startOnlineCheck(0); } // SCREEN_OFF else if (AndroidUtils.isActionEquals(intent, Intent.ACTION_SCREEN_OFF)) { state.stopBattCalc(context); terminateOnlineCheck(); } } } }; void startWatchdogOnApConn() { //Logger.v("Watchdog started"); watchdogThread = new WatchdogThread(Const.getPrefApConnTimeoutMs(this)); watchdogThread.start(); } void startWatchdog() { //Logger.v("Watchdog started"); watchdogThread = new WatchdogThread(Const.WATCH_DOG_TIMEOUT_MS); watchdogThread.start(); } /** * @return ?????interrupt????????????true */ boolean stopWatchdog() { if (watchdogThread != null && watchdogThread.isAlive()) { //Logger.v("Watchdog stopped"); watchdogThread.interrupt(); watchdogThread = null; return true; } return false; } class WatchdogThread extends Thread { long timeout_ms = -1; public WatchdogThread(long timeout) { this.timeout_ms = timeout; } @Override public void run() { try { // ???????????????? if (timeout_ms > 0) { Thread.sleep(timeout_ms); } Logger.w("Watchdog timeout error, " + timeout_ms + "ms"); // ?????? state.perform(TRIGGER.WATCHDOG_TIMEOUT); } catch (InterruptedException e) { // interrupt????????????? } catch (Throwable e) { Logger.w("WatchdogThread error", e); } } } public void startOnlineCheck(long delay_ms) { terminateOnlineCheck(); if (delay_ms != 0 && shortIntervalCheck) { delay_ms = Const.getPrefOnlineCheckIntervalMsAfterOffline(this); } // ???????????? Logger.v("OnlineChecker started, delay_ms=" + delay_ms); onlineCheckerThread = new OnlineChecker(delay_ms); onlineCheckerThread.start(); } public void terminateOnlineCheck() { if (onlineCheckerThread != null && onlineCheckerThread.isExecuting()) { Logger.v("OnlineChecker stopped"); onlineCheckerThread.stopThread(); onlineCheckerThread = null; } } public void postNotify(int notifyImageId, String notifyText) { //Logger.v("BackgroundService postNotify"); // ????????????????????? if (Const.isStatusBarNotifyNever(this) == false) { final NotificationManager nman = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // Ticker?????????????????? boolean showTicker = false; if (Const.isStatusBarNotifyAlways(this) || (Const.isStatusBarNotifyWhenChanged(this) && MyStringUtlis.eqauls(notifyText, prevNotifyText) == false)) { showTicker = true; } prevNotifyText = notifyText; // Android4.4?? if (Build.VERSION.SDK_INT <= 20) { // ??????????????Ticker????????? if (notificationBuilder == null || showTicker) { // ?????????????????????????TickerText???????????Ticker????????? stopForeground(true); startForeground(Const.NOTIF_ID_MAIN, createNotification(notifyImageId, notifyText, false)); } // ?????? else { nman.notify(Const.NOTIF_ID_MAIN, createNotification(notifyImageId, notifyText, false)); } } // Android5.0?? else { // ?????????? if (notificationBuilder == null) { startForeground(Const.NOTIF_ID_MAIN, createNotification(notifyImageId, notifyText, false)); } // ?????? else { nman.notify(Const.NOTIF_ID_MAIN, createNotification(notifyImageId, notifyText, false)); } if (showTicker) { // Heads Up Notification??? nman.notify(Const.NOTIF_ID_HEADSUP, createNotification(notifyImageId, notifyText, true)); // 2.5?????????? new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { @Override public void run() { nman.cancel(Const.NOTIF_ID_HEADSUP); } }, 2500); } } } } private Notification createNotification(int notifyImageId, String notifyText, boolean headsUp) { NotificationCompat.Builder builder = null; if (notifyImageId == Const.NOTIF_ID_MAIN && notificationBuilder != null && headsUp == false) { builder = notificationBuilder; } else { Intent notificationIntent = new Intent(this, MainActivity.class); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); builder = new NotificationCompat.Builder(getApplicationContext()); builder.setContentIntent(contentIntent); builder.setContentTitle(getString(R.string.app_name)); builder.setWhen(System.currentTimeMillis()); if (notifyImageId == Const.NOTIF_ID_MAIN) { notificationBuilder = builder; } } if (headsUp) { builder.setCategory(Notification.CATEGORY_SERVICE); builder.setPriority(Notification.PRIORITY_HIGH); builder.setVibrate(new long[]{60000, 100}); // ??????????????????????????????????????? } else { builder.setCategory(null); builder.setPriority(Notification.PRIORITY_DEFAULT); builder.setVibrate(null); } if (Const.isStatusBarNotifyAlways(this) || Const.isStatusBarNotifyWhenChanged(this)) { builder.setTicker(notifyText); } else { builder.setTicker(null); } builder.setSmallIcon(notifyImageId); builder.setContentText(notifyText); return builder.build(); } public void toggleRouterFromUI(boolean forceResume) { boolean resume = forceResume || getConnectivityState() != ConnectivityState.COMPLETE_WIFI; if (resume) { state.resetTextLock(); String bluetoothAddress = Const.getPrefBluetoothAddress(this); if (BluetoothHelper.isValidBluetoothAddress(bluetoothAddress)) { getWakeLock(); state.perform(TRIGGER.BUTTON_BT_RESUME); } else { state.perform(TRIGGER.BUTTON_WIFI_ON); } } else { state.perform(TRIGGER.BUTTON_STANDBY); } } public void toggleWifiFromUI() { boolean enabled = AndroidUtils.isWifiEnabledOrEnabling(wifi); state.perform(enabled ? TRIGGER.BUTTON_WIFI_OFF : TRIGGER.BUTTON_WIFI_ON); } private synchronized void getWakeLock() { if (wakelock == null) { Logger.v("getWakeLock"); wakelock = ((PowerManager) getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Const.LOGTAG); wakelock.acquire(); // TODO Thread????????????????????? new Thread() { public void run() { AndroidUtils.sleep(60000); releaseWakeLock(); } }.start(); } } private synchronized void releaseWakeLock() { if (isWakeLocked()) { Logger.v("releaseWakeLock"); wakelock.release(); wakelock = null; } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static enum ConnectivityState { COMPLETE_WIFI, COMPLETE_MOBILE, STANDBY_OK, NONE } public ConnectivityState getConnectivityState() { if (isSupplicantCompleted()) { ConnectivityState connState = getConnectivityState(conn); if (connState != null) { return connState; } } if (state.isStandbyWaitState()) { return ConnectivityState.STANDBY_OK; } return ConnectivityState.NONE; } protected static ConnectivityState getConnectivityState(ConnectivityManager conn) { if (conn != null) { NetworkInfo activeNetworkInfo = conn.getActiveNetworkInfo(); if (activeNetworkInfo != null) { DetailedState detailedState = activeNetworkInfo.getDetailedState(); if (detailedState == DetailedState.CONNECTED) { int type = activeNetworkInfo.getType(); if (type == ConnectivityManager.TYPE_WIFI) { return ConnectivityState.COMPLETE_WIFI; } else if (type == ConnectivityManager.TYPE_MOBILE || type == ConnectivityManager.TYPE_MOBILE_DUN || type == ConnectivityManager.TYPE_MOBILE_HIPRI || type == ConnectivityManager.TYPE_MOBILE_MMS || type == ConnectivityManager.TYPE_MOBILE_SUPL) { return ConnectivityState.COMPLETE_MOBILE; } } } } return null; } /** * WiFi?????????true???????????????? * * @return */ public boolean isSupplicantCompleted() { return isSupplicantCompleted(wifi); } /** * WiFi?????????true???????????????? * * @param wifi * @return */ public static boolean isSupplicantCompleted(WifiManager wifi) { return wifi.getConnectionInfo().getSupplicantState() == SupplicantState.COMPLETED; } public static BackgroundService getInstance() { return instance; } public boolean isWifiDisabledState() { return getStateMachine().getState() == STATE.WIFI_DISABLED; } public StateMachine getStateMachine() { return state; } public WifiManager getWifi() { return wifi; } public boolean isScreenOn() { return power.isScreenOn(); } private void resetShortInterval() { shortIntervalCheck = false; shortIntervalCount = 0; } public Boolean getEcoCharge() { return ecoCharge; } public boolean isWakeLocked() { return wakelock != null && wakelock.isHeld(); } }