List of usage examples for org.json JSONObject isNull
public boolean isNull(String key)
From source file:org.akvo.flow.api.parser.json.SurveyedLocaleParser.java
public SurveyedLocale parseSurveyedLocale(JSONObject jSurveyedLocale) throws JSONException { String id = jSurveyedLocale.getString(Attrs.ID); long lastModified = jSurveyedLocale.getLong(Attrs.LAST_MODIFIED); long surveyGroupId = jSurveyedLocale.getLong(Attrs.SURVEY_GROUP_ID); Double latitude = jSurveyedLocale.has(Attrs.LATITUDE) && !jSurveyedLocale.isNull(Attrs.LATITUDE) ? jSurveyedLocale.getDouble(Attrs.LATITUDE) : null;/*from w w w . ja v a2s.com*/ Double longitude = jSurveyedLocale.has(Attrs.LONGITUDE) && !jSurveyedLocale.isNull(Attrs.LONGITUDE) ? jSurveyedLocale.getDouble(Attrs.LONGITUDE) : null; String name = jSurveyedLocale.has(Attrs.NAME) && !jSurveyedLocale.isNull(Attrs.NAME) ? jSurveyedLocale.getString(Attrs.NAME) : null; JSONArray jSurveyInstances = jSurveyedLocale.getJSONArray(Attrs.SURVEY_INSTANCES); List<SurveyInstance> surveyInstances = new SurveyInstanceParser().parseList(jSurveyInstances); SurveyedLocale surveyedLocale = new SurveyedLocale(id, name, lastModified, surveyGroupId, latitude, longitude); surveyedLocale.setSurveyInstances(surveyInstances); return surveyedLocale; }
From source file:org.eclipse.orion.server.tests.servlets.git.GitTest.java
private JSONObject waitForTaskCompletionObject(String taskLocation, String userName, String userPassword) throws IOException, SAXException, JSONException { JSONObject status = null; long start = System.currentTimeMillis(); while (true) { WebRequest request = new GetMethodWebRequest(toAbsoluteURI(taskLocation)); setAuthentication(request, userName, userPassword); WebResponse response = webConversation.getResponse(request); String text = response.getText(); status = new JSONObject(text); if (status.isNull(TaskInfo.KEY_TYPE)) fail("Unexpected task format: " + text); String type = status.getString(TaskInfo.KEY_TYPE); boolean running = "loadstart".equals(type) || "progress".equals(type); if (!running) break; //timeout after reasonable time to avoid hanging tests if (System.currentTimeMillis() - start > 15000) assertTrue("The operation took too long", false); try {//from w w w . j a v a2s.c om Thread.sleep(200); } catch (InterruptedException e) { //ignore } } assertNotNull(status); return status; }
From source file:hongik.android.project.best.StoreActivity.java
public void drawPage() throws Exception { String query = "func=storereview" + "&license=" + license; DBConnector conn = new DBConnector(query); conn.start();/* w w w . j a v a2 s . c o m*/ conn.join(); JSONObject jsonResult = conn.getResult(); boolean result = jsonResult.getBoolean("result"); if (!result) return; final JSONObject store = jsonResult.getJSONArray("store").getJSONObject(0); JSONArray menu = null; if (!jsonResult.isNull("menu")) menu = jsonResult.getJSONArray("menu"); JSONArray review = null; if (!jsonResult.isNull("review")) review = jsonResult.getJSONArray("review"); //Draw Store Information Lat = Double.parseDouble(store.getString("LAT")); Lng = Double.parseDouble(store.getString("LNG")); sname = store.getString("SNAME"); ((TextViewPlus) findViewById(R.id.store_storename)).setText(sname); ((TextViewPlus) findViewById(R.id.store_address)).setText(store.getString("ADDR")); ImageLoader imgLoader = new ImageLoader(store.getString("IMG")); imgLoader.start(); try { imgLoader.join(); Bitmap storeImg = imgLoader.getBitmap(); ((ImageView) findViewById(R.id.store_image)).setImageBitmap(storeImg); } catch (InterruptedException e) { Toast.makeText(this, "Can not bring " + license + "store's image", Toast.LENGTH_SHORT).show(); Log.e("StoreInfo", "Can not bring " + license + "store's image"); } //Draw Menu Table if (menu != null) { TableRow motive = (TableRow) menuTable.getChildAt(1); for (int i = 0; i < menu.length(); i++) { JSONObject json = menu.getJSONObject(i); TableRow tbRow = new TableRow(this); TextViewPlus[] tbCols = new TextViewPlus[3]; final String[] elements = new String[2]; elements[0] = json.getString("ITEM#"); elements[1] = json.getString("PRICE"); imgLoader = new ImageLoader(json.getString("IMG")); imgLoader.start(); imgLoader.join(); ImageView img = new ImageView(this); Bitmap bitmap = imgLoader.getBitmap(); img.setImageBitmap(bitmap); img.setLayoutParams(motive.getChildAt(0).getLayoutParams()); img.setScaleType(ImageView.ScaleType.FIT_XY); img.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent storeIntent = new Intent(originActivity, MenuActivity.class); storeIntent.putExtra("LICENSE", license); storeIntent.putExtra("MENU", elements[0]); startActivity(storeIntent); } }); tbRow.addView(img); for (int j = 0; j < 2; j++) { tbCols[j] = new TextViewPlus(this); tbCols[j].setText(elements[j]); tbCols[j].setLayoutParams(motive.getChildAt(j + 1).getLayoutParams()); tbCols[j].setGravity(Gravity.CENTER); tbCols[j].setTypeface(Typeface.createFromAsset(tbCols[j].getContext().getAssets(), "InterparkGothicBold.ttf")); tbCols[j].setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent storeIntent = new Intent(originActivity, MenuActivity.class); storeIntent.putExtra("LICENSE", license); storeIntent.putExtra("MENU", elements[0]); startActivity(storeIntent); } }); Log.i("StoreMenu", "COL" + j + ":" + elements[j]); tbRow.addView(tbCols[j]); } menuTable.addView(tbRow); } } menuTable.removeViewAt(1); //Draw Review Table if (review != null) { TableRow motive = (TableRow) reviewTable.getChildAt(1); int rowCnt = 5; if (review.length() < 5) rowCnt = review.length(); for (int i = 0; i < rowCnt; i++) { JSONObject json = review.getJSONObject(i); final String[] elements = new String[4]; elements[0] = Double.parseDouble(json.getString("GRADE")) + ""; elements[1] = json.getString("NOTE"); elements[2] = json.getString("CID#"); elements[3] = json.getString("DAY"); TableRow tbRow = new TableRow(this); TextViewPlus[] tbCols = new TextViewPlus[4]; if (elements[1].length() > 14) elements[1] = elements[1].substring(0, 14) + "..."; for (int j = 0; j < 4; j++) { tbCols[j] = new TextViewPlus(this); tbCols[j].setText(elements[j]); tbCols[j].setLayoutParams(motive.getChildAt(j).getLayoutParams()); tbCols[j].setGravity(Gravity.CENTER); tbCols[j].setTypeface(Typeface.createFromAsset(tbCols[j].getContext().getAssets(), "InterparkGothicBold.ttf")); tbCols[j].setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent reviewIntent = new Intent(originActivity, ReviewDetailActivity.class); reviewIntent.putExtra("ACCESS", "STORE"); reviewIntent.putExtra("CID", elements[2]); reviewIntent.putExtra("LICENSE", license); Log.i("StoreReview", "StartActivity"); startActivity(reviewIntent); } }); Log.i("StoreMenu", "COL" + j + ":" + elements[j]); tbRow.addView(tbCols[j]); } reviewTable.addView(tbRow); } } reviewTable.removeViewAt(1); SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.store_map); mapFragment.getMapAsync(this); }
From source file:org.official.json.HTTP.java
/** * Convert a JSONObject into an HTTP header. A request header must contain * <pre>{/*w ww. j a va2s . co m*/ * Method: "POST" (for example), * "Request-URI": "/" (for example), * "HTTP-Version": "HTTP/1.1" (for example) * }</pre> * A response header must contain * <pre>{ * "HTTP-Version": "HTTP/1.1" (for example), * "Status-Code": "200" (for example), * "Reason-Phrase": "OK" (for example) * }</pre> * Any other members of the JSONObject will be output as HTTP fields. * The result will end with two CRLF pairs. * @param jo A JSONObject * @return An HTTP header string. * @throws JSONException if the object does not contain enough * information. */ public static String toString(JSONObject jo) throws JSONException { Iterator<String> keys = jo.keys(); String string; StringBuilder sb = new StringBuilder(); if (jo.has("Status-Code") && jo.has("Reason-Phrase")) { sb.append(jo.getString("HTTP-Version")); sb.append(' '); sb.append(jo.getString("Status-Code")); sb.append(' '); sb.append(jo.getString("Reason-Phrase")); } else if (jo.has("Method") && jo.has("Request-URI")) { sb.append(jo.getString("Method")); sb.append(' '); sb.append('"'); sb.append(jo.getString("Request-URI")); sb.append('"'); sb.append(' '); sb.append(jo.getString("HTTP-Version")); } else { throw new JSONException("Not enough material for an HTTP header."); } sb.append(CRLF); while (keys.hasNext()) { string = keys.next(); if (!"HTTP-Version".equals(string) && !"Status-Code".equals(string) && !"Reason-Phrase".equals(string) && !"Method".equals(string) && !"Request-URI".equals(string) && !jo.isNull(string)) { sb.append(string); sb.append(": "); sb.append(jo.getString(string)); sb.append(CRLF); } } sb.append(CRLF); return sb.toString(); }
From source file:net.dv8tion.jda.core.requests.WebSocketClient.java
@Override public void onTextMessage(WebSocket websocket, String message) { JSONObject content = new JSONObject(message); int opCode = content.getInt("op"); if (!content.isNull("s")) { api.setResponseTotal(content.getInt("s")); }/*w ww .j av a 2s .c om*/ switch (opCode) { case WebSocketCode.DISPATCH: handleEvent(content); break; case WebSocketCode.HEARTBEAT: LOG.debug("Got Keep-Alive request (OP 1). Sending response..."); sendKeepAlive(); break; case WebSocketCode.RECONNECT: LOG.debug("Got Reconnect request (OP 7). Closing connection now..."); close(); break; case WebSocketCode.INVALIDATE_SESSION: LOG.debug("Got Invalidate request (OP 9). Invalidating..."); final boolean isResume = content.getBoolean("d"); // When d: true we can wait a bit and then try to resume again //sending 4000 to not drop session int closeCode = isResume ? 4000 : 1000; if (isResume) LOG.debug("Session can be recovered... Closing and sending new RESUME request"); else if (!handleIdentifyRateLimit) // this can also mean we got rate limited in IDENTIFY (no need to invalidate then) invalidate(); close(closeCode); break; case WebSocketCode.HELLO: LOG.debug("Got HELLO packet (OP 10). Initializing keep-alive."); final JSONObject data = content.getJSONObject("d"); setupKeepAlive(data.getLong("heartbeat_interval")); if (!data.isNull("_trace")) updateTraces(data.getJSONArray("_trace"), "HELLO", WebSocketCode.HELLO); break; case WebSocketCode.HEARTBEAT_ACK: LOG.trace("Got Heartbeat Ack (OP 11)."); api.setPing(System.currentTimeMillis() - heartbeatStartTime); break; default: LOG.debug("Got unknown op-code: " + opCode + " with content: " + message); } }
From source file:net.dv8tion.jda.core.requests.WebSocketClient.java
protected void handleEvent(JSONObject raw) { String type = raw.getString("t"); long responseTotal = api.getResponseTotal(); if (type.equals("GUILD_MEMBER_ADD")) ((GuildMembersChunkHandler) getHandler("GUILD_MEMBERS_CHUNK")) .modifyExpectedGuildMember(raw.getJSONObject("d").getLong("guild_id"), 1); if (type.equals("GUILD_MEMBER_REMOVE")) ((GuildMembersChunkHandler) getHandler("GUILD_MEMBERS_CHUNK")) .modifyExpectedGuildMember(raw.getJSONObject("d").getLong("guild_id"), -1); //If initiating, only allows READY, RESUMED, GUILD_MEMBERS_CHUNK, GUILD_SYNC, and GUILD_CREATE through. // If we are currently chunking, we don't allow GUILD_CREATE through anymore. if (initiating && !(type.equals("READY") || type.equals("GUILD_MEMBERS_CHUNK") || type.equals("RESUMED") || type.equals("GUILD_SYNC") || (!chunkingAndSyncing && type.equals("GUILD_CREATE")))) { //If we are currently GuildStreaming, and we get a GUILD_DELETE informing us that a Guild is unavailable // convert it to a GUILD_CREATE for handling. JSONObject content = raw.getJSONObject("d"); if (!chunkingAndSyncing && type.equals("GUILD_DELETE") && content.has("unavailable") && content.getBoolean("unavailable")) { type = "GUILD_CREATE"; raw.put("t", "GUILD_CREATE").put("jda-field", "This event was originally a GUILD_DELETE but was converted to GUILD_CREATE for WS init Guild streaming"); } else {/*from ww w.ja va2s. co m*/ LOG.debug("Caching " + type + " event during init!"); cachedEvents.add(raw); return; } } // // // Needs special handling due to content of "d" being an array // if(type.equals("PRESENCE_REPLACE")) // { // JSONArray presences = raw.getJSONArray("d"); // LOG.trace(String.format("%s -> %s", type, presences.toString())); // PresenceUpdateHandler handler = new PresenceUpdateHandler(api, responseTotal); // for (int i = 0; i < presences.length(); i++) // { // JSONObject presence = presences.getJSONObject(i); // handler.handle(presence); // } // return; // } JSONObject content = raw.getJSONObject("d"); LOG.trace(String.format("%s -> %s", type, content.toString())); try { switch (type) { //INIT types case "READY": //LOG.debug(String.format("%s -> %s", type, content.toString())); already logged on trace level processingReady = true; handleIdentifyRateLimit = false; sessionId = content.getString("session_id"); if (!content.isNull("_trace")) updateTraces(content.getJSONArray("_trace"), "READY", WebSocketCode.DISPATCH); handlers.get("READY").handle(responseTotal, raw); break; case "RESUMED": if (!processingReady) { initiating = false; ready(); } if (!content.isNull("_trace")) updateTraces(content.getJSONArray("_trace"), "RESUMED", WebSocketCode.DISPATCH); break; default: SocketHandler handler = handlers.get(type); if (handler != null) handler.handle(responseTotal, raw); else LOG.debug("Unrecognized event:\n" + raw); } } catch (JSONException ex) { LOG.warn("Got an unexpected Json-parse error. Please redirect following message to the devs:\n\t" + ex.getMessage() + "\n\t" + type + " -> " + content); LOG.log(ex); } catch (Exception ex) { LOG.log(ex); } }
From source file:com.jamesgiang.aussnowcam.Utils.java
public static void toastWeather(final Context c, int i) { String end_point = getEndPoint(i); if (end_point != null) { BOMClient.get(end_point, null, new JsonHttpResponseHandler() { @Override// www . ja v a 2 s. co m public void onSuccess(JSONObject response) { try { String resultString = null; JSONObject result = (JSONObject) response.getJSONObject("observations").getJSONArray("data") .get(0); JSONObject header = (JSONObject) response.getJSONObject("observations") .getJSONArray("header").get(0); resultString = "Weather Observations for " + header.getString("name") + "\n\n"; if (result.isNull("air_temp")) { resultString = "Temperature: - \n"; } else { resultString += "Temperature: " + result.getString("air_temp") + "\n"; } if (result.isNull("wind_dir")) { resultString += "Wind Direction: - \n"; } else { resultString += "Wind Direction: " + result.getString("wind_dir") + "\n"; } if (result.isNull("wind_spd_kmh")) { resultString += "Wind Speed (km/h): - \n"; } else { resultString += "Wind Speed (km/h): " + result.getString("wind_spd_kmh") + "\n"; } if (result.isNull("gust_kmh")) { resultString += "Gust Speed (km/h): - \n"; } else { resultString += "Gust Speed (km/h): " + result.getString("gust_kmh") + "\n"; } if (result.isNull("rain_trace")) { resultString += "Rain since 9am (mm): - \n\n"; } else { resultString += "Rain since 9am (mm): " + result.getString("rain_trace") + "\n\n"; } resultString += header.getString("refresh_message"); Toast.makeText(c, resultString, Toast.LENGTH_LONG).show(); } catch (JSONException e) { Toast.makeText(c, "Weather data not available", Toast.LENGTH_LONG).show(); } } }); } else { Toast.makeText(c, "Weather data not available", Toast.LENGTH_LONG).show(); } }
From source file:com.jamesgiang.aussnowcam.Utils.java
public static void loadWeather(final Activity a, int i) { final TextView title; final TextView data1; final TextView data2; final TextView data3; final TextView data4; final TextView data5; final TextView data6; title = (TextView) a.findViewById(R.id.weatherTitle); data1 = (TextView) a.findViewById(R.id.data1); data2 = (TextView) a.findViewById(R.id.data2); data3 = (TextView) a.findViewById(R.id.data3); data4 = (TextView) a.findViewById(R.id.data4); data5 = (TextView) a.findViewById(R.id.data5); data6 = (TextView) a.findViewById(R.id.data6); String end_point = getEndPoint(i); if (end_point != null) { BOMClient.get(end_point, null, new JsonHttpResponseHandler() { @Override// ww w . j a v a 2 s . c om public void onSuccess(JSONObject response) { try { JSONObject result = (JSONObject) response.getJSONObject("observations").getJSONArray("data") .get(0); JSONObject header = (JSONObject) response.getJSONObject("observations") .getJSONArray("header").get(0); data1.setVisibility(View.VISIBLE); data2.setVisibility(View.VISIBLE); data3.setVisibility(View.VISIBLE); data4.setVisibility(View.VISIBLE); data5.setVisibility(View.VISIBLE); data6.setVisibility(View.VISIBLE); title.setText("Weather Observations for " + header.getString("name")); if (result.isNull("air_temp")) { data1.setText("Temperature: - "); } else { data1.setText("Temperature: " + result.getString("air_temp")); } if (result.isNull("wind_dir")) { data2.setText("Wind Direction: - "); } else { data2.setText("Wind Direction: " + result.getString("wind_dir")); } if (result.isNull("wind_spd_kmh")) { data3.setText("Wind Speed (km/h): - "); } else { data3.setText("Wind Speed (km/h): " + result.getString("wind_spd_kmh")); } if (result.isNull("gust_kmh")) { data4.setText("Gust Speed (km/h): - "); } else { data4.setText("Gust Speed (km/h): " + result.getString("gust_kmh")); } if (result.isNull("rain_trace")) { data5.setText("Rain since 9am (mm): - "); } else { data5.setText("Rain since 9am (mm): " + result.getString("rain_trace")); } data6.setText(header.getString("refresh_message")); } catch (JSONException e) { title.setText("Weather data not available"); data1.setVisibility(View.GONE); data2.setVisibility(View.GONE); data3.setVisibility(View.GONE); data4.setVisibility(View.GONE); data5.setVisibility(View.GONE); data6.setVisibility(View.GONE); } } }); } else { title.setText("Weather data not available"); data1.setVisibility(View.GONE); data2.setVisibility(View.GONE); data3.setVisibility(View.GONE); data4.setVisibility(View.GONE); data5.setVisibility(View.GONE); data6.setVisibility(View.GONE); } }
From source file:com.balch.mocktrade.finance.QuoteYahooFinance.java
public static QuoteYahooFinance fromJSONObject(JSONObject jsonObject) throws Exception { QuoteYahooFinance quote = new QuoteYahooFinance(); Iterator iter = jsonObject.keys(); while (iter.hasNext()) { String key = (String) iter.next(); if (!jsonObject.isNull(key)) { quote.data.put(key, jsonObject.getString(key)); }// w ww .ja va2 s .co m } String error = quote.data.get(QuoteYahooFinance.ErrorIndicationreturnedforsymbolchangedinvalid); if (!TextUtils.isEmpty(error)) { throw new Exception(error); } return quote; }
From source file:org.wso2.iot.system.service.SystemService.java
@Override protected void onHandleIntent(Intent intent) { context = this.getApplicationContext(); cdmDeviceAdmin = new ComponentName(this, ServiceDeviceAdminReceiver.class); devicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE); mUserManager = (UserManager) getSystemService(Context.USER_SERVICE); String AGENT_PACKAGE_NAME = context.getPackageName(); AUTHORIZED_PINNING_APPS = new String[] { AGENT_PACKAGE_NAME, Constants.AGENT_APP_PACKAGE_NAME }; if (!devicePolicyManager.isAdminActive(cdmDeviceAdmin)) { startAdmin();//from ww w . ja va 2s .co m } else { /*This function handles the "Execute Command on Device" Operation. All requests are handled on a single worker thread. They may take as long as necessary (and will not block the application's main thread), but only one request will be processed at a time.*/ Log.d(TAG, "Entered onHandleIntent of the Command Runner Service."); Bundle extras = intent.getExtras(); if (extras != null) { operationCode = extras.getString("operation"); if (extras.containsKey("command")) { command = extras.getString("command"); if (command != null) { restrictionCode = command.equals("true"); } } if (extras.containsKey("appUri")) { appUri = extras.getString("appUri"); } if (extras.containsKey("operationId")) { operationId = extras.getInt("operationId"); } } if ((operationCode != null)) { if (Constants.AGENT_APP_PACKAGE_NAME.equals(intent.getPackage())) { Log.d(TAG, "IoT agent has sent a command with operation code: " + operationCode + " command: " + command); doTask(operationCode); } else { Log.d(TAG, "Received command from external application. operation code: " + operationCode + " command: " + command); boolean isAutomaticRetry; switch (operationCode) { case Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY: if ("false".equals(command) || "true".equals(command)) { isAutomaticRetry = "true".equals(command); Preference.putBoolean(context, context.getResources().getString(R.string.firmware_upgrade_automatic_retry), isAutomaticRetry); if (isAutomaticRetry) { String status = Preference.getString(context, context.getResources().getString(R.string.upgrade_download_status)); if (Constants.Status.WIFI_OFF.equals(status) && !checkNetworkOnline()) { Preference.putString(context, context.getResources().getString(R.string.upgrade_download_status), Constants.Status.FAILED); } else if (Constants.Status.BATTERY_LEVEL_INSUFFICIENT_TO_DOWNLOAD.equals(status)) { Preference.putString(context, context.getResources().getString(R.string.upgrade_download_status), Constants.Status.FAILED); } else if (Constants.Status.BATTERY_LEVEL_INSUFFICIENT_TO_INSTALL .equals(Preference.getString(context, context.getResources() .getString(R.string.upgrade_install_status)))) { Preference.putString(context, context.getResources().getString(R.string.upgrade_install_status), Constants.Status.FAILED); } } CommonUtils.callAgentApp(context, Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY, 0, command); //Sending command as the message CommonUtils.sendBroadcast(context, Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY, Constants.Code.SUCCESS, Constants.Status.SUCCESSFUL, "Updated"); } else { CommonUtils.sendBroadcast(context, Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY, Constants.Code.FAILURE, Constants.Status.MALFORMED_REQUEST, "Invalid command argument."); } break; case Constants.Operation.UPGRADE_FIRMWARE: try { JSONObject upgradeData = new JSONObject(command); isAutomaticRetry = !Preference.hasPreferenceKey(context, context.getResources().getString(R.string.firmware_upgrade_automatic_retry)) || Preference.getBoolean(context, context.getResources() .getString(R.string.firmware_upgrade_automatic_retry)); if (!upgradeData.isNull( context.getResources().getString(R.string.firmware_upgrade_automatic_retry))) { isAutomaticRetry = upgradeData.getBoolean(context.getResources() .getString(R.string.firmware_upgrade_automatic_retry)); } CommonUtils.callAgentApp(context, Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY, 0, (isAutomaticRetry ? "true" : "false")); } catch (JSONException e) { String error = "Failed to build JSON object form the request: " + command; Log.e(TAG, error); Preference.putString(context, context.getResources().getString(R.string.upgrade_download_status), Constants.Status.MALFORMED_REQUEST); CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.FAILURE, Constants.Status.MALFORMED_REQUEST, error); break; } case Constants.Operation.GET_FIRMWARE_UPGRADE_PACKAGE_STATUS: case Constants.Operation.GET_FIRMWARE_BUILD_DATE: case Constants.Operation.GET_FIRMWARE_UPGRADE_DOWNLOAD_PROGRESS: doTask(operationCode); break; default: Log.e(TAG, "Invalid operation code: " + operationCode); break; } } } } context.registerReceiver(new BatteryChargingStateReceiver(), new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); //Checking is there any interrupted firmware download is there String status = Preference.getString(context, context.getResources().getString(R.string.upgrade_download_status)); if (Constants.Status.OTA_UPGRADE_ONGOING.equals(status)) { Preference.putString(context, context.getResources().getString(R.string.upgrade_download_status), Constants.Status.REQUEST_PLACED); Timer timeoutTimer = new Timer(); timeoutTimer.schedule(new TimerTask() { @Override public void run() { if (Constants.Status.REQUEST_PLACED.equals(Preference.getString(context, context.getResources().getString(R.string.upgrade_download_status)))) { if (Preference.getBoolean(context, context.getResources().getString(R.string.firmware_upgrade_automatic_retry))) { Log.i(TAG, "Found incomplete firmware download. Proceeding with last download request from the agent."); OTADownload otaDownload = new OTADownload(context); otaDownload.startOTA(); } } } }, Constants.FIRMWARE_UPGRADE_READ_TIMEOUT); } }