List of usage examples for android.os SystemClock elapsedRealtime
@CriticalNative native public static long elapsedRealtime();
From source file:com.mr.http.toolbox.MR_BasicNetwork.java
@Override public MR_NetworkResponse performRequest(MR_Request<?> request) throws MR_VolleyError { long requestStart = SystemClock.elapsedRealtime(); while (true) { HttpResponse httpResponse = null; byte[] responseContents = null; Map<String, String> responseHeaders = new HashMap<String, String>(); try {/*from w w w . j av a2s. c o m*/ // Gather headers. Map<String, String> headers = new HashMap<String, String>(); addCacheHeaders(headers, request.getCacheEntry()); httpResponse = mHttpStack.performRequest(request, headers); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); responseHeaders = convertHeaders(httpResponse.getAllHeaders()); // Handle cache validation. if (statusCode == HttpStatus.SC_NOT_MODIFIED) { return new MR_NetworkResponse(HttpStatus.SC_NOT_MODIFIED, request.getCacheEntry().data, responseHeaders, true); } // Some responses such as 204s do not have content. We must check. if (httpResponse.getEntity() != null) { responseContents = entityToBytes(httpResponse.getEntity()); } else { // Add 0 byte response as a way of honestly representing a // no-content request. responseContents = new byte[0]; } // if the request is slow, log it. long requestLifetime = SystemClock.elapsedRealtime() - requestStart; logSlowRequests(requestLifetime, request, responseContents, statusLine); if (statusCode < 200 || statusCode > 299) { throw new IOException(); } return new MR_NetworkResponse(statusCode, responseContents, responseHeaders, false); } catch (SocketTimeoutException e) { attemptRetryOnException("socket", request, new MR_TimeoutError()); } catch (ConnectTimeoutException e) { attemptRetryOnException("connection", request, new MR_TimeoutError()); } catch (MalformedURLException e) { throw new RuntimeException("Bad URL " + request.getUrl(), e); } catch (IOException e) { int statusCode = 0; MR_NetworkResponse networkResponse = null; if (httpResponse != null) { statusCode = httpResponse.getStatusLine().getStatusCode(); } else { throw new MR_NoConnectionError(e); } MR_VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl()); if (responseContents != null) { networkResponse = new MR_NetworkResponse(statusCode, responseContents, responseHeaders, false); if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) { attemptRetryOnException("auth", request, new MR_AuthFailureError(networkResponse)); } else { // TODO: Only throw ServerError for 5xx status codes. throw new MR_ServerError(networkResponse); } } else { throw new MR_NetworkError(networkResponse); } } } }
From source file:com.appbase.connection.toolbox.BasicNetwork.java
@Override public NetworkResponse performRequest(Request<?> request) throws VolleyError { long requestStart = SystemClock.elapsedRealtime(); while (true) { HttpResponse httpResponse = null; byte[] responseContents = null; Map<String, String> responseHeaders = new HashMap<String, String>(); try {//from w ww. j a v a 2s . co m // Gather headers. Map<String, String> headers = new HashMap<String, String>(); addCacheHeaders(headers, request.getCacheEntry()); httpResponse = mHttpStack.performRequest(request, headers); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); responseHeaders = convertHeaders(httpResponse.getAllHeaders()); // Handle cache validation. if (statusCode == HttpStatus.SC_NOT_MODIFIED) { return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, request.getCacheEntry().data, responseHeaders, true); } responseContents = entityToBytes(httpResponse.getEntity()); // if the request is slow, log it. long requestLifetime = SystemClock.elapsedRealtime() - requestStart; logSlowRequests(requestLifetime, request, responseContents, statusLine); if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_NO_CONTENT) { throw new IOException(); } return new NetworkResponse(statusCode, responseContents, responseHeaders, false); } catch (SocketTimeoutException e) { attemptRetryOnException("socket", request, new TimeoutError()); } catch (ConnectTimeoutException e) { attemptRetryOnException("connection", request, new TimeoutError()); } catch (MalformedURLException e) { throw new RuntimeException("Bad URL " + request.getUrl(), e); } catch (IOException e) { int statusCode = 0; NetworkResponse networkResponse = null; if (httpResponse != null) { statusCode = httpResponse.getStatusLine().getStatusCode(); } else { throw new NoConnectionError(e); } VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl()); if (responseContents != null) { networkResponse = new NetworkResponse(statusCode, responseContents, responseHeaders, false); if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) { attemptRetryOnException("auth", request, new AuthFailureError(networkResponse)); } else { // TODO: Only throw ServerError for 5xx status codes. throw new ServerError(networkResponse); } } else { throw new NetworkError(networkResponse); } } } }
From source file:com.baseproject.volley.toolbox.BasicNetwork.java
@Override public NetworkResponse performRequest(Request<?> request) throws VolleyError { long requestStart = SystemClock.elapsedRealtime(); while (true) { HttpResponse httpResponse = null; byte[] responseContents = null; Map<String, String> responseHeaders = new HashMap<String, String>(); try {/* www . j a v a 2s . c om*/ // Gather headers. Map<String, String> headers = new HashMap<String, String>(); addCacheHeaders(headers, request.getCacheEntry()); httpResponse = mHttpStack.performRequest(request, headers); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); responseHeaders = convertHeaders(httpResponse.getAllHeaders()); // Handle cache validation. if (statusCode == HttpStatus.SC_NOT_MODIFIED) { return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, request.getCacheEntry() == null ? null : request.getCacheEntry().data, responseHeaders.get("Etag"), HttpHeaderParser.parseCharset(responseHeaders), true, request.getExpireTime()); } // Some responses such as 204s do not have content. We must check. if (httpResponse.getEntity() != null) { responseContents = entityToBytes(httpResponse.getEntity()); // TODO add to ensure download correct add by fenglei // long realLength = responseContents.length; // long requireLength = httpResponse.getEntity().getContentLength(); // if(realLength != requireLength && requireLength != -1) { // Log.i("Error", "realLength = " + realLength + ", requireLength = " + requireLength); // } if (responseContents != null && httpResponse.getEntity().getContentLength() > 0 && responseContents.length != httpResponse.getEntity().getContentLength()) { attemptRetryOnException("socket", request, new VolleyError(Util.buildHttpErrorMsg("failed", -1, "ContentLength Error"))); continue; } } else { // Add 0 byte response as a way of honestly representing a // no-content request. responseContents = new byte[0]; } // if the request is slow, log it. long requestLifetime = SystemClock.elapsedRealtime() - requestStart; logSlowRequests(requestLifetime, request, responseContents, statusLine); // if (statusCode < 200 || statusCode > 299) { // throw new IOException(); // } if (request.isUpdateCookie()) { Header[] cookies = httpResponse.getHeaders("Set-Cookie"); int count = cookies.length; int i = 0; StringBuilder cookieBuilder = new StringBuilder(); for (Header cookie : cookies) { String cookieStr = cookie.getValue(); i++; if (!TextUtils.isEmpty(cookieStr) && cookieStr.length() > 10) { int end = cookieStr.indexOf(" "); if (i == count) { cookieStr = cookieStr.subSequence(0, end - 1).toString(); } else { cookieStr = cookieStr.subSequence(0, end).toString(); } cookieBuilder.append(cookieStr).append(" "); } } if (cookieBuilder.length() > 0) { cookieBuilder.deleteCharAt(cookieBuilder.length() - 1); } request.setUpdateCookie(cookieBuilder.toString()); } return new NetworkResponse(statusCode, responseContents, responseHeaders.get("Etag"), HttpHeaderParser.parseCharset(responseHeaders), false, request.getExpireTime()); } catch (SocketTimeoutException e) { attemptRetryOnException("socket", request, new VolleyError( Util.buildHttpErrorMsg("failed", -1, HttpRequestManager.STATE_ERROR_TIMEOUT))); } catch (ConnectTimeoutException e) { attemptRetryOnException("connection", request, new VolleyError( Util.buildHttpErrorMsg("failed", -1, HttpRequestManager.STATE_ERROR_TIMEOUT))); } catch (MalformedURLException e) { throw new VolleyError(Util.buildHttpErrorMsg("failed", -1, HttpRequestManager.STATE_ERROR_MALFORMED_URL_EXCEPTION)); // throw new RuntimeException("Bad URL " + request.getUrl(), e); } catch (IOException e) { attemptRetryOnException("io", request, new VolleyError(e)); // int statusCode = 0; // NetworkResponse networkResponse = null; // if (httpResponse != null) { // statusCode = httpResponse.getStatusLine().getStatusCode(); // } else { // throw new NoConnectionError(e); // } // VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl()); // if (responseContents != null) { // networkResponse = new NetworkResponse(statusCode, responseContents, // responseHeaders, false); // if (statusCode == HttpStatus.SC_UNAUTHORIZED || // statusCode == HttpStatus.SC_FORBIDDEN) { // attemptRetryOnException("auth", // request, new AuthFailureError(networkResponse)); // } else { // // TODO: Only throw ServerError for 5xx status codes. // throw new ServerError(networkResponse); // } // } else { // throw new NetworkError(networkResponse); // } } } }
From source file:com.mgalgs.trackthatthing.LocationReceiver.java
@Override public void onReceive(Context context, Intent intent) { mContext = context;//from w w w .j av a 2 s . c o m Location loc = (Location) intent.getExtras().get(LocationPoller.EXTRA_LOCATION); if (loc == null) { msg = intent.getStringExtra(LocationPoller.EXTRA_ERROR); } else { SharedPreferences settings = context.getSharedPreferences(TrackThatThing.PREFS_NAME, Context.MODE_PRIVATE); long sleep_period = settings.getLong(TrackThatThing.PREF_SLEEP_TIME, TrackThatThing.DEFAULT_SLEEP_TIME); if (getTimeSinceLastLoc_S() > sleep_period - 3 || mLastLocTime == -1) { // it has been long enough } else { // it hasn't been long enough! Log.d(TrackThatThing.TAG, "It has only been " + getTimeSinceLastLoc_S() + " seconds since the last location update, not long enough!"); return; } mLastLocTime = SystemClock.elapsedRealtime(); float acc = loc.getAccuracy(); double lat = loc.getLatitude(); double lon = loc.getLongitude(); float speed = loc.getSpeed(); String secret_code = settings.getString(TrackThatThing.PREF_SECRET_CODE, null); QueryString qs = new QueryString(TrackThatThing.BASE_URL + "/put"); qs.add("secret", secret_code); qs.add("lat", Double.toString(lat)); qs.add("lon", Double.toString(lon)); qs.add("acc", Float.toString(acc)); qs.add("speed", Float.toString(speed)); Runnable r = new MyInternetThread(qs); new Thread(r).start(); msg = loc.toString(); } Log.d(TrackThatThing.TAG, "got this location: " + msg); }
From source file:com.ta.truckmap.gpstracking.GcmIntentService.java
@Override protected void onHandleIntent(Intent intent) { Bundle extras = intent.getExtras();/*w ww. j a v a 2s . c om*/ GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); String messageType = gcm.getMessageType(intent); if (!extras.isEmpty()) { if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) { sendNotification("Send error: " + extras.toString()); } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) { sendNotification("Deleted messages on server: " + extras.toString()); // If it's a regular GCM message, do some work. } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) { // This loop represents the service doing some work. for (int i = 0; i < 1; i++) { Log.i(TAG, "Working... " + (i + 1) + "/5 @ " + SystemClock.elapsedRealtime()); try { Thread.sleep(5000); } catch (InterruptedException e) { } } Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime()); // Post notification of received message. realMsg = extras.getString("payload"); /*if (Utility.getSharedPrefStringData(getApplicationContext(), "driverrtype").equalsIgnoreCase("1")) {*/ displayMsg(realMsg); /*}*/ Log.i(TAG, "Received: " + extras.toString()); } } GcmBroadcastReceiver.completeWakefulIntent(intent); }
From source file:com.hkc.android.volley.toolbox.BasicNetwork.java
@Override public NetworkResponse performRequest(Request<?> request) throws VolleyError { long requestStart = SystemClock.elapsedRealtime(); while (true) { HttpResponse httpResponse = null; byte[] responseContents = null; Map<String, String> responseHeaders = new HashMap<String, String>(); try {// w w w . j ava2 s . c o m // Gather headers. Map<String, String> headers = new HashMap<String, String>(); addCacheHeaders(headers, request.getCacheEntry()); httpResponse = mHttpStack.performRequest(request, headers); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); responseHeaders = convertHeaders(httpResponse.getAllHeaders()); // Handle cache validation. if (statusCode == HttpStatus.SC_NOT_MODIFIED) { return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, request.getCacheEntry() == null ? null : request.getCacheEntry().data, responseHeaders, true); } // Handle moved resources if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) { String newUrl = responseHeaders.get("Location"); request.setRedirectUrl(newUrl); } // Some responses such as 204s do not have content. We must check. if (httpResponse.getEntity() != null) { responseContents = entityToBytes(httpResponse.getEntity()); } else { // Add 0 byte response as a way of honestly representing a // no-content request. responseContents = new byte[0]; } // if the request is slow, log it. long requestLifetime = SystemClock.elapsedRealtime() - requestStart; logSlowRequests(requestLifetime, request, responseContents, statusLine); if (statusCode < 200 || statusCode > 299) { throw new IOException(); } return new NetworkResponse(statusCode, responseContents, responseHeaders, false); } catch (SocketTimeoutException e) { attemptRetryOnException("socket", request, new TimeoutError()); } catch (ConnectTimeoutException e) { attemptRetryOnException("connection", request, new TimeoutError()); } catch (MalformedURLException e) { throw new RuntimeException("Bad URL " + request.getUrl(), e); } catch (IOException e) { int statusCode = 0; NetworkResponse networkResponse = null; if (httpResponse != null) { statusCode = httpResponse.getStatusLine().getStatusCode(); } else { throw new NoConnectionError(e); } if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) { VolleyLog.e("Request at %s has been redirected to %s", request.getOriginUrl(), request.getUrl()); } else { VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl()); } if (responseContents != null) { networkResponse = new NetworkResponse(statusCode, responseContents, responseHeaders, false); if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) { attemptRetryOnException("auth", request, new AuthFailureError(networkResponse)); } else if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) { attemptRetryOnException("redirect", request, new AuthFailureError(networkResponse)); } else { // TODO: Only throw ServerError for 5xx status codes. throw new ServerError(networkResponse); } } else { throw new NetworkError(networkResponse); } } } }
From source file:com.playpalgames.app.GcmIntentService.java
@Override protected void onHandleIntent(Intent intent) { Bundle extras = intent.getExtras();//from w w w . ja v a 2 s . c o m GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); // The getMessageType() intent parameter must be the intent you received // in your BroadcastReceiver. String messageType = gcm.getMessageType(intent); if (!extras.isEmpty()) { // has effect of unparcelling Bundle /* * Filter messages based on message type. Since it is likely that GCM * will be extended in the future with new message types, just ignore * any message types you're not interested in, or that you don't * recognize. */ if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) { processMessage("Send error: " + extras.toString()); } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) { processMessage("Deleted messages on server: " + extras.toString()); // If it's a regular GCM message, do some work. } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) { Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime()); // Post notification of received message. processMessage(extras.getString("message")); Log.i(TAG, "Received: " + extras.toString()); } } // Release the wake lock provided by the WakefulBroadcastReceiver. GcmBroadcastReceiver.completeWakefulIntent(intent); }
From source file:com.oliversride.wordryo.UpdateCheckReceiver.java
public static void restartTimer(Context context) { AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(context, UpdateCheckReceiver.class); PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0); am.cancel(pi);/*from ww w .j a v a 2 s . c o m*/ long interval_millis = INTERVAL_ONEDAY; if (!devOK(context)) { interval_millis *= INTERVAL_NDAYS; } interval_millis = (interval_millis / 2) + Math.abs(Utils.nextRandomInt() % interval_millis); am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + interval_millis, interval_millis, pi); }
From source file:de.hero.vertretungsplan.CheckForAppUpdate.java
@Override public int onStartCommand(Intent intent, int flags, int startId) { boolean setTimer = intent.getBooleanExtra("setTimer", false); boolean checkNow = intent.getBooleanExtra("checkNow", false); Intent i = new Intent(this, de.hero.vertretungsplan.CheckForAppUpdate.class); i.putExtra("checkNow", true); PendingIntent pi = PendingIntent.getService(this, 0, i, 0); AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); am.cancel(pi);//from w w w . j a v a 2 s . co m Log.d("CheckForAppUpdate", "Alarm canceled"); if (setTimer) { long lngInterval = AlarmManager.INTERVAL_DAY * 7; Log.d("CheckForAppUpdate", "Alarm set"); am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_DAY * 6, lngInterval, pi); //For debugging: after 10 seconds //am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 25000 , AlarmManager.INTERVAL_HOUR , pi); } if (checkNow) { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected()) { try { new HtmlWorkAppUpdate(this).execute(new URI(getString(R.string.htmlAdresseAktuelleVersion))); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return START_NOT_STICKY; }
From source file:com.duowan.mobile.netroid.toolbox.BasicNetwork.java
@Override public NetworkResponse performRequest(Request<?> request) throws NetroidError { // Determine if request had non-http perform. NetworkResponse networkResponse = request.perform(); if (networkResponse != null) return networkResponse; long requestStart = SystemClock.elapsedRealtime(); while (true) { // If the request was cancelled already, // do not perform the network request. if (request.isCanceled()) { request.finish("perform-discard-cancelled"); mDelivery.postCancel(request); throw new NetworkError(networkResponse); }//ww w . j av a 2s .co m HttpResponse httpResponse = null; byte[] responseContents = null; try { // prepare to perform this request, normally is reset the request headers. request.prepare(); httpResponse = mHttpStack.performRequest(request); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode < 200 || statusCode > 299) throw new IOException(); responseContents = request.handleResponse(httpResponse, mDelivery); // if the request is slow, log it. long requestLifetime = SystemClock.elapsedRealtime() - requestStart; logSlowRequests(requestLifetime, request, responseContents, statusLine); return new NetworkResponse(statusCode, responseContents, parseCharset(httpResponse)); } catch (SocketTimeoutException e) { attemptRetryOnException("socket", request, new TimeoutError()); } catch (ConnectTimeoutException e) { attemptRetryOnException("connection", request, new TimeoutError()); } catch (MalformedURLException e) { throw new RuntimeException("Bad URL " + request.getUrl(), e); } catch (IOException e) { if (httpResponse == null) throw new NoConnectionError(e); int statusCode = httpResponse.getStatusLine().getStatusCode(); NetroidLog.e("Unexpected response code %d for %s", statusCode, request.getUrl()); if (responseContents != null) { networkResponse = new NetworkResponse(statusCode, responseContents, parseCharset(httpResponse)); if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) { attemptRetryOnException("auth", request, new AuthFailureError(networkResponse)); } else { // TODO: Only throw ServerError for 5xx status codes. throw new ServerError(networkResponse); } } else { throw new NetworkError(networkResponse); } } } }