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.quarterfull.newsAndroid.NewsReaderListActivity.java

private void UpdateButtonLayoutWithHandler() {
    Handler refresh = new Handler(Looper.getMainLooper());
    refresh.post(new Runnable() {
        public void run() {
            UpdateButtonLayout();//from www . j av a 2 s  .co  m
        }
    });
}

From source file:com.eutectoid.dosomething.picker.PlacePickerFragment.java

private void onSearchTextTimerTriggered() {
    if (hasSearchTextChangedSinceLastQuery) {
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {
            @Override//from   ww  w .  j  av  a2 s  .co  m
            public void run() {
                FacebookException error = null;
                try {
                    loadData(true);
                } catch (FacebookException fe) {
                    error = fe;
                } catch (Exception e) {
                    error = new FacebookException(e);
                } finally {
                    if (error != null) {
                        OnErrorListener onErrorListener = getOnErrorListener();
                        if (onErrorListener != null) {
                            onErrorListener.onError(PlacePickerFragment.this, error);
                        } else {
                            Logger.log(LoggingBehavior.REQUESTS, TAG, "Error loading data : %s", error);
                        }
                    }
                }
            }
        });
    } else {
        // Nothing has changed in 2 seconds. Invalidate and forget about this timer.
        // Next time the user types, we will fire a query immediately again.
        searchTextTimer.cancel();
        searchTextTimer = null;
    }
}

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

/**
 *  Notify the group that a group message was received. 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 endpoint     The endpoint that sent the message
 *  @param timestamp    The message timestamp
 *//*from www .  j a  v  a 2  s .  c  om*/
public void didReceiveMessage(final String message, final RespokeEndpoint endpoint, final Date timestamp) {
    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            Listener listener = listenerReference.get();
            if (null != listener) {
                listener.onGroupMessage(message, endpoint, RespokeGroup.this, timestamp);
            }
        }
    });
}

From source file:com.quarterfull.newsAndroid.NewsReaderListActivity.java

@Subscribe
public void onEvent(SyncFinishedEvent event) {
    Handler refresh = new Handler(Looper.getMainLooper());
    refresh.post(new Runnable() {
        public void run() {
            UpdateButtonLayout();/*from ww  w .  ja va2s  .c  o  m*/
            syncFinishedHandler();
        }
    });
}

From source file:applab.search.client.SynchronizationManager.java

/**
 * Called by our background or timer thread to perform the actual synchronization tasks from a separate thread.
 * //from w  w  w.j a  va2s  .  c o m
 * @throws XmlPullParserException
 */
private void performBackgroundSynchronization() throws XmlPullParserException {
    Boolean setupLooper = true;
    if (this.launchedFromTimer) {
        setupLooper = false;
    }

    if (setupLooper) {
        // we may want to associate UI with this task, so create
        // a looper to setup the message pump (by default, background threads
        // don't have a message pump)

        Looper.prepare();
    }

    try {
        sendInternalMessage(GlobalConstants.KEYWORD_DOWNLOAD_STARTING); // We send this so that the dialog shows up
                                                                        // immediately
        SynchronizationManager.singleton.isSynchronizing = true;

        // First submit pending farmer registrations and get latest registration form
        String serverUrl = Settings.getServerUrl();
        FarmerRegistrationController farmerRegController = new FarmerRegistrationController();
        farmerRegController.postFarmerRegistrationData(serverUrl);
        farmerRegController.fetchAndStoreRegistrationForm(serverUrl);

        // Then submit pending usage logs and incomplete searches
        InboxAdapter inboxAdapter = new InboxAdapter(ApplabActivity.getGlobalContext());
        inboxAdapter.open();
        submitPendingUsageLogs(inboxAdapter);

        inboxAdapter.close();

        // Finally update keywords
        updateKeywords();
    } catch (Exception e) {
        e.printStackTrace();
        completeSynchronization();
    }

    if (setupLooper) {
        // TODO: Looper.loop is problematic here. This should be restructured
        Looper.loop();
        Looper looper = Looper.getMainLooper();
        looper.quit();
    }
}

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

/**
 *  Join a list of Groups and begin keeping track of them.
 *
 *  @param groupIDList         An array of IDs of the groups to join
 *  @param completionListener  A listener to receive a notification of the success or failure of the asynchronous operation
 *///from w ww. j a  v a  2  s . c  om
public void joinGroups(final ArrayList<String> groupIDList,
        final JoinGroupCompletionListener completionListener) {
    if (isConnected()) {
        if ((groupIDList != null) && (groupIDList.size() > 0)) {
            String urlEndpoint = "/v1/groups";

            JSONArray groupList = new JSONArray(groupIDList);
            JSONObject data = new JSONObject();
            try {
                data.put("groups", groupList);

                signalingChannel.sendRESTMessage("post", urlEndpoint, data,
                        new RespokeSignalingChannel.RESTListener() {
                            @Override
                            public void onSuccess(Object response) {
                                final ArrayList<RespokeGroup> newGroupList = new ArrayList<RespokeGroup>();
                                for (String eachGroupID : groupIDList) {
                                    RespokeGroup newGroup = new RespokeGroup(eachGroupID, signalingChannel,
                                            RespokeClient.this);
                                    groups.put(eachGroupID, newGroup);
                                    newGroupList.add(newGroup);
                                }

                                new Handler(Looper.getMainLooper()).post(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (null != completionListener) {
                                            completionListener.onSuccess(newGroupList);
                                        }
                                    }
                                });
                            }

                            @Override
                            public void onError(final String errorMessage) {
                                postJoinGroupMembersError(completionListener, errorMessage);
                            }
                        });
            } catch (JSONException e) {
                postJoinGroupMembersError(completionListener, "Error encoding group list to json");
            }
        } else {
            postJoinGroupMembersError(completionListener, "At least one group must be specified");
        }
    } else {
        postJoinGroupMembersError(completionListener,
                "Can't complete request when not connected. Please reconnect!");
    }
}

From source file:com.rxsampleapp.RxApiTestActivity.java

public void createAnUserJSONObject(View view) {
    JSONObject jsonObject = new JSONObject();
    try {//ww w .  j  a v a2 s  . c  o  m
        jsonObject.put("firstname", "Rohit");
        jsonObject.put("lastname", "Kumar");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    RxAndroidNetworking.post(ApiEndPoint.BASE_URL + ApiEndPoint.POST_CREATE_AN_USER)
            .addJSONObjectBody(jsonObject).build().setAnalyticsListener(new AnalyticsListener() {
                @Override
                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);
                }
            }).getJSONObjectObservable().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<JSONObject>() {
                @Override
                public void onCompleted() {
                    Log.d(TAG, "onComplete Detail : createAnUserJSONObject completed");
                }

                @Override
                public void onError(Throwable e) {
                    if (e instanceof ANError) {
                        ANError anError = (ANError) e;
                        if (anError.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 : " + anError.getErrorCode());
                            Log.d(TAG, "onError errorBody : " + anError.getErrorBody());
                            Log.d(TAG, "onError errorDetail : " + anError.getErrorDetail());
                        } else {
                            // error.getErrorDetail() : connectionError, parseError, requestCancelledError
                            Log.d(TAG, "onError errorDetail : " + anError.getErrorDetail());
                        }
                    } else {
                        Log.d(TAG, "onError errorMessage : " + e.getMessage());
                    }
                }

                @Override
                public void onNext(JSONObject response) {
                    Log.d(TAG, "onResponse object : " + response.toString());
                    Log.d(TAG, "onResponse isMainThread : "
                            + String.valueOf(Looper.myLooper() == Looper.getMainLooper()));
                }
            });
}

From source file:com.wishlist.Wishlist.java

public void fetchCurrentLocation() {
    new Thread() {
        public void run() {
            Looper.prepare();//from   www .j a v a2s. com
            mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            MyLocationListener locationListener = new MyLocationListener();
            Criteria criteria = new Criteria();
            criteria.setAccuracy(Criteria.ACCURACY_COARSE);
            String provider = mLocationManager.getBestProvider(criteria, true);
            if (provider != null && mLocationManager.isProviderEnabled(provider)) {
                mLocationManager.requestLocationUpdates(provider, 1, 0, locationListener,
                        Looper.getMainLooper());
            } else {
                showToast("Please turn on handset's GPS");
            }
            Looper.loop();
        }
    }.start();
}

From source file:com.google.android.exoplayer2.ext.mediasession.MediaSessionConnector.java

/**
 * Creates an instance. Must be called on the same thread that is used to construct the player
 * instances passed to {@link #setPlayer(Player, PlaybackPreparer, CustomActionProvider...)}.
 *
 * @param mediaSession The {@link MediaSessionCompat} to connect to.
 * @param playbackController A {@link PlaybackController} for handling playback actions, or
 *     {@code null} if the connector should handle playback actions directly.
 * @param doMaintainMetadata Whether the connector should maintain the metadata of the session. If
 *     {@code false}, you need to maintain the metadata of the media session yourself (provide at
 *     least the duration to allow clients to show a progress bar).
 *///from w w  w.ja v  a2s . co m
public MediaSessionConnector(MediaSessionCompat mediaSession, PlaybackController playbackController,
        boolean doMaintainMetadata) {
    this.mediaSession = mediaSession;
    this.playbackController = playbackController != null ? playbackController : new DefaultPlaybackController();
    this.handler = new Handler(Looper.myLooper() != null ? Looper.myLooper() : Looper.getMainLooper());
    this.doMaintainMetadata = doMaintainMetadata;
    mediaSession.setFlags(BASE_MEDIA_SESSION_FLAGS);
    mediaController = mediaSession.getController();
    mediaSessionCallback = new MediaSessionCallback();
    exoPlayerEventListener = new ExoPlayerEventListener();
    customActionMap = Collections.emptyMap();
    commandMap = new HashMap<>();
    registerCommandReceiver(playbackController);
}

From source file:com.appsimobile.appsii.module.weather.WeatherLoadingService.java

@Nullable
@RequiresPermission(anyOf = { ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION })
private Location requestLocationInfoBlocking() throws InterruptedException {

    List<String> providers = mLocationManager.getAllProviders();

    if (!providers.contains(LocationManager.NETWORK_PROVIDER))
        return null;
    if (!mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
        return null;

    SimpleLocationListener listener = new SimpleLocationListener(mLocationManager);

    mLocationManager.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, listener, Looper.getMainLooper());

    Location result = listener.waitForResult();
    if (result == null) {
        result = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    }/* ww w  .  j a  va2  s. co  m*/
    if (BuildConfig.DEBUG)
        Log.d("WeatherLoadingService", "location: " + result);
    return result;
}