Example usage for android.os Looper getMainLooper

List of usage examples for android.os Looper getMainLooper

Introduction

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

Prototype

public static Looper getMainLooper() 

Source Link

Document

Returns the application's main looper, which lives in the main thread of the application.

Usage

From source file:com.owncloud.android.providers.UsersAndGroupsSearchProvider.java

/**
 * Show error message//from  www .  java2s  .  co  m
 *
 * @param result    Result with the failure information.
 */
public void showErrorMessage(final RemoteOperationResult result) {
    Handler handler = new Handler(Looper.getMainLooper());
    handler.post(new Runnable() {
        @Override
        public void run() {
            // The Toast must be shown in the main thread to grant that will be hidden correctly; otherwise
            // the thread may die before, an exception will occur, and the message will be left on the screen
            // until the app dies
            Toast.makeText(getContext().getApplicationContext(),
                    ErrorMessageAdapter.getErrorCauseMessage(result, null, getContext().getResources()),
                    Toast.LENGTH_SHORT).show();
        }
    });
}

From source file:com.hybris.mobile.lib.http.PersistenceHelper.java

/**
 * Execute the request then convert the results into the generic T response
 *
 * @param responseReceiver    Response callback result
 * @param dataConverterHelper Helper to convert the result into a POJO
 * @param getCachedResult     Indicator to use cache or not * @param requestId Identifier for the call
 * @param url                 Url to call
 * @param parameters          Call parameters
 * @param headers             Call parameters headers
 * @param httpMethod          Http method: GET, POST, PUT, DELETE
 * @return Generic Type response/*from   w w w  .  j a va2s. co m*/
 */
public <T, Z> boolean execute(final ResponseCallback<T, Z> responseReceiver,
        final DataConverter.Helper<T, Z> dataConverterHelper, boolean getCachedResult, final String requestId,
        String url, Map<String, Object> parameters, Map<String, String> headers, String httpMethod) {

    DataResponseCallBack dataResponseCallBack = new DataResponseCallBack() {

        @Override
        public void onResponse(DataResponse dataResponse) {

            try {
                final Response<T> response;

                // Conversion with the DataConverter
                if (StringUtils.isBlank(dataConverterHelper.getPropertyName())) {
                    response = Response.createResponse(mDataConverter
                            .convertFrom(dataConverterHelper.getClassName(), dataResponse.getData()), requestId,
                            dataResponse.isSync());
                } else {
                    response = Response.createResponse(
                            mDataConverter.convertFrom(dataConverterHelper.getClassName(),
                                    dataResponse.getData(), dataConverterHelper.getPropertyName()),
                            requestId, dataResponse.isSync());
                }

                if (mUiRelated) {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            responseReceiver.onResponse(response);
                        }
                    });
                } else {
                    responseReceiver.onResponse(response);
                }

            }
            // Conversion error, we return the response with the error message
            catch (DataConverterException e) {
                handleGenericError(responseReceiver, dataResponse, dataConverterHelper, requestId);
            }
        }

        @Override
        public void onError(final DataResponse dataResponse) {

            try {
                final Response<Z> response = Response.createResponse(mDataConverter
                        .convertFrom(dataConverterHelper.getErrorClassName(), dataResponse.getData()),
                        requestId, dataResponse.isSync());

                if (mUiRelated) {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            responseReceiver.onError(response);
                        }
                    });
                } else {
                    responseReceiver.onError(response);
                }

            }
            // Conversion error, we return the response with the error message
            catch (DataConverterException e) {
                handleGenericError(responseReceiver, dataResponse, dataConverterHelper, requestId);
            }

        }
    };

    return executeRequest(dataResponseCallBack, getCachedResult, requestId, url, parameters, headers,
            httpMethod);

}

From source file:com.money.manager.ex.assetallocation.editor.AssetAllocationEditorActivity.java

private LoaderManager.LoaderCallbacks<AssetClass> setUpLoaderCallbacks() {
    return new LoaderManager.LoaderCallbacks<AssetClass>() {
        @Override/*from   w  w w  .j av  a 2  s . c  o  m*/
        public Loader<AssetClass> onCreateLoader(int id, Bundle args) {
            return new AssetAllocationLoader(AssetAllocationEditorActivity.this);
        }

        @Override
        public void onLoadFinished(Loader<AssetClass> loader, final AssetClass data) {
            AssetAllocationEditorActivity.this.assetAllocation = data;

            // Create handler to perform showing of fragment(s).
            Handler h = new Handler(Looper.getMainLooper());
            Runnable runnable = new Runnable() {
                public void run() {
                    showAssetClass(data);
                }
            };

            // show the data
            AssetAllocationContentsFragment fragment = (AssetAllocationContentsFragment) UIHelpers
                    .getVisibleFragment(AssetAllocationEditorActivity.this);
            // If there are no other fragments, create the initial view.
            if (fragment == null) {
                h.post(runnable);
            } else {
                // Otherwise, find the fragment and update the data.
                //                    refreshDataInFragment(data);
                refreshDataInFragments(data);
            }
        }

        @Override
        public void onLoaderReset(Loader<AssetClass> loader) {
            // adapter swap cursor?
        }
    };
}

From source file:com.appnexus.opensdk.mediatednativead.InMobiNativeAdResponse.java

@Override
public void destroy() {
    Handler handler = new Handler(Looper.getMainLooper());
    handler.removeCallbacks(runnable);
    handler.post(runnable);
}

From source file:com.jefftharris.passwdsafe.sync.onedrive.OnedriveProvider.java

/**
 * Get a OneDrive service for the client
 *///www .ja  v a 2  s .c o m
public IOneDriveService acquireOnedriveService() throws Exception {
    if (Looper.myLooper() == Looper.getMainLooper()) {
        throw new Exception("Can't invoke getOnedriveService in ui thread");
    }

    if (!itsServiceLock.tryLock(15, TimeUnit.MINUTES)) {
        throw new Exception("Timeout waiting for OneDrive service");
    }

    if (itsAuthClient.getSession().isExpired()) {
        PasswdSafeUtil.dbginfo(TAG, "sync refreshing auth token");
        itsAuthClient.getSession().refresh();
    }

    ODConnection conn = new ODConnection(itsAuthClient);
    conn.setVerboseLogcatOutput(false);
    return conn.getService();
}

From source file:com.digium.respokesdk.RespokeEndpoint.java

/**
 *  Process a received message. This is used internally to the SDK and should not be called directly by your client application.
 *
 *  @param message The body of the message
 *  @param timestamp The message timestamp
 *//*from  w ww.ja v a 2  s . c om*/
public void didReceiveMessage(final String message, final Date timestamp) {
    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            if (null != listenerReference) {
                Listener listener = listenerReference.get();
                if (null != listener) {
                    listener.onMessage(message, timestamp, RespokeEndpoint.this, false);
                }
            }
        }
    });
}

From source file:android.support.text.emoji.EmojiCompat.java

/**
 * Private constructor for singleton instance.
 *
 * @see #init(Config)/*www. j  av  a 2 s  .c o  m*/
 */
private EmojiCompat(@NonNull final Config config) {
    mInitLock = new ReentrantReadWriteLock();
    mReplaceAll = config.mReplaceAll;
    mEmojiSpanIndicatorEnabled = config.mEmojiSpanIndicatorEnabled;
    mEmojiSpanIndicatorColor = config.mEmojiSpanIndicatorColor;
    mMetadataLoader = config.mMetadataLoader;
    mMainHandler = new Handler(Looper.getMainLooper());
    mInitCallbacks = new ArraySet<>();
    if (config.mInitCallbacks != null && !config.mInitCallbacks.isEmpty()) {
        mInitCallbacks.addAll(config.mInitCallbacks);
    }
    mHelper = Build.VERSION.SDK_INT < 19 ? new CompatInternal(this) : new CompatInternal19(this);
    loadMetadata();
}

From source file:com.actinarium.rhythm.control.RhythmNotificationService.java

private void handleNextGroup() {
    Application application = getApplication();
    if (application instanceof RhythmControl.Host) {
        final RhythmControl rhythmControl = ((RhythmControl.Host) application).getRhythmControl();
        Handler handler = new Handler(Looper.getMainLooper());
        // Not using anonymous classes here to avoid leaking context
        handler.post(new NextGroupRunnable(rhythmControl));
    }//ww  w  .j a  va  2 s. com
}

From source file:com.example.scrumptious.PickerActivity.java

@Override
protected void onStart() {
    super.onStart();
    if (FRIEND_PICKER.equals(getIntent().getData())) {
        try {/*w ww  .  ja v a2 s  .  c  o m*/
            friendPickerFragment.loadData(false);
        } catch (Exception ex) {
            onError(ex);
        }
    } else if (PLACE_PICKER.equals(getIntent().getData())) {
        try {
            Location location = null;
            Criteria criteria = new Criteria();
            LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            String bestProvider = locationManager.getBestProvider(criteria, false);
            if (bestProvider != null) {
                location = locationManager.getLastKnownLocation(bestProvider);
                if (locationManager.isProviderEnabled(bestProvider) && locationListener == null) {
                    locationListener = new LocationListener() {
                        @Override
                        public void onLocationChanged(Location location) {
                            boolean updateLocation = true;
                            Location prevLocation = placePickerFragment.getLocation();
                            if (prevLocation != null) {
                                updateLocation = location.distanceTo(prevLocation) >= LOCATION_CHANGE_THRESHOLD;
                            }
                            if (updateLocation) {
                                placePickerFragment.setLocation(location);
                                placePickerFragment.loadData(true);
                            }
                        }

                        @Override
                        public void onStatusChanged(String s, int i, Bundle bundle) {
                        }

                        @Override
                        public void onProviderEnabled(String s) {
                        }

                        @Override
                        public void onProviderDisabled(String s) {
                        }
                    };
                    locationManager.requestLocationUpdates(bestProvider, 1, LOCATION_CHANGE_THRESHOLD,
                            locationListener, Looper.getMainLooper());
                }
            }
            if (location != null) {
                placePickerFragment.setLocation(location);
                placePickerFragment.setRadiusInMeters(SEARCH_RADIUS_METERS);
                placePickerFragment.setSearchText(SEARCH_TEXT);
                placePickerFragment.setResultsLimit(SEARCH_RESULT_LIMIT);
                placePickerFragment.loadData(false);
            }
        } catch (Exception ex) {
            onError(ex);
        }
    }
}

From source file:com.trk.aboutme.facebook.Settings.java

/**
 * Manually publish install attribution to the Facebook graph.  Internally handles tracking repeat calls to prevent
 * multiple installs being published to the graph.
 * @param context the current Context/* w w  w.  j av a  2 s  .  com*/
 * @param applicationId the fb application being published.
 * @param callback a callback to invoke with a Response object, carrying the server response, or an error.
 */
public static void publishInstallAsync(final Context context, final String applicationId,
        final Request.Callback callback) {
    // grab the application context ahead of time, since we will return to the caller immediately.
    final Context applicationContext = context.getApplicationContext();
    Settings.getExecutor().execute(new Runnable() {
        @Override
        public void run() {
            final Response response = Settings.publishInstallAndWaitForResponse(applicationContext,
                    applicationId);
            if (callback != null) {
                // invoke the callback on the main thread.
                Handler handler = new Handler(Looper.getMainLooper());
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onCompleted(response);
                    }
                });
            }
        }
    });
}