List of usage examples for android.os Looper getMainLooper
public static Looper getMainLooper()
From source file:android.bus.EventBus.java
private void checkPostStickyEventToSubscription(Subscription newSubscription, Object stickyEvent) { if (stickyEvent != null) { // If the subscriber is trying to abort the event, it will fail (event is not tracked in posting state) // --> Strange corner case, which we don't take care of here. postToSubscription(newSubscription, stickyEvent, Looper.getMainLooper() == Looper.myLooper()); }// w ww . j a v a 2s . c om }
From source file:com.markodevcic.eventhub.EventHub.java
private <T extends BaseEvent> void executeOnEvent(final OnEvent<T> onEvent, final T event, PublicationMode publicationMode) { switch (publicationMode) { case MAIN_THREAD: if (Looper.getMainLooper().getThread() == Thread.currentThread()) { onEvent.invoke(event);//www . ja v a 2 s. c o m } else { MainThreadScheduler.schedule(() -> onEvent.invoke(event)); } break; case BACKGROUND_THREAD: BackgroundThreadScheduler.schedule(() -> onEvent.invoke(event)); break; case CALLING_THREAD: onEvent.invoke(event); break; } }
From source file:com.TagFu.facebook.Session.java
/** * Used by version 2 of the serialization proxy, do not modify. *///w ww . j a v a 2 s .co m private Session(final String applicationId, final SessionState state, final AccessToken tokenInfo, final Date lastAttemptedTokenExtendDate, final boolean shouldAutoPublish, final AuthorizationRequest pendingAuthorizationRequest, final Set<String> requestedPermissions) { this.applicationId = applicationId; this.state = state; this.tokenInfo = tokenInfo; this.lastAttemptedTokenExtendDate = lastAttemptedTokenExtendDate; this.pendingAuthorizationRequest = pendingAuthorizationRequest; this.handler = new Handler(Looper.getMainLooper()); this.currentTokenRefreshRequest = null; this.tokenCachingStrategy = null; this.callbacks = new ArrayList<StatusCallback>(); }
From source file:com.facebook.internal.LikeActionController.java
private synchronized static void performFirstInitialize() { if (isInitialized) { return;/*from w w w. j ava 2s . c om*/ } handler = new Handler(Looper.getMainLooper()); SharedPreferences sharedPreferences = applicationContext.getSharedPreferences(LIKE_ACTION_CONTROLLER_STORE, Context.MODE_PRIVATE); objectSuffix = sharedPreferences.getInt(LIKE_ACTION_CONTROLLER_STORE_OBJECT_SUFFIX_KEY, 1); controllerDiskCache = new FileLruCache(applicationContext, TAG, new FileLruCache.Limits()); registerSessionBroadcastReceivers(); isInitialized = true; }
From source file:com.quantcast.measurement.service.QCLocation.java
private void sendLocation(Location location) { final Double lat = location.getLatitude(); final Double longTemp = location.getLongitude(); _geoTask = new AsyncTask<Double, Void, MeasurementLocation>() { @Override//w ww . j av a 2s. c o m protected MeasurementLocation doInBackground(Double... params) { MeasurementLocation retval; double latitude = params[0]; double longitude = params[1]; QCLog.i(TAG, "Looking for address."); try { QCLog.i(TAG, "Geocoder."); List<Address> addresses = _geocoder.getFromLocation(latitude, longitude, 1); if (addresses != null && addresses.size() > 0) { Address address = addresses.get(0); retval = new MeasurementLocation(address.getCountryCode(), address.getAdminArea(), address.getLocality(), address.getPostalCode()); } else { QCLog.i(TAG, "Geocoder reverse lookup failed."); retval = this.fallbackGeoLocate(latitude, longitude); } } catch (Exception e) { QCLog.i(TAG, "Geocoder API not available."); retval = this.fallbackGeoLocate(latitude, longitude); } return retval; } protected MeasurementLocation fallbackGeoLocate(double latitude, double longitude) { MeasurementLocation retval = null; // call googles map api directly MeasurementLocation geoInfo = lookup(latitude, longitude); if (geoInfo != null && !this.isCancelled()) { retval = geoInfo; } else { QCLog.i(TAG, "Google Maps API reverse lookup failed."); } return retval; } @Override protected void onPostExecute(MeasurementLocation address) { if (null != address && address.getCountry() != null) { QCLog.i(TAG, "Got address and sending..." + address.getCountry() + " " + address.getState() + " " + address.getLocality()); HashMap<String, String> params = new HashMap<String, String>(); params.put(QCEvent.QC_EVENT_KEY, QC_EVENT_LOCATION); if (address.getCountry() != null) { params.put(QC_COUNTRY_KEY, address.getCountry()); } if (address.getState() != null) { params.put(QC_STATE_KEY, address.getState()); } if (address.getLocality() != null) { params.put(QC_CITY_KEY, address.getLocality()); } if (address.getPostalCode() != null) { params.put(QC_POSTALCODE_KEY, address.getPostalCode()); } QCMeasurement.INSTANCE.logOptionalEvent(params, null, null); } } }; //Async execute needs to be on main thread if (Looper.getMainLooper().getThread() == Thread.currentThread()) { if (_geoTask != null && _geoTask.getStatus() == AsyncTask.Status.PENDING) { _geoTask.execute(lat, longTemp); } } else { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { if (_geoTask != null && _geoTask.getStatus() == AsyncTask.Status.PENDING) { _geoTask.execute(lat, longTemp); } } }); } }
From source file:com.android.mail.browse.ConversationCursor.java
public ConversationCursor(Activity activity, Uri uri, boolean useInitialConversationLimit, String name) { mUseInitialConversationLimit = useInitialConversationLimit; mResolver = activity.getApplicationContext().getContentResolver(); qUri = uri;/*from w w w . j ava 2s . c o m*/ mName = name; qProjection = UIProvider.CONVERSATION_PROJECTION; mCursorObserver = new CursorObserver(new Handler(Looper.getMainLooper())); // Disable caching on low memory devices mCachingEnabled = !Utils.isLowRamDevice(activity); }
From source file:com.numenta.core.service.DataSyncService.java
/** * This method is execute periodically and update {@link com.numenta.core.data.CoreDatabase} * with new data from the/* w w w . j a v a 2 s .c om*/ * server. */ protected void synchronizeWithServer() throws IOException { Log.i(TAG, "synchronizeWithServer"); if (_synchronizingWithServer) { return; } if (!NetUtils.isConnected()) { // Not connected, skip until we connect return; } final CoreDatabase database = HTMApplication.getDatabase(); if (database == null) { return; } synchronized (this) { if (_synchronizingWithServer) { return; } _synchronizingWithServer = true; } String result = null; try { // Guard against blocking the UI Thread if (Looper.myLooper() == Looper.getMainLooper()) { throw new IllegalStateException("You should not access the database from the UI thread"); } fireRefreshStateEvent(_synchronizingWithServer); final Context context = _service.getApplicationContext(); final long now = System.currentTimeMillis(); // Check if enough time has passed since we checked for new data SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); final long lastConnectedTime = prefs.getLong(PREF_LAST_CONNECTED_TIME, 0); if (now - lastConnectedTime < DataUtils.METRIC_DATA_INTERVAL) { return; } // Calculate hours since last update. This information will be // passed to the user together with error message final CharSequence hoursSinceData = DateUtils.getRelativeTimeSpanString(database.getLastTimestamp(), now, DateUtils.MINUTE_IN_MILLIS); Future<?> pendingIO = null; try { // Try to connect to server if (_htmClient == null) { _htmClient = _service.connectToServer(); } if (_htmClient == null) { throw new IOException("Unable to connect to server"); } // Update last connected time SharedPreferences.Editor editor = prefs.edit(); editor.putLong(PREF_LAST_CONNECTED_TIME, now); editor.apply(); // Start by downloading all the metrics available from backend // in a background IO thread pendingIO = _service.getIOThreadPool().submit(new Callable<Void>() { @Override public Void call() throws Exception { try { // First load metrics loadAllMetrics(); // Load all annotations after metrics loadAllAnnotations(); // Load all data after annotations loadAllData(); // Synchronize notifications after data synchronizeNotifications(); // Synchronize application data last HTMApplication.getInstance().loadApplicationData(_htmClient); } catch (android.database.sqlite.SQLiteFullException e) { // Try to delete old records to make room if possible Log.e(TAG, "Failed to save data into database", e); database.deleteOldRecords(); } return null; } }); // Wait for metric data to finish pendingIO.get(); } catch (InterruptedException e) { // Cancel pending tasks if (!pendingIO.isDone()) { pendingIO.cancel(true); } Log.w(TAG, "Interrupted while loading data"); } catch (ExecutionException e) { // Cancel pending tasks if (!pendingIO.isDone()) { pendingIO.cancel(true); } Throwable original = e.getCause(); if (original instanceof AuthenticationException) { _service.fireAuthenticationFailedEvent(); } else if (original instanceof ObjectNotFoundException) { Log.e(TAG, "Error loading data", e); result = context.getString(R.string.refresh_update_error, hoursSinceData); } else if (original instanceof IOException) { Log.e(TAG, "Unable to connect", e); result = context.getString(R.string.refresh_server_unreachable, hoursSinceData); } else { Log.e(TAG, "Error loading data", e); result = context.getString(R.string.refresh_update_error, hoursSinceData); } } catch (AuthenticationException e) { _service.fireAuthenticationFailedEvent(); } catch (HTMException e) { Log.e(TAG, "Error loading data", e); result = context.getString(R.string.refresh_update_error, hoursSinceData); } catch (IOException e) { Log.e(TAG, "Unable to connect", e); result = context.getString(R.string.refresh_server_unreachable, hoursSinceData); } } finally { _synchronizingWithServer = false; fireRefreshStateEvent(_synchronizingWithServer, result); } }
From source file:com.hybris.mobile.lib.http.PersistenceHelper.java
/** * Create a proper json error and send the response through the ResponseCallBack * * @param responseReceiver Data returned after REST Call * @param dataResponse ResponseCallBack * @param dataConverterHelper Transform Data from JSON into a POJO * @param requestId Unique Request Identifier *//* ww w. j av a 2 s . co m*/ private <Z, T> void handleGenericError(final ResponseCallback<T, Z> responseReceiver, DataResponse dataResponse, DataConverter.Helper<T, Z> dataConverterHelper, String requestId) { String errorMsg = dataResponse.getData(); // Unknown error if no message coming from the http layer if (StringUtils.isBlank(errorMsg)) { errorMsg = mContext.getString(R.string.error_unknown); } errorMsg = StringEscapeUtils.escapeEcmaScript(errorMsg); try { final Response<Z> response = Response.createResponse( mDataConverter.convertFrom(dataConverterHelper.getErrorClassName(), mDataConverter.createErrorMessage(errorMsg, Constants.ERROR_TYPE_UNKNOWN)), requestId, dataResponse.isSync()); if (mUiRelated) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { responseReceiver.onError(response); } }); } else { responseReceiver.onError(response); } } catch (DataConverterException e1) { throw new IllegalArgumentException(e1.getLocalizedMessage()); } }
From source file:hochschuledarmstadt.photostream_tools.PhotoStreamClientImpl.java
void bootstrap() { internetAvailableBroadcastReceiver = new BroadcastReceiver() { @Override// w ww . j ava2s.co m public void onReceive(Context context, Intent intent) { if (webSocketClient != null) { if (isOnline() && !webSocketClient.isConnected()) webSocketClient.connect(); else if (!isOnline()) { webSocketClient.destroy(); } } } }; if (webSocketClient != null) { webSocketClient.setMessageListener(this); webSocketClient.connect(); } new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { @Override public void run() { registerInternetAvailableBroadcastReceiver(); } }, 2000); }
From source file:com.networking.ApiTestActivity.java
public void checkForHeaderPost(View view) { ANRequest.PostRequestBuilder postRequestBuilder = AndroidNetworking .post(ApiEndPoint.BASE_URL + ApiEndPoint.CHECK_FOR_HEADER); postRequestBuilder.addHeaders("token", "1234"); ANRequest anRequest = postRequestBuilder.setTag(this).setPriority(Priority.LOW) .setExecutor(Executors.newSingleThreadExecutor()).build(); anRequest.setAnalyticsListener(new AnalyticsListener() { @Override/*from ww w.ja v a2 s.co m*/ public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) { Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis); Log.d(TAG, " bytesSent : " + bytesSent); Log.d(TAG, " bytesReceived : " + bytesReceived); Log.d(TAG, " isFromCache : " + isFromCache); } }); anRequest.getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { Log.d(TAG, "onResponse object : " + response.toString()); Log.d(TAG, "onResponse isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper())); } @Override public void onError(ANError error) { if (error.getErrorCode() != 0) { // received ANError from server // error.getErrorCode() - the ANError code from server // error.getErrorBody() - the ANError body from server // error.getErrorDetail() - just a ANError detail Log.d(TAG, "onError errorCode : " + error.getErrorCode()); Log.d(TAG, "onError errorBody : " + error.getErrorBody()); Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } else { // error.getErrorDetail() : connectionError, parseError, requestCancelledError Log.d(TAG, "onError errorDetail : " + error.getErrorDetail()); } } }); }