List of usage examples for android.content Intent ACTION_SCREEN_OFF
String ACTION_SCREEN_OFF
To view the source code for android.content Intent ACTION_SCREEN_OFF.
Click Source Link
From source file:com.androzic.MapActivity.java
@Override protected void onResume() { super.onResume(); Log.e(TAG, "onResume()"); SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); Resources resources = getResources(); // update some preferences int speedIdx = Integer.parseInt(settings.getString(getString(R.string.pref_unitspeed), "0")); speedFactor = Double.parseDouble(resources.getStringArray(R.array.speed_factors)[speedIdx]); speedAbbr = resources.getStringArray(R.array.speed_abbrs)[speedIdx]; speedUnit.setText(speedAbbr);/*from ww w . ja v a 2 s .c om*/ int distanceIdx = Integer.parseInt(settings.getString(getString(R.string.pref_unitdistance), "0")); StringFormatter.distanceFactor = Double .parseDouble(resources.getStringArray(R.array.distance_factors)[distanceIdx]); StringFormatter.distanceAbbr = resources.getStringArray(R.array.distance_abbrs)[distanceIdx]; StringFormatter.distanceShortFactor = Double .parseDouble(resources.getStringArray(R.array.distance_factors_short)[distanceIdx]); StringFormatter.distanceShortAbbr = resources.getStringArray(R.array.distance_abbrs_short)[distanceIdx]; int elevationIdx = Integer.parseInt(settings.getString(getString(R.string.pref_unitelevation), "0")); elevationFactor = Double.parseDouble(resources.getStringArray(R.array.elevation_factors)[elevationIdx]); elevationAbbr = resources.getStringArray(R.array.elevation_abbrs)[elevationIdx]; elevationUnit.setText(elevationAbbr); application.angleType = Integer.parseInt(settings.getString(getString(R.string.pref_unitangle), "0")); trackUnit.setText((application.angleType == 0 ? "deg" : getString(R.string.degmag))); bearingUnit.setText((application.angleType == 0 ? "deg" : getString(R.string.degmag))); application.coordinateFormat = Integer .parseInt(settings.getString(getString(R.string.pref_unitcoordinate), "0")); application.sunriseType = Integer.parseInt(settings.getString(getString(R.string.pref_unitsunrise), "0")); renderInterval = settings.getInt(getString(R.string.pref_maprenderinterval), resources.getInteger(R.integer.def_maprenderinterval)) * 100; followOnLocation = settings.getBoolean(getString(R.string.pref_mapfollowonloc), resources.getBoolean(R.bool.def_mapfollowonloc)); magInterval = resources.getInteger(R.integer.def_maginterval) * 1000; showDistance = Integer.parseInt(settings.getString(getString(R.string.pref_showdistance_int), getString(R.string.def_showdistance))); showAccuracy = settings.getBoolean(getString(R.string.pref_showaccuracy), true); autoDim = settings.getBoolean(getString(R.string.pref_mapdim), resources.getBoolean(R.bool.def_mapdim)); dimInterval = settings.getInt(getString(R.string.pref_mapdiminterval), resources.getInteger(R.integer.def_mapdiminterval)) * 1000; dimValue = settings.getInt(getString(R.string.pref_mapdimvalue), resources.getInteger(R.integer.def_mapdimvalue)); map.setHideOnDrag(settings.getBoolean(getString(R.string.pref_maphideondrag), resources.getBoolean(R.bool.def_maphideondrag))); map.setStrictUnfollow(!settings.getBoolean(getString(R.string.pref_unfollowontap), resources.getBoolean(R.bool.def_unfollowontap))); map.setLookAhead( settings.getInt(getString(R.string.pref_lookahead), resources.getInteger(R.integer.def_lookahead))); map.setBestMapEnabled( settings.getBoolean(getString(R.string.pref_mapbest), resources.getBoolean(R.bool.def_mapbest))); map.setBestMapInterval(settings.getInt(getString(R.string.pref_mapbestinterval), resources.getInteger(R.integer.def_mapbestinterval)) * 1000); map.setCursorVector( Integer.parseInt(settings.getString(getString(R.string.pref_cursorvector), getString(R.string.def_cursorvector))), settings.getInt(getString(R.string.pref_cursorvectormlpr), resources.getInteger(R.integer.def_cursorvectormlpr))); map.setProximity(Integer.parseInt(settings.getString(getString(R.string.pref_navigation_proximity), getString(R.string.def_navigation_proximity)))); // prepare views customizeLayout(settings); findViewById(R.id.editroute).setVisibility(application.editingRoute != null ? View.VISIBLE : View.GONE); if (application.editingTrack != null) { startEditTrack(application.editingTrack); } updateGPSStatus(); updateNavigationStatus(); // prepare overlays updateOverlays(settings, false); if (settings.getBoolean(getString(R.string.ui_drawer_open), false)) { Panel panel = (Panel) findViewById(R.id.panel); panel.setOpen(true, false); } onSharedPreferenceChanged(settings, getString(R.string.pref_wakelock)); map.setKeepScreenOn(keepScreenOn); // TODO move into application if (lastKnownLocation != null) { if (lastKnownLocation.getProvider().equals(LocationManager.GPS_PROVIDER)) { updateMovingInfo(lastKnownLocation, true); updateNavigationInfo(); dimScreen(lastKnownLocation); } else if (lastKnownLocation.getProvider().equals(LocationManager.NETWORK_PROVIDER)) { dimScreen(lastKnownLocation); } } bindService(new Intent(this, LocationService.class), locationConnection, BIND_AUTO_CREATE); bindService(new Intent(this, NavigationService.class), navigationConnection, BIND_AUTO_CREATE); registerReceiver(broadcastReceiver, new IntentFilter(NavigationService.BROADCAST_NAVIGATION_STATUS)); registerReceiver(broadcastReceiver, new IntentFilter(NavigationService.BROADCAST_NAVIGATION_STATE)); registerReceiver(broadcastReceiver, new IntentFilter(LocationService.BROADCAST_LOCATING_STATUS)); registerReceiver(broadcastReceiver, new IntentFilter(LocationService.BROADCAST_TRACKING_STATUS)); registerReceiver(broadcastReceiver, new IntentFilter(Intent.ACTION_SCREEN_OFF)); registerReceiver(broadcastReceiver, new IntentFilter(Intent.ACTION_SCREEN_ON)); if (application.hasEnsureVisible()) { setFollowing(false); double[] loc = application.getEnsureVisible(); application.setMapCenter(loc[0], loc[1], true, false); application.clearEnsureVisible(); } else { application.updateLocationMaps(true, map.isBestMapEnabled()); } updateMapViewArea(); map.resume(); map.updateMapInfo(); map.update(); map.requestFocus(); }
From source file:org.restcomm.app.qoslib.Services.Intents.IntentHandler.java
@Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Bundle intentExtras = intent.getExtras(); if (owner == null) return;// w ww . j av a 2 s.c o m owner.getWebSocketManager().sendIntentToWebSocket(action, intentExtras); //capture the "battery changed" event if (action.equals(Intent.ACTION_BATTERY_CHANGED)) { int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0); int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100); DeviceInfoOld.battery = level * 100 / scale; int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1); boolean bCharging = plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB; owner.setBatteryCharging(bCharging); dataMonitorStats.setBattery(bCharging, DeviceInfoOld.battery); } else if (action.equals(Intent.ACTION_POWER_CONNECTED)) { owner.setBatteryCharging(true); dataMonitorStats.setBattery(true, null); } else if (action.equals(Intent.ACTION_POWER_DISCONNECTED)) { owner.setBatteryCharging(false); dataMonitorStats.setBattery(false, null); } else if (action.equals(Intent.ACTION_VIEW)) { //this is supposed to trigger the update event //owner.triggerUpdateEvent(false, false); } else if (action.equals(CommonIntentActionsOld.ACTION_START_UI)) { String packagename = intent.getStringExtra("packagename"); String mypackagename = context.getPackageName(); PreferenceManager.getDefaultSharedPreferences(context).edit() .putString(PreferenceKeys.Miscellaneous.YEILDED_SERVICE, packagename).commit(); // If the UI started on a different MMC app UI, then we stop this service until this UI is launched if (!packagename.equals(mypackagename)) // This will exit the service when safe, and won't restart it because it will be yeilded owner.restartSelf(); } else if (action.equals(UPDATE_ACTION)) { owner.getEventManager().triggerUpdateEvent(false, false); } else if (action.equals(COLDRESET_ACTION)) { //this is supposed to trigger the update event owner.getGpsManager().coldStart("triggered by user"); } else if (action.equals(EMAIL_CSV)) { //this is supposed to trigger the update event owner.requestCsvEmail(); } else if (action.equals(SPEED_TEST)) { //this is supposed to trigger a speed test int trigger = intent.getIntExtra(CommonIntentBundleKeysOld.EXTRA_SPEED_TRIGGER, 0); //owner.triggerSMSTest(trigger); owner.getEventManager().queueActiveTest(EventType.MAN_SPEEDTEST, trigger); } else if (action.equals(RUN_WEBSOCKET)) { //this is supposed to trigger a speed test boolean bStart = intent.getBooleanExtra(EXTRA_START_WEBSOCKET, true); owner.getWebSocketManager().runWebSocket(bStart); //owner.triggerSpeedTest(trigger); } else if (action.equals(ACTIVE_TEST)) { //this is supposed to trigger a speed test int evType = intent.getIntExtra(CommonIntentBundleKeysOld.EXTRA_TEST_TYPE, 0); EventType eventType = EventType.get(evType); int trigger = intent.getIntExtra(CommonIntentBundleKeysOld.EXTRA_SPEED_TRIGGER, 0); owner.getEventManager().queueActiveTest(eventType, trigger); } else if (action.equals(SMS_TEST)) { //this is supposed to trigger a speed test int trigger = intent.getIntExtra(CommonIntentBundleKeysOld.EXTRA_SPEED_TRIGGER, 0); //owner.triggerSMSTest(trigger); owner.getEventManager().queueActiveTest(EventType.SMS_TEST, trigger); } else if (action.contains(SMS_DELIVERED)) { //add delivery time to connection history int identifier = intent.getIntExtra("identifier", 0); //in case we need to search connection list to find which SMS long deliveryTime = 0; switch (getResultCode()) { case Activity.RESULT_OK: deliveryTime = System.currentTimeMillis(); break; case SmsManager.RESULT_ERROR_GENERIC_FAILURE: deliveryTime = -1; break; case SmsManager.RESULT_ERROR_NO_SERVICE: deliveryTime = -1; break; case SmsManager.RESULT_ERROR_NULL_PDU: deliveryTime = -1; break; case SmsManager.RESULT_ERROR_RADIO_OFF: deliveryTime = -1; break; } owner.getEventManager().handleSMSDeliverNotification(identifier, deliveryTime); } else if (action.equals(LATENCY_TEST)) { int trigger = intent.getIntExtra(CommonIntentBundleKeysOld.EXTRA_SPEED_TRIGGER, 0); owner.getEventManager().queueActiveTest(EventType.LATENCY_TEST, trigger); //owner.runLatencyTest(false); } else if (action.equals(ACTION_STOP_SPEEDTEST)) { owner.getEventManager().killSpeedTest(); } else if (action.equals(ACTION_STOP_VIDEOTEST)) { int testType = intent.getIntExtra(CommonIntentBundleKeysOld.EXTRA_TEST_TYPE, 0); owner.getEventManager().killActiveTest(testType); } else if (action.equals(ROAMING_ON)) { dataMonitorStats.setRoaming(true); } else if (action.equals(ROAMING_OFF)) { dataMonitorStats.setRoaming(false); } else if (action.equals("android.intent.action.ANY_DATA_STATE")) { String apn = intentExtras.getString("apn"); String state = intentExtras.getString("state"); String apnType = intentExtras.getString("apnType"); String extras = apnType + "" + state; if (state.equals("CONNECTED") && !apnType.equals("default")) extras = extras + "!"; if (apnType != null && apnType.equals("default") && apn != null) { SharedPreferences securePref = MainService.getSecurePreferences(context); securePref.edit().putString(PreferenceKeys.Miscellaneous.KEY_APN, apn).commit(); } } else if (action.equals("android.intent.action.DATA_CONNECTION_CONNECTED_TO_PROVISIONING_APN")) { String apn = intentExtras.getString("apn"); String apnType = intentExtras.getString("apnType"); String extras = apn + "," + apnType; } else if (action.equals("android.intent.action.ACTION_DATA_CONNECTION_FAILED")) { String phoneName = intentExtras.getString("phoneName"); String reason = intentExtras.getString("reason"); String extras = phoneName + "," + reason; } else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) { if (owner.getUsageLimits().getDormantMode() > 0) return; // wifi state change may trigger the event queue to be sent //MMCLogger.logToFile(MMCLogger.Level.DEBUG, "MMCIntentHandlerOld", "NETWORK_STATE_CHANGED_ACTION", ""); owner.wifiStateChange((NetworkInfo) intentExtras.getParcelable(WifiManager.EXTRA_NETWORK_INFO)); owner.trackAccessPoints(0); dataMonitorStats.setWifi(PhoneState.isNetworkWifi(owner)); } else if (action.equals(WIMAX_STATE_CHANGE)) { owner.trackAccessPoints(0); } else if (action.equals(BluetoothDevice.ACTION_ACL_CONNECTED)) { // BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // BluetoothClass bclass = device.getBluetoothClass(); // int major = bclass.getMajorDeviceClass(); // if (major == 1024) // owner.setBTHeadsetState(1); // owner.trackAccessPoints(); } else if (action.equals(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED)) { owner.trackAccessPoints(0); } else if (action.equals(BluetoothDevice.ACTION_ACL_DISCONNECTED)) { // BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // BluetoothClass bclass = device.getBluetoothClass(); // int major = bclass.getMajorDeviceClass(); // if (major == 1024) // owner.setBTHeadsetState(0); // owner.trackAccessPoints(); } else if (action.equals(Intent.ACTION_HEADSET_PLUG)) { try { int state = intent.getIntExtra("state", -1); owner.setHeadsetState(state); } catch (Exception e) { LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "onReceive", "error receiving Intent.ACTION_HEADSET_PLUG: " + e); } } else if (action.equals(Intent.ACTION_HEADSET_PLUG)) { int state = intent.getIntExtra("state", -1); owner.setHeadsetState(state); } else if (action.equals(CommonIntentActionsOld.ACTION_START_VOICETEST)) { //this is supposed to trigger a speed test int trigger = intent.getIntExtra(CommonIntentBundleKeysOld.EXTRA_VQ_TRIGGER, 0); owner.getVQManager().runTest(trigger); } else if (action.equals(CommonIntentActionsOld.ACTION_TEST_VQ_DEVICE)) { owner.getVQManager().runTest(10); } else if (action.equals(CommonIntentActionsOld.ACTION_STOP_VOICETEST)) { owner.getVQManager().killTest(); } else if (action.equals(RESTART_MMC_SERVICE)) { owner.restartNextIdle(); } else if (action.equals(STOP_TRACKING_ACTION)) { owner.getEventManager().stopTracking(); } else if (action.equals(Intent.ACTION_SCREEN_OFF)) { try { dataMonitorStats.setScreen(false); SignalEx mmcSignal = new SignalEx(); owner.getPhoneStateListener().processNewMMCSignal(mmcSignal); if (owner.getTravelDetector() != null) { owner.getPhoneState().screenChanged(false); owner.getEventManager().screenChanged(false); } } catch (Exception e) { LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "onReceive", "received action SCREEN_OFF, calling MainService.processNewMMCSignal()", e); } } else if (action.equals(Intent.ACTION_SCREEN_ON)) { dataMonitorStats.setScreen(true); if (owner.getTravelDetector() != null) { owner.getPhoneState().screenChanged(true); owner.getEventManager().screenChanged(true); } } else if (action.equals(ACTION_ALARM_MINUTE)) { // CPU wakes very briefly only in order to spur cellid updates owner.getTravelDetector().triggerTravelCheck(); QosAPI.checkHostApp(context); } else if (action.equals(ACTION_TRACKING_5MINUTE)) { owner.getTrackingManager().runTracking(); } else if (action.equals(ACTION_TRACKING_1MINUTE)) { LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "onReceive", "ACTION_TRACKING_1MINUTE"); owner.getTrackingManager().runTrackingTests(); } else if (action.equals(ACTION_ALARM_3HOUR)) { dataMonitorStats.prepareAllStatistics(); owner.getEventManager().triggerUpdateEvent(true, false); // Calendar cal = Calendar.getInstance(); // int hour = cal.get (Calendar.HOUR_OF_DAY); // //If 12pm to 3 am // if(((hour >= 0 && hour <= 3) || hour == 24) && owner.isNetworkWifi()) { // //See if transit info needs to be downloaded // // //Don't allow the app to shut down until the work is done, keep the CPU running // MMCLogger.logToFile(MMCLogger.Level.DEBUG, TAG, "onReceive", "ACTION_ALARM_3HOUR, wakelock turned on and checking transit " // + "info uptodate at 24-hour: " + hour); // wakeLock.acquire(); // // downloadAreasIfOutOfDate(); // } } // else if(action.equals(ACTION_TRANSIT_DL_DONE)) { // //Allow CPU to move on // if(wakeLock != null) { // wakeLock.release(); // MMCLogger.logToFile(MMCLogger.Level.DEBUG, TAG, "onReceive", "received action ACTION_TRANSIT_DONE, wakelock turned off"); // } // } // else if(action.equals(ACTION_TRANSIT_DL_START)) { // //Don't allow the app to shut down until the work is done, keep the CPU running // MMCLogger.logToFile(MMCLogger.Level.DEBUG, TAG, "onReceive", "ACTION_TRANSIT_DL_START, wakelock turned on and downloading transit if was requested"); // wakeLock.acquire(); // // downloadAreasIfOutOfDate(); // } else if (action.equals(ACTION_ALARM_SCANAPPS)) { int intervalDM = PreferenceManager.getDefaultSharedPreferences(owner) .getInt(PreferenceKeys.Miscellaneous.MANAGE_DATAMONITOR, 0); // run datamonitor if enabled if (intervalDM > 0) { dataMonitorStats.scanApps(); dataMonitorStats.getRunningAppsString(false); // for debug } // Also using this timer for GCM heartbeats (its a 5 minute heartbeat to tell Google Cloud Messaging to check the socket more often for more reliable push messages) // 2 independent timers might wake up device twice as often, doubling the battery impact, so I'm forcing it to use one for both cases // boolean useHeartbeat = PreferenceManager.getDefaultSharedPreferences(owner).getBoolean("KEY_GCM_HEARTBEAT", false); // if (useHeartbeat) { // GcmKeepAlive gcm = new GcmKeepAlive(owner); // gcm.broadcastIntents(); // } } else if (action.equals(ACTION_ALARM_15MINUTE)) { int intervalDM = PreferenceManager.getDefaultSharedPreferences(owner) .getInt(PreferenceKeys.Miscellaneous.MANAGE_DATAMONITOR, 0); // run datamonitor if enabled if (intervalDM > 0) { boolean firstBucketDone = PreferenceManager.getDefaultSharedPreferences(owner) .getBoolean(PreferenceKeys.Miscellaneous.FIRST_BUCKET, false); if (!firstBucketDone) { //if false, first bucket needs to be done dataMonitorStats.firstBucket(); dataMonitorStats.monitor(); PreferenceManager.getDefaultSharedPreferences(owner).edit() .putBoolean(PreferenceKeys.Miscellaneous.FIRST_BUCKET, true).commit(); LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, "MMCIntentHandlerOld", "onReceive", "First bucket at: " + System.currentTimeMillis() / 1000); } else { dataMonitorStats.monitor(); //MMCLogger.logToFile(MMCLogger.Level.DEBUG, "MMCIntentHandlerOld", "onReceive", "15 min bucket at: " + System.currentTimeMillis()/1000); } } // regardless, still make sure GPS is idle unless needed owner.getGpsManager().safeguardGps(); } else if (action.equals(GPS_STATE_ON)) { dataMonitorStats.setGps(true); } else if (action.equals(GPS_STATE_OFF)) { dataMonitorStats.setGps(false); } else if (action.equals(PHONE_CALL_CONNECT)) { dataMonitorStats.setPhone(true); } else if (action.equals(PHONE_CALL_DISCONNECT)) { dataMonitorStats.setPhone(false); } else if (action.equals(HANDOFF)) { dataMonitorStats.handoff(); } else if (action.equals(MANUAL_TRANSIT_START)) { long lat = intent.getIntExtra("latitude", 0); long lon = intent.getIntExtra("longitude", 0); Location location = new Location(""); location.setLatitude(lat / 1000000.0); location.setLongitude(lon / 1000000.0); location.setAccuracy(-3); // PreferenceManager.getDefaultSharedPreferences(owner).edit().putString( // PreferenceKeys.Miscellaneous.SURVEY_COMMAND,).commit(); PreferenceManager.getDefaultSharedPreferences(owner).edit() .putString("transitEvent", String.valueOf(lat) + "," + String.valueOf(lon)).commit(); reportManager.manualTransitEvent = owner.getEventManager().triggerSingletonEvent(EventType.MAN_TRANSIT); reportManager.manualTransitEvent.setLocation(location, 0); owner.getTravelDetector().setTravelling(false); } else if (action.equals(MANUAL_TRANSIT_END)) { if (reportManager.manualTransitEvent == null) return; String accelData = intent.getStringExtra("accelerometer"); int stationFrom = intent.getIntExtra("stationFrom", 0); int stationTo = intent.getIntExtra("stationTo", 0); int duration = intent.getIntExtra("duration", 0); int corrected = intent.getIntExtra("corrected", 0); if (corrected != 0) { Location location = reportManager.manualTransitEvent.getLocation(); location.setAccuracy(-4); } reportManager.manualTransitEvent.setAppData(accelData); //TODO want this to really be in appdata? reportManager.manualTransitEvent.setLookupid1(stationFrom); reportManager.manualTransitEvent.setLookupid2(stationTo); reportManager.manualTransitEvent.setDuration(duration); owner.getEventManager().unstageAndUploadEvent(reportManager.manualTransitEvent, null); reportManager.manualTransitEvent = null; } else if (action.equals(MANUAL_TRANSIT_CANCEL)) { if (reportManager.manualTransitEvent != null) { owner.getEventManager().unstageEvent(reportManager.manualTransitEvent); ReportManager reportManager = ReportManager.getInstance(owner); reportManager.getDBProvider().delete(TablesEnum.LOCATIONS.getContentUri(), "timestamp > ? And accuracy = 3", new String[] { String.valueOf(reportManager.manualTransitEvent.getEventTimestamp()) }); reportManager.manualTransitEvent = null; } } else if (action.equals(MANUAL_PLOTTING_START)) { int floor = intent.getIntExtra("floor", 0); // int type = intent.getIntExtra("type", -1); //1(indoor) or 2(outdoor) int topFloor = intent.getIntExtra("top", -1); int lat = intent.getIntExtra("latitude", -1); int lng = intent.getIntExtra("longitude", -1); long osm_id = intent.getLongExtra("osm_id", 0); String poly = intent.getStringExtra("poly"); reportManager.manualPlottingEvent = owner.getEventManager() .triggerSingletonEvent(EventType.MAN_PLOTTING); reportManager.manualPlottingEvent.setEventIndex(floor); reportManager.manualPlottingEvent.setDuration(topFloor); reportManager.manualPlottingEvent.setBuildingID(osm_id); reportManager.manualPlottingEvent.setAppData(poly); Location location = new Location(""); location.setLatitude(lat / 1000000.0); location.setLongitude(lng / 1000000.0); location.setAccuracy(-1); reportManager.updateEventField(reportManager.manualPlottingEvent.getLocalID(), "latitude", Double.toString(location.getLatitude())); reportManager.updateEventField(reportManager.manualPlottingEvent.getLocalID(), "longitude", Double.toString(location.getLongitude())); reportManager.manualPlottingEvent.setLocation(location, 0); presetEventId(reportManager.manualPlottingEvent); // reserve an EventID for this manual sampling event, to be used for Share links owner.getTravelDetector().setTravelling(false); } else if (action.equals(MANUAL_PLOTTING_END)) { LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "onReceive", "MANUAL_PLOTTING_END"); // owner.getEventManager().unstageEvent(manulaPlottingEvent); //does not upload if (reportManager.manualPlottingEvent != null) owner.getEventManager().unstageAndUploadEvent(reportManager.manualPlottingEvent, null); //After the event was submitted, reset it so we don't restore an old event in ManualMapping reportManager.manualPlottingEvent = null; } else if (action.equals(MANUAL_PLOTTING_CANCEL)) { if (reportManager.manualPlottingEvent != null) { reportManager.getDBProvider().delete(TablesEnum.LOCATIONS.getContentUri(), "timestamp > ? And accuracy < 0", new String[] { String.valueOf(reportManager.manualPlottingEvent.getEventTimestamp()) }); reportManager.manualPlottingEvent = null; } } // else if(intent.getAction().equals(MMS_RECEIVED)) { // LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "onReceived MMS_RECEIVED", intentExtras.toString()); // } // else if(intent.getAction().equals(MMS_SENT)) { // LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "onReceived MMS_SENT", intentExtras.toString()); // } // else if(intent.getAction().equals(SMS_REJECTED)) { // LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "onReceived SMS_REJECTED", intentExtras.toString()); // } else if (intent.getAction().equals(SMS_RECEIVED)) { SmsMessage[] msgs = null; // String msg_from; if (intentExtras == null) return; Object[] pdus = (Object[]) intentExtras.get("pdus"); msgs = new SmsMessage[pdus.length]; String[] msgBody = new String[msgs.length]; for (int i = 0; i < msgs.length; i++) { msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); // msg_from = msgs[i].getOriginatingAddress(); String msg = msgs[i].getMessageBody().trim(); if (msg.length() > 10) { msg = msg.substring(1, msg.length() - 1); msg = "{" + msg + "}"; } msgBody[i] = msg; } handleCommands(msgBody, true, 0); } else if (action.equals(VIEWING_SIGNAL)) { owner.setEnggQueryTime(); } else if (intent.getAction().equals(SURVEY)) { if (intentExtras == null) return; int surveyid = intentExtras.getInt(SURVEY_EXTRA); postSurvey(surveyid); } else if (intent.getAction().equals(GCM_MESSAGE)) { if (intentExtras == null) return; try { String msg = intentExtras.getString(GCM_MESSAGE_EXTRA); long starttime = intentExtras.getLong("GCM_STARTTIME_EXTRA"); EventResponse eventResponse = gson.fromJson(msg, EventResponse.class); eventResponse.init(); eventResponse.setStartTime(starttime); eventResponse.handleEventResponse(owner, true); } catch (Exception e) { LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "onReceived GCM_MESSAGE", "exception", e); } } else if (intent.getAction().equals(COMMAND)) { if (intentExtras == null) return; String commands = intentExtras.getString(COMMAND_EXTRA); if (commands == null) return; long starttime = intent.getLongExtra("STARTTIME_EXTRA", 0); String[] msgs = null; try { JSONArray cmds = new JSONArray(commands); msgs = new String[cmds.length()]; for (int j = 0; j < cmds.length(); j++) msgs[j] = cmds.getJSONObject(j).toString(); } catch (JSONException e) { // TODO Auto-generated catch block //e.printStackTrace(); } //commands = commands.replace("[", ""); //commands = commands.replace("]", ""); //String msgs[] = commands.split("/"); handleCommands(msgs, false, starttime); } else if (intent.getAction().equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) { int val = 0; val = intent.getIntExtra("android.telecom.extra.CALL_DISCONNECT_CAUSE", -1); String msg = intent.getStringExtra("android.telecom.extra.CALL_DISCONNECT_CAUSE"); String msg2 = intent.getStringExtra("android.telecom.extra.CALL_DISCONNECT_MESSAGE"); //MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "String CALL_DISCONNECT_CAUSE", msg); //MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "Int CALL_DISCONNECT_CAUSE", ""+val); } else if (intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL")) { String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER); //if (phoneNumber != null) // MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "NEW_OUTGOING_CALL", phoneNumber); } else if (intent.getAction().equals("android.intent.action.PRECISE_CALL_STATE")) { int val = 0; //val = intent.getIntExtra("android.telecom.extra.CALL_DISCONNECT_CAUSE", -1); int state_ringing = intent.getIntExtra("ringing_state", -1); int state_foreground = intent.getIntExtra("foreground_state", -1); int state_background = intent.getIntExtra("background_state", -1); int disconnect_cause = intent.getIntExtra("disconnect_cause", -1); int precise_disconnect_cause = intent.getIntExtra("precise_disconnect_cause", -1); PreciseCallCodes precisecall = new PreciseCallCodes(state_ringing, state_foreground, state_background, disconnect_cause, precise_disconnect_cause); LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "PRECISE_CALL_STATE", precisecall.toString()); owner.getPhoneStateListener().onPreciseCallState(precisecall); } else if (intent.getAction().equals("android.intent.action.PRECISE_DATA_CONNECTION_STATE_CHANGED")) { int val = 0; //val = intent.getIntExtra("android.telecom.extra.CALL_DISCONNECT_CAUSE", -1); int state = intent.getIntExtra("state", -1); int networkType = intent.getIntExtra("networkType", -1); String reason = intent.getStringExtra("reason"); String failCause = intent.getStringExtra("failCause"); String apnType = intent.getStringExtra("apnType"); String apn = intent.getStringExtra("apn"); Object linkProperties = intent.getParcelableExtra("linkProperties"); if (!apnType.equals("default")) return; // if (failCause != null && failCause.length() > 0) // { // String msg = String.format("state:%d,netType:%d,apnType:%s,reason:%s\r\nfailCause:%s", state,networkType,apnType,reason,failCause); // MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "PRECISE_DATA_CONNECTION_STATE_CHANGED", msg); // if (linkProperties != null) // { // msg = String.format("PRECISE_DATA_CONNECTION_STATE_CHANGED linkProperties:%s", linkProperties.toString()); // MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "PRECISE_DATA_CONNECTION_STATE_CHANGED", msg); // } // } // else if (reason != null && reason.length() > 0) // { // String msg = String.format("state:%d,netType:%d,apnType:%s,reason:%s\r\nfailCause:%s", state,networkType,apnType,reason,failCause); // MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "PRECISE_DATA_CONNECTION_STATE_CHANGED", msg); // if (linkProperties != null) // { // msg = String.format("PRECISE_DATA_CONNECTION_STATE_CHANGED linkProperties:%s", linkProperties.toString()); // MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "PRECISE_DATA_CONNECTION_STATE_CHANGED", msg); // } // } } else if (intent.getAction().equals("org.restcomm.android.CONNECT_FAILED") || intent.getAction().equals("org.restcomm.android.CALL_STATE") || intent.getAction().equals("org.restcomm.android.DISCONNECT_ERROR")) { owner.getPhoneStateListener().getRestCommManager().handleIntent(owner, intent); } else if (intent.getAction().equals(ACTION_RADIOLOG_DISCONNECT)) { String time = intent.getStringExtra(EXTRA_RADIOLOG_TIME); String cause = intent.getStringExtra(EXTRA_RADIOLOG_DISC_CAUSE); owner.getPhoneStateListener().onDisconnect(time, cause); } else if (intent.getAction().equals(ACTION_RADIOLOG_CONNECT)) { String time = intent.getStringExtra(EXTRA_RADIOLOG_TIME); String state = intent.getStringExtra(EXTRA_RADIOLOG_CONN_STATE); owner.getPhoneStateListener().onConnect(time, state); } else if (intent.getAction().equals(ACTION_RADIOLOG_NEIGHBORS)) { String time = intent.getStringExtra(EXTRA_RADIOLOG_TIME); String neighbors = intent.getStringExtra(EXTRA_RADIOLOG_NEIGHBORS); //owner.onConnect(time, state); } else if (intent.getAction().equals(ACTION_RADIOLOG_SERVICEMODE)) { String time = intent.getStringExtra(EXTRA_RADIOLOG_TIME); String jsonstr = intent.getStringExtra(EXTRA_RADIOLOG_SVC_JSON); JSONObject json = null; try { json = new JSONObject(jsonstr); } catch (Exception e) { } String values = intent.getStringExtra(EXTRA_RADIOLOG_SVC_TEXT); String name = intent.getStringExtra(EXTRA_RADIOLOG_SVC_NAME); owner.getPhoneStateListener().onServiceMode(time, json, values, name); } else if (intent.getAction().equals(ACTION_RADIOLOG_SERVICEMENU)) { String time = intent.getStringExtra(EXTRA_RADIOLOG_TIME); String values = intent.getStringExtra(EXTRA_RADIOLOG_SVC_TEXT); String name = intent.getStringExtra(EXTRA_RADIOLOG_SVC_NAME); owner.getPhoneStateListener().onServiceMenu(time, values, name); } else if (intent.getAction().equals(ACTION_MMCSYS_VERSION)) { Integer version = intent.getIntExtra(EXTRA_MMCSYS_VERSION, 0); owner.onSvcModeVersion(version); } else if (intent.getAction().equals(ACTION_RADIOLOG_ERROR)) { String error = intent.getStringExtra(EXTRA_RADIOLOG_ERROR); String details = intent.getStringExtra(EXTRA_RADIOLOG_ERROR_DETAIL); LoggerUtil.logToFile(LoggerUtil.Level.ERROR, "RilReader", error, details); //owner.onConnect(time, state); } }
From source file:org.kontalk.service.msgcenter.MessageCenterService.java
private void registerInactivity() { IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF); filter.addAction(Intent.ACTION_SCREEN_OFF); registerReceiver(mInactivityReceiver, filter); }
From source file:org.tigase.messenger.phone.pro.service.XMPPService.java
@Override public void onCreate() { super.onCreate(); Log.i("XMPPService", "Service started"); getApplication().registerActivityLifecycleCallbacks(mActivityCallbacks); this.ownPresenceStanzaFactory = new OwnPresenceFactoryImpl(); this.dbHelper = DatabaseHelper.getInstance(this); this.connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); this.dataRemover = new DataRemover(this.dbHelper); SSLSessionCache sslSessionCache = new SSLSessionCache(this); this.sslSocketFactory = SSLCertificateSocketFactory.getDefault(0, sslSessionCache); this.rosterProvider = new RosterProviderExt(this, dbHelper, new RosterProviderExt.Listener() { @Override//from w w w.ja v a2 s .c o m public void onChange(Long rosterItemId) { Uri uri = rosterItemId != null ? ContentUris.withAppendedId(RosterProvider.ROSTER_URI, rosterItemId) : RosterProvider.ROSTER_URI; Log.i(TAG, "Content change: " + uri); getApplicationContext().getContentResolver().notifyChange(uri, null); } }, "roster_version"); rosterProvider.resetStatus(); this.mobileModeFeature = new MobileModeFeature(this); this.presenceHandler = new PresenceHandler(this); this.messageHandler = new MessageHandler(this); this.chatProvider = new org.tigase.messenger.jaxmpp.android.chat.ChatProvider(this, dbHelper, new org.tigase.messenger.jaxmpp.android.chat.ChatProvider.Listener() { @Override public void onChange(Long chatId) { Uri uri = chatId != null ? ContentUris.withAppendedId(ChatProvider.OPEN_CHATS_URI, chatId) : ChatProvider.OPEN_CHATS_URI; getApplicationContext().getContentResolver().notifyChange(uri, null); } }); chatProvider.resetRoomState(CPresence.OFFLINE); this.mucHandler = new MucHandler(); this.capsCache = new CapabilitiesDBCache(dbHelper); IntentFilter screenStateReceiverFilter = new IntentFilter(Intent.ACTION_SCREEN_ON); screenStateReceiverFilter.addAction(Intent.ACTION_SCREEN_OFF); registerReceiver(screenStateReceiver, screenStateReceiverFilter); registerReceiver(presenceChangedReceiver, new IntentFilter(CLIENT_PRESENCE_CHANGED_ACTION)); registerReceiver(connReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE")); multiJaxmpp.addHandler( StreamManagementModule.StreamManagementFailedHandler.StreamManagementFailedEvent.class, new StreamManagementModule.StreamManagementFailedHandler() { @Override public void onStreamManagementFailed(final SessionObject sessionObject, XMPPException.ErrorCondition condition) { if (condition != null && condition.getElementName().equals("item-not-found")) { XMPPService.this.rosterProvider.resetStatus(sessionObject); } } }); multiJaxmpp.addHandler(DiscoveryModule.ServerFeaturesReceivedHandler.ServerFeaturesReceivedEvent.class, streamHandler); multiJaxmpp.addHandler(JaxmppCore.LoggedInHandler.LoggedInEvent.class, jaxmppConnectedHandler); multiJaxmpp.addHandler(JaxmppCore.LoggedOutHandler.LoggedOutEvent.class, jaxmppDisconnectedHandler); // multiJaxmpp.addHandler(SocketConnector.ErrorHandler.ErrorEvent.class, // ); // // this.connectorListener = new Connector.ErrorHandler() { // // @Override // public void onError(SessionObject sessionObject, StreamError // condition, Throwable caught) throws JaxmppException { // AbstractSocketXmppSessionLogic.this.processConnectorErrors(condition, // caught); // } // }; multiJaxmpp.addHandler(PresenceModule.ContactAvailableHandler.ContactAvailableEvent.class, presenceHandler); multiJaxmpp.addHandler(PresenceModule.ContactUnavailableHandler.ContactUnavailableEvent.class, presenceHandler); multiJaxmpp.addHandler(PresenceModule.ContactChangedPresenceHandler.ContactChangedPresenceEvent.class, presenceHandler); multiJaxmpp.addHandler(PresenceModule.SubscribeRequestHandler.SubscribeRequestEvent.class, subscribeHandler); multiJaxmpp.addHandler(MessageModule.MessageReceivedHandler.MessageReceivedEvent.class, messageHandler); multiJaxmpp.addHandler(MessageCarbonsModule.CarbonReceivedHandler.CarbonReceivedEvent.class, messageHandler); multiJaxmpp.addHandler(ChatStateExtension.ChatStateChangedHandler.ChatStateChangedEvent.class, messageHandler); multiJaxmpp.addHandler(AuthModule.AuthFailedHandler.AuthFailedEvent.class, new AuthModule.AuthFailedHandler() { @Override public void onAuthFailed(SessionObject sessionObject, SaslModule.SaslError error) throws JaxmppException { processAuthenticationError((Jaxmpp) multiJaxmpp.get(sessionObject)); } }); multiJaxmpp.addHandler(MucModule.MucMessageReceivedHandler.MucMessageReceivedEvent.class, mucHandler); multiJaxmpp.addHandler(MucModule.MessageErrorHandler.MessageErrorEvent.class, mucHandler); multiJaxmpp.addHandler(MucModule.YouJoinedHandler.YouJoinedEvent.class, mucHandler); multiJaxmpp.addHandler(MucModule.StateChangeHandler.StateChangeEvent.class, mucHandler); multiJaxmpp.addHandler(MucModule.PresenceErrorHandler.PresenceErrorEvent.class, mucHandler); IntentFilter filterAccountModifyReceiver = new IntentFilter(); filterAccountModifyReceiver.addAction(LoginActivity.ACCOUNT_MODIFIED_MSG); filterAccountModifyReceiver.addAction(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION); registerReceiver(accountModifyReceiver, filterAccountModifyReceiver); startKeepAlive(); updateJaxmppInstances(); // connectAllJaxmpp(); }
From source file:co.beem.project.beem.FbTextService.java
/** * {@inheritDoc}/*from w w w . j av a 2s.c o m*/ */ @Override public void onCreate() { super.onCreate(); Utils.setContext(getApplicationContext()); smackAndroid = SmackAndroid.init(FbTextService.this); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); savingMessageQueue = new LinkedBlockingQueue<co.beem.project.beem.service.BeemMessage>(); stateChangeQueue = new LinkedBlockingQueue<User>(); sendImageQueue = new LinkedBlockingDeque<ImageMessageInQueue>(); isRunning = true; sessionManager = new SessionManager(FbTextService.this); savingMessageOnBackgroundThread(new SavingNewMessageTask()); savingMessageOnBackgroundThread(new UpdateUserStateTask()); savingMessageOnBackgroundThread(new SendImageTask()); handler = new Handler(); registerReceiver(mReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); this.registerReceiver(mReceiver, new IntentFilter(BeemBroadcastReceiver.BEEM_CONNECTION_CLOSED)); this.registerReceiver(mReceiver, new IntentFilter(BeemBroadcastReceiver.BEEM_CONNECTION_CONNECTED)); this.registerReceiver(mReceiver, new IntentFilter(BeemBroadcastReceiver.BEEM_CONNECTION_CONNECTING)); this.registerReceiver(mReceiver, new IntentFilter(BeemBroadcastReceiver.BEEM_CONNECTION_DISCONNECT)); this.registerReceiver(mReceiver, new IntentFilter(BeemBroadcastReceiver.BEEM_CONNECTION_CONNECTING_In)); registerReceiver(mOnOffReceiver, new IntentFilter(FbTextApplication.SEND_IMAGE_MESSAGE)); registerReceiver(mOnOffReceiver, new IntentFilter(FbTextApplication.SEND_INVITATION)); registerReceiver(mOnOffReceiver, new IntentFilter(FbTextApplication.UPDATE_USER_STATE)); registerReceiver(mOnOffReceiver, new IntentFilter(FbTextApplication.PUSH_NOTIFICATION_FAVORITE_ONLINE)); registerReceiver(mOnOffReceiver, new IntentFilter(FbTextApplication.CHANGE_STATUS)); mSettings = PreferenceManager.getDefaultSharedPreferences(this); mSettings.registerOnSharedPreferenceChangeListener(mPreferenceListener); if (mSettings.getBoolean(FbTextApplication.USE_AUTO_AWAY_KEY, false)) { mOnOffReceiverIsRegistered = true; registerReceiver(mOnOffReceiver, new IntentFilter(Intent.ACTION_SCREEN_OFF)); registerReceiver(mOnOffReceiver, new IntentFilter(Intent.ACTION_SCREEN_ON)); // registerReceiver(sma, filter) } String tmpJid = mSettings.getString(FbTextApplication.ACCOUNT_USERNAME_KEY, "").trim(); mLogin = StringUtils.parseName(tmpJid); boolean useSystemAccount = mSettings.getBoolean(FbTextApplication.USE_SYSTEM_ACCOUNT_KEY, false); mPort = DEFAULT_XMPP_PORT; mService = StringUtils.parseServer(tmpJid); mHost = mService; initMemorizingTrustManager(); if (mSettings.getBoolean(FbTextApplication.ACCOUNT_SPECIFIC_SERVER_KEY, false)) { mHost = mSettings.getString(FbTextApplication.ACCOUNT_SPECIFIC_SERVER_HOST_KEY, "").trim(); if ("".equals(mHost)) mHost = mService; String tmpPort = mSettings.getString(FbTextApplication.ACCOUNT_SPECIFIC_SERVER_PORT_KEY, "5222"); if (!"".equals(tmpPort)) mPort = Integer.parseInt(tmpPort); } if (mSettings.getBoolean(FbTextApplication.FULL_JID_LOGIN_KEY, false) || "gmail.com".equals(mService) || "googlemail.com".equals(mService) || useSystemAccount) { mLogin = tmpJid; } configure(ProviderManager.getInstance()); mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); Roster.setDefaultSubscriptionMode(SubscriptionMode.manual); mBind = new XmppFacade(this); if (FbTextApplication.isDebug) Log.d(TAG, "Create FacebookTextService \t id: " + mLogin + " \t host: " + mHost + "\tmPort" + mPort + "\t service" + mService); }
From source file:net.ustyugov.jtalk.service.JTalkService.java
@Override public void onCreate() { configure();//from ww w .j a v a 2s.c o m js = this; prefs = PreferenceManager.getDefaultSharedPreferences(this); iconPicker = new IconPicker(this); // updateReceiver = new BroadcastReceiver() { // @Override // public void onReceive(Context arg0, Intent arg1) { // updateWidget(); // } // }; // registerReceiver(updateReceiver, new IntentFilter(Constants.UPDATE)); connectionReceiver = new ChangeConnectionReceiver(); registerReceiver(connectionReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); screenStateReceiver = new ScreenStateReceiver(); registerReceiver(new ScreenStateReceiver(), new IntentFilter(Intent.ACTION_SCREEN_ON)); registerReceiver(new ScreenStateReceiver(), new IntentFilter(Intent.ACTION_SCREEN_OFF)); Intent i = new Intent(this, RosterActivity.class); i.setAction(Intent.ACTION_MAIN); i.addCategory(Intent.CATEGORY_LAUNCHER); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i, 0); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this); mBuilder.setSmallIcon(R.drawable.stat_offline); mBuilder.setContentTitle(getString(R.string.app_name)); mBuilder.setContentIntent(contentIntent); startForeground(Notify.NOTIFICATION, mBuilder.build()); WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, "jTalk"); PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "jTalk"); started = true; Cursor cursor = getContentResolver().query(JTalkProvider.ACCOUNT_URI, null, AccountDbHelper.ENABLED + " = '" + 1 + "'", null, null); if (cursor != null && cursor.getCount() > 0) { connect(); cursor.close(); } }
From source file:com.ubiLive.GameCloud.Browser.WebBrowser.java
/** register boradcast*/ private void registerBoradcast() { IntentFilter intentfilter = new IntentFilter(); intentfilter.addAction(Constants.RECEIVER_BROADCAST); intentfilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); intentfilter.addAction(Intent.ACTION_SCREEN_OFF); intentfilter.addAction(Intent.ACTION_SCREEN_ON); boradcastListener = new BroadcastReceiver() { @Override/*from w w w. j a v a2s. c o m*/ public void onReceive(Context context, Intent intent) { DebugLog.d(TAG, "WebViewActivity onReceive"); DebugLog.e(TAG, "BroadcastReceiver action = " + intent.getAction()); if (intent.getAction().equalsIgnoreCase(Constants.RECEIVER_BROADCAST)) { Bundle bundle = intent.getExtras(); int msgtype = bundle.getInt("msgtype"); String msgcontent = bundle.getString("msgcontent"); DebugLog.d(TAG, "handleMessage...... msgtype=" + msgtype + ", msgcontent=" + msgcontent); switch (msgtype) { case NotifyManagement.UP_PROBE_BAD_NETWORK: //irtsp 1.12 , WebBrowser is not need to handler the UP_PROBE_BAD_NETWORK event message. /*DebugLog.d(TAG, "UP_PROBE_BAD_NETWORK"); mPoorProbingresultFlag = true; mPlayer.bitrate_stopProbe(); notifyProbingCompleted(true);*/ break; case NotifyManagement.UP_PROBE_EXIT:// callback disconnectCB = 6 when bandwidth probe // success. Up_ui_gc.h DebugLog.d(TAG, "GameActivity.m_player.bitrate_stopProbe()"); //notifyProbingCompleted(true); /*if(bExitWaitProbeDone){ new Timer().schedule(new LogoutTimer(), 100); }*/ break; case NotifyManagement.UP_PROBE_EXIT_FAIL:// callback disconnectCB = 10 when bandwidth probe // fail. Up_ui_gc.h DebugLog.d(TAG, "WebViewActivity.onStart() probe fail, GameActivity.m_player.bitrate_stopProbe()"); //mPlayer.bitrate_stopProbe(); notifyProbingCompleted(false); /*if(bExitWaitProbeDone){ new Timer().schedule(new LogoutTimer(), 100); }*/ break; case NotifyManagement.UP_GAME_NOTIFY_DISPLAYTEXT: DebugLog.d(TAG, "notify UP_GAME_NOTIFY_DISPLAYTEXT"); gBNotifyDisplayExit = true; gNotifyDisplayText = msgcontent; break; case NotifyManagement.LOCAL_BROADCAST_CALL_UPDATE_STATE_200: callJsUpdateStatus(Constants.RESPONSE_200); break; case NotifyManagement.LOCAL_NOTIFY_WEBJS_GET_DUI: String gid = bundle.getString("gid"); String useragent = bundle.getString("useragent"); DebugLog.d(TAG, "notify webview js get DUI gid=" + gid + ",useragent=" + useragent); setToJsPlayMetadata(gid, useragent); break; case NotifyManagement.LOCAL_GAMEACTIVITY_RESULT: DebugLog.d(TAG, "Constants.LOCAL_GAMEACTIVITY_RESULT"); ((LoadWebJsActivity) mWebviewActivity).handleGameActivityResult(); break; case NotifyManagement.CAST_SESSION_STATUS_WEB: DebugLog.d(TAG, "build session have done"); String deviceId; String deviceName; String status; deviceId = bundle.getString("deviceId"); deviceName = bundle.getString("deviceName"); status = bundle.getString("status"); retPlayOnCast(deviceId, deviceName, status); synchronized (mLock) { mLock.notify(); DebugLog.d(TAG, "notify the thread"); } break; } } else if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) { processNetworkType(intent, context); } if (intent.getAction().compareTo(Intent.ACTION_SCREEN_OFF) == 0) { DebugLog.d(TAG, "POWER ACTION_SCREEN_OFF"); final LoadWebJsActivity loadWebJsActivity = (LoadWebJsActivity) mContext; loadWebJsActivity.gBEntryPowerKeyMode = true; loadWebJsActivity.gCurEntryBackgroundTime = System.currentTimeMillis(); } else if (intent.getAction().compareTo(Intent.ACTION_SCREEN_ON) == 0) { DebugLog.d(TAG, "POWER ACTION_SCREEN_ON"); final LoadWebJsActivity loadWebJsActivity = (LoadWebJsActivity) mContext; loadWebJsActivity.gBEntryPowerKeyMode = false; // loadWebJsActivity.gCurEntryBackgroundTime = 0; } } }; this.mContext.registerReceiver(boradcastListener, intentfilter); }
From source file:com.android.tv.MainActivity.java
@Override protected void onStart() { if (DEBUG)//from w ww. j a v a2 s.c om Log.d(TAG, "onStart()"); super.onStart(); mScreenOffIntentReceived = false; mActivityStarted = true; mTracker.sendMainStart(); mMainDurationTimer.start(); applyParentalControlSettings(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(TvInputManager.ACTION_PARENTAL_CONTROLS_ENABLED_CHANGED); intentFilter.addAction(Intent.ACTION_SCREEN_OFF); intentFilter.addAction(Intent.ACTION_SCREEN_ON); registerReceiver(mBroadcastReceiver, intentFilter); Intent notificationIntent = new Intent(this, NotificationService.class); notificationIntent.setAction(NotificationService.ACTION_SHOW_RECOMMENDATION); startService(notificationIntent); }
From source file:org.sipdroid.sipua.ui.Receiver.java
@Override public void onReceive(Context context, Intent intent) { String intentAction = intent.getAction(); if (!Sipdroid.on(context)) return;/*from w w w. ja va 2 s .c o m*/ if (!Sipdroid.release) Log.i("SipUA:", intentAction); if (mContext == null) mContext = context; if (intentAction.equals(Intent.ACTION_BOOT_COMPLETED)) { on_vpn(false); engine(context).register(); } else if (intentAction.equals(ConnectivityManager.CONNECTIVITY_ACTION) || intentAction.equals(ACTION_EXTERNAL_APPLICATIONS_AVAILABLE) || intentAction.equals(ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE) || intentAction.equals(Intent.ACTION_PACKAGE_REPLACED)) { engine(context).register(); } else if (intentAction.equals(ACTION_VPN_CONNECTIVITY) && intent.hasExtra("connection_state")) { String state = intent.getSerializableExtra("connection_state").toString(); if (state != null && on_vpn() != state.equals("CONNECTED")) { on_vpn(state.equals("CONNECTED")); for (SipProvider sip_provider : engine(context).sip_providers) if (sip_provider != null) sip_provider.haltConnections(); engine(context).register(); } } else if (intentAction.equals(ACTION_DATA_STATE_CHANGED)) { engine(context).registerMore(); } else if (intentAction.equals(ACTION_PHONE_STATE_CHANGED) && !intent.getBooleanExtra(context.getString(R.string.app_name), false)) { stopRingtone(); pstn_state = intent.getStringExtra("state"); pstn_time = SystemClock.elapsedRealtime(); if (pstn_state.equals("IDLE") && call_state != UserAgent.UA_STATE_IDLE) broadcastCallStateChanged(null, null); if (!pstn_state.equals("IDLE") && call_state == UserAgent.UA_STATE_INCALL) mHandler.sendEmptyMessageDelayed(MSG_HOLD, 5000); else if (!pstn_state.equals("IDLE") && (call_state == UserAgent.UA_STATE_INCOMING_CALL || call_state == UserAgent.UA_STATE_OUTGOING_CALL)) mHandler.sendEmptyMessageDelayed(MSG_HANGUP, 5000); else if (pstn_state.equals("IDLE")) { mHandler.removeMessages(MSG_HOLD); mHandler.removeMessages(MSG_HANGUP); if (call_state == UserAgent.UA_STATE_HOLD) mHandler.sendEmptyMessageDelayed(MSG_HOLD, 1000); } } else if (intentAction.equals(ACTION_DOCK_EVENT)) { docked = intent.getIntExtra(EXTRA_DOCK_STATE, -1) & 7; if (call_state == UserAgent.UA_STATE_INCALL) engine(mContext).speaker(speakermode()); } else if (intentAction.equals(ACTION_SCO_AUDIO_STATE_CHANGED)) { bluetooth = intent.getIntExtra(EXTRA_SCO_AUDIO_STATE, -1); progress(); RtpStreamSender.changed = true; } else if (intentAction.equals(Intent.ACTION_HEADSET_PLUG)) { headset = intent.getIntExtra("state", -1); if (call_state == UserAgent.UA_STATE_INCALL) engine(mContext).speaker(speakermode()); } else if (intentAction.equals(Intent.ACTION_SCREEN_ON)) { if (!PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean( org.sipdroid.sipua.ui.Settings.PREF_OWNWIFI, org.sipdroid.sipua.ui.Settings.DEFAULT_OWNWIFI)) alarm(0, OwnWifi.class); } else if (intentAction.equals(Intent.ACTION_USER_PRESENT)) { mHandler.sendEmptyMessageDelayed(MSG_ENABLE, 3000); } else if (intentAction.equals(Intent.ACTION_SCREEN_OFF)) { if (PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean( org.sipdroid.sipua.ui.Settings.PREF_OWNWIFI, org.sipdroid.sipua.ui.Settings.DEFAULT_OWNWIFI)) { WifiManager wm = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE); WifiInfo wi = wm.getConnectionInfo(); if (wm.getWifiState() != WifiManager.WIFI_STATE_ENABLED || wi == null || wi.getSupplicantState() != SupplicantState.COMPLETED || wi.getIpAddress() == 0) alarm(2 * 60, OwnWifi.class); else alarm(15 * 60, OwnWifi.class); } if (SipdroidEngine.pwl != null) for (PowerManager.WakeLock pwl : SipdroidEngine.pwl) if (pwl != null && pwl.isHeld()) { pwl.release(); pwl.acquire(); } } else if (intentAction.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) { if (PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean( org.sipdroid.sipua.ui.Settings.PREF_SELECTWIFI, org.sipdroid.sipua.ui.Settings.DEFAULT_SELECTWIFI)) mHandler.sendEmptyMessageDelayed(MSG_SCAN, 3000); } else if (intentAction.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) { if (SystemClock.uptimeMillis() > lastscan + 45000 && PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean( org.sipdroid.sipua.ui.Settings.PREF_SELECTWIFI, org.sipdroid.sipua.ui.Settings.DEFAULT_SELECTWIFI)) { WifiManager wm = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE); WifiInfo wi = wm.getConnectionInfo(); String activeSSID = null; if (wi != null) activeSSID = wi.getSSID(); if (activeSSID != null && (activeSSID.length() == 0 || activeSSID.equals("0x"))) activeSSID = null; List<ScanResult> mScanResults = wm.getScanResults(); List<WifiConfiguration> configurations = wm.getConfiguredNetworks(); if (configurations != null) { WifiConfiguration bestconfig = null, maxconfig = null, activeconfig = null; for (final WifiConfiguration config : configurations) { if (maxconfig == null || config.priority > maxconfig.priority) { maxconfig = config; } if (config.SSID != null && (config.SSID.equals("\"" + activeSSID + "\"") || config.SSID.equals(activeSSID))) activeconfig = config; } ScanResult bestscan = null, activescan = null; if (mScanResults != null) for (final ScanResult scan : mScanResults) { for (final WifiConfiguration config : configurations) { if (config.SSID != null && config.SSID.equals("\"" + scan.SSID + "\"")) { if (bestscan == null || scan.level > bestscan.level) { bestscan = scan; bestconfig = config; } if (config == activeconfig) activescan = scan; } } } if (activescan != null) System.out.println("debug wifi asu(active)" + asu(activescan)); if (bestconfig != null && (activeconfig == null || bestconfig.priority != activeconfig.priority) && asu(bestscan) > asu(activescan) * 1.5 && /* (activeSSID == null || activescan != null) && */ asu(bestscan) > 22) { if (!Sipdroid.release) Log.i("SipUA:", "changing to " + bestconfig.SSID); if (activeSSID == null || !activeSSID.equals(bestscan.SSID)) wm.disconnect(); bestconfig.priority = maxconfig.priority + 1; wm.updateNetwork(bestconfig); wm.enableNetwork(bestconfig.networkId, true); wm.saveConfiguration(); if (activeSSID == null || !activeSSID.equals(bestscan.SSID)) wm.reconnect(); lastscan = SystemClock.uptimeMillis(); } else if (activescan != null && asu(activescan) < 15) { wm.disconnect(); wm.disableNetwork(activeconfig.networkId); wm.saveConfiguration(); } } } } }
From source file:com.android.leanlauncher.LauncherTransitionable.java
@Override public void onAttachedToWindow() { super.onAttachedToWindow(); // Listen for broadcasts related to user-presence final IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_SCREEN_OFF); filter.addAction(Intent.ACTION_USER_PRESENT); // For handling managed profiles filter.addAction(LauncherAppsCompat.ACTION_MANAGED_PROFILE_ADDED); filter.addAction(LauncherAppsCompat.ACTION_MANAGED_PROFILE_REMOVED); registerReceiver(mReceiver, filter); FirstFrameAnimatorHelper.initializeDrawListener(getWindow().getDecorView()); setupTransparentSystemBarsForLmp();/*from ww w. j a va2s .c o m*/ mAttached = true; mVisible = true; }