Example usage for android.os Looper myLooper

List of usage examples for android.os Looper myLooper

Introduction

In this page you can find the example usage for android.os Looper myLooper.

Prototype

public static @Nullable Looper myLooper() 

Source Link

Document

Return the Looper object associated with the current thread.

Usage

From source file:com.mediatek.systemupdate.HttpManager.java

private HttpManager(Context context) {
    mContext = context;//from ww w  . j  ava 2s  .c o  m
    mDownloadInfo = DownloadInfo.getInstance(mContext);
    mNotification = new NotifyManager(mContext);
    initHttpParam();
    initHttpClientMgr();
    new Thread() {
        public void run() {
            Xlog.v(TAG, "thread run " + Thread.currentThread().getName());
            Looper.prepare();
            mToastHandler = new Handler(Looper.myLooper()) {

                @Override
                public void handleMessage(Message msg) {
                    switch (msg.what) {
                    case NETWORK_ERROR_TOAST:
                        Toast.makeText(mContext, R.string.network_error, Toast.LENGTH_SHORT).show();
                        break;
                    case SERVER_VERSION_ERROR_TOAST:
                        Toast.makeText(mContext, R.string.server_version_error, Toast.LENGTH_LONG).show();
                        break;
                    default:
                        break;
                    }
                }
            };
            Looper.loop();
        }
    }.start();
}

From source file:cn.com.hgh.view.SlideSwitch.java

/**
 * draw again/*  ww w . jav  a2s  .  c  o  m*/
 */
private void invalidateView() {
    if (Looper.getMainLooper() == Looper.myLooper()) {
        invalidate();
    } else {
        postInvalidate();
    }
}

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());
    }//from   w  ww  .j a v a  2 s .c o m
}

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/*from  w w  w  .  j a v  a  2s . co m*/
 * 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.flyn.net.asynchttp.AsyncHttpResponseHandler.java

/**
 * Helper method to send runnable into local handler loop
 *
 * @param runnable runnable instance, can be null
 *///from w  w w . j ava 2  s .c  o  m
protected void postRunnable(Runnable runnable) {
    boolean missingLooper = null == Looper.myLooper();
    if (missingLooper) {
        Looper.prepare();
    }
    if (null == handler) {
        handler = new ResponderHandler(this);
    }
    if (null != runnable) {
        handler.post(runnable);
    }
    if (missingLooper) {
        Looper.loop();
    }
}

From source file:de.manumaticx.crouton.Manager.java

/**
 * Removes the {@link Crouton}'s view after it's display
 * durationInMilliseconds./* w ww  . j a  v  a2 s  .c  o  m*/
 *
 * @param crouton
 *     The {@link Crouton} added to a {@link ViewGroup} and should be
 *     removed.
 */
protected void removeCrouton(Crouton crouton) {
    View croutonView = crouton.getView();
    ViewGroup croutonParentView = (ViewGroup) croutonView.getParent();

    if (null != croutonParentView) {
        if (Looper.myLooper() == Looper.getMainLooper()) {

            croutonView.startAnimation(crouton.getOutAnimation());
            // Remove the Crouton from the queue.
            Crouton removed = croutonQueue.poll();

            // Remove the crouton from the view's parent.
            croutonParentView.removeView(croutonView);
            if (null != removed) {
                removed.detachActivity();
                removed.detachViewGroup();
                if (null != removed.getLifecycleCallback()) {
                    removed.getLifecycleCallback().onRemoved();
                }
                removed.detachLifecycleCallback();
            }

            // Send a message to display the next crouton but delay it by the out
            // animation duration to make sure it finishes
            sendMessageDelayed(crouton, Messages.DISPLAY_CROUTON, crouton.getOutAnimation().getDuration());
        } else {
            final View mCroutonView = croutonView;
            final ViewGroup mCroutonParentView = croutonParentView;
            final Crouton mCrouton = crouton;
            crouton.getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mCroutonView.startAnimation(mCrouton.getOutAnimation());
                    // Remove the Crouton from the queue.
                    Crouton removed = croutonQueue.poll();

                    // Remove the crouton from the view's parent.
                    mCroutonParentView.removeView(mCroutonView);
                    if (null != removed) {
                        removed.detachActivity();
                        removed.detachViewGroup();
                        if (null != removed.getLifecycleCallback()) {
                            removed.getLifecycleCallback().onRemoved();
                        }
                        removed.detachLifecycleCallback();
                    }

                    // Send a message to display the next crouton but delay it by the out
                    // animation duration to make sure it finishes
                    sendMessageDelayed(mCrouton, Messages.DISPLAY_CROUTON,
                            mCrouton.getOutAnimation().getDuration());
                }
            });
        }
    }
}

From source file:com.wen.security.http.AsyncHttpResponseHandler.java

/**
 * Helper method to send runnable into local handler loop
 *
 * @param runnable runnable instance, can be null
 *///from w w w  . j  a  va  2  s.  c  o  m
protected void postRunnable(Runnable runnable) {
    boolean missingLooper = null == Looper.myLooper();
    if (missingLooper) {
        Looper.prepare();
    }
    if (null != runnable) {
        handler.post(runnable);
    }
    if (missingLooper) {
        Looper.loop();
    }
}

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   w  w  w  . ja  v a  2 s . c  o 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());
            }
        }
    });
}

From source file:org.restcomm.app.utillib.Reporters.WebReporter.WebReporter.java

public boolean isAuthorized() {
    boolean authorized = false;
    int userId = Global.getUserID(mContext);

    if (mApiKey != null && mApiKey.length() > 10 && userId > 0)
        authorized = true;//from   w ww  .j  a  v a 2  s  .c o m
    // Unless user signed himself out
    SecurePreferences prefs = PreferenceKeys.getSecurePreferences(mContext);
    if (prefs.getBoolean(PreferenceKeys.Miscellaneous.SIGNED_OUT, false) == true)
        authorized = false;

    if (authorized == true && Global.isOnline() && Looper.myLooper() != Looper.getMainLooper()) {
        URL request = RequestServerGet.getURL(mHost, mApiKey, null, "user", null);
        try {
            HttpURLConnection connection = (HttpURLConnection) request.openConnection();
            connection.connect();
            if (connection.getResponseCode() == 401)
                return false;
        } catch (Exception e) {
            LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "isAuthorized", "exception", e);
        }
    }
    return authorized; //  && mApiKey.length() > 10);
}

From source file:com.mirasense.scanditsdk.plugin.SubViewPickerController.java

private void internalRemoveSubviewPicker() {
    if (Looper.myLooper() == null || Looper.myLooper().getThread() != Thread.currentThread()) {
        throw new RuntimeException("must be called on main thread");
    }/*ww w .  ja v a  2s. co m*/
    if (mPickerStateMachine == null) {
        return;
    }
    mPickerStateMachine.setState(PickerStateMachine.STOPPED);
    ViewGroup viewGroup = getPickerParent();
    if (viewGroup != null) {
        viewGroup.removeView(mLayout);
    }
    mLayout = null;
    mPickerStateMachine = null;
}