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.amytech.android.library.utils.asynchttp.AsyncHttpClient.java

/**
 * Cancels any pending (or potentially active) requests associated with the
 * passed Context.//from  ww w  . j  a  v a 2s.  co m
 * <p>
 * &nbsp;
 * </p>
 * <b>Note:</b> This will only affect requests which were created with a
 * non-null android Context. This method is intended to be used in the
 * onDestroy method of your android activities to destroy all requests which
 * are no longer required.
 *
 * @param context
 *            the android Context instance associated to the request.
 * @param mayInterruptIfRunning
 *            specifies if active requests should be cancelled along with
 *            pending requests.
 */
public void cancelRequests(final Context context, final boolean mayInterruptIfRunning) {
    if (context == null) {
        Log.e(LOG_TAG, "Passed null Context to cancelRequests");
        return;
    }

    final List<RequestHandle> requestList = requestMap.get(context);
    requestMap.remove(context);

    if (Looper.myLooper() == Looper.getMainLooper()) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                cancelRequests(requestList, mayInterruptIfRunning);
            }
        };
        threadPool.submit(runnable);
    } else {
        cancelRequests(requestList, mayInterruptIfRunning);
    }
}

From source file:org.cryptsecure.Utility.java

/**
 * Update tile for OpenStreetMap./*  www . j  a  v  a2  s .c o m*/
 * 
 * @param context
 *            the context
 * @param image
 *            the image
 * @param zoom
 *            the zoom
 * @param latitude
 *            the latitude
 * @param longitude
 *            the longitude
 */
public static void updateTile(Context context, final ImageView image, int zoom, double latitude,
        double longitude) {
    final String url = "http://tile.openstreetmap.org/" + getTileNumber(latitude, longitude, zoom) + ".png";

    (new Thread() {
        public void run() {
            try {
                final InputStream is = (InputStream) new URL(url).getContent();
                final Bitmap bm = BitmapFactory.decodeStream(is);
                if (image != null) {
                    final Handler mUIHandler = new Handler(Looper.getMainLooper());
                    mUIHandler.post(new Thread() {
                        @Override
                        public void run() {
                            super.run();
                            image.setImageBitmap(bm);
                        }
                    });

                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }).start();
}

From source file:cn.com.loopj.android.http.AsyncHttpClient.java

/**
 * Cancels any pending (or potentially active) requests associated with the passed Context.
 * <p>&nbsp;</p> <b>Note:</b> This will only affect requests which were created with a non-null
 * android Context. This method is intended to be used in the onDestroy method of your android
 * activities to destroy all requests which are no longer required.
 *
 * @param context               the android Context instance associated to the request.
 * @param mayInterruptIfRunning specifies if active requests should be cancelled along with
 *                              pending requests.
 *//* w w  w.  jav  a2  s.  c o m*/
public void cancelRequests(final Context context, final boolean mayInterruptIfRunning) {
    if (context == null) {
        log.e(LOG_TAG, "Passed null Context to cancelRequests");
        return;
    }

    final List<RequestHandle> requestList = requestMap.get(context);
    requestMap.remove(context);

    if (Looper.myLooper() == Looper.getMainLooper()) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                cancelRequests(requestList, mayInterruptIfRunning);
            }
        };
        threadPool.submit(runnable);
    } else {
        cancelRequests(requestList, mayInterruptIfRunning);
    }
}

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

/**
 * Retrieve the history of messages that have been persisted for a specific group. Only those
 * messages that have been marked to be persisted when sent will show up in the history.
 *
 * @param groupId The groups to pull history for
 * @param maxMessages The maximum number of messages per group to pull. Must be &gt;= 1
 * @param before Limit messages to those with a timestamp before this value
 * @param completionListener The callback called when this async operation has completed
 *//*w w w  . j a  va  2s  . c o m*/
public void getGroupHistory(final String groupId, final Integer maxMessages, final Date before,
        final GroupHistoryCompletionListener completionListener) {
    if (!isConnected()) {
        getGroupHistoryError(completionListener,
                "Can't complete request when not connected, " + "Please reconnect!");
        return;
    }

    if ((maxMessages == null) || (maxMessages < 1)) {
        getGroupHistoryError(completionListener, "maxMessages must be at least 1");
        return;
    }

    if ((groupId == null) || groupId.length() == 0) {
        getGroupHistoryError(completionListener, "groupId cannot be blank");
        return;
    }

    Uri.Builder builder = new Uri.Builder();
    builder.appendQueryParameter("limit", maxMessages.toString());

    if (before != null) {
        builder.appendQueryParameter("before", Long.toString(before.getTime()));
    }

    String urlEndpoint = String.format("/v1/groups/%s/history%s", groupId, builder.build().toString());
    signalingChannel.sendRESTMessage("get", urlEndpoint, null, new RespokeSignalingChannel.RESTListener() {
        @Override
        public void onSuccess(Object response) {
            if (!(response instanceof JSONArray)) {
                getGroupHistoryError(completionListener, "Invalid response from server");
                return;
            }

            final JSONArray json = (JSONArray) response;
            final ArrayList<RespokeGroupMessage> results = new ArrayList<>(json.length());

            try {
                for (int i = 0; i < json.length(); i++) {
                    final JSONObject jsonMessage = json.getJSONObject(i);
                    final RespokeGroupMessage message = buildGroupMessage(jsonMessage);
                    results.add(message);
                }
            } catch (JSONException e) {
                getGroupHistoryError(completionListener, "Error parsing JSON response");
                return;
            }

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

        @Override
        public void onError(final String errorMessage) {
            getGroupHistoryError(completionListener, errorMessage);
        }
    });
}

From source file:android.support.v7.media.MediaRouter.java

/**
 * Ensures that calls into the media router are on the correct thread.
 * It pays to be a little paranoid when global state invariants are at risk.
 *///  ww w .ja v a 2s .co m
static void checkCallingThread() {
    if (Looper.myLooper() != Looper.getMainLooper()) {
        throw new IllegalStateException(
                "The media router service must only be " + "accessed on the application's main thread.");
    }
}

From source file:com.vuze.android.remote.SessionInfo.java

public void initRefreshHandler() {
    if (AndroidUtils.DEBUG) {
        Log.d(TAG, "initRefreshHandler");
    }//from   w  w w  .  jav a  2s .  c o m
    if (handler != null) {
        return;
    }
    long interval = remoteProfile.calcUpdateInterval();
    if (AndroidUtils.DEBUG) {
        Log.d(TAG, "Handler fires every " + interval);
    }
    if (interval <= 0) {
        cancelRefreshHandler();
        return;
    }
    handler = new Handler(Looper.getMainLooper());
    Runnable handlerRunnable = new Runnable() {
        public void run() {
            if (remoteProfile == null) {
                if (AndroidUtils.DEBUG) {
                    Log.d(TAG, "Handler ignored: No remote profile");
                }
                return;
            }

            long interval = remoteProfile.calcUpdateInterval();
            if (interval <= 0) {
                if (AndroidUtils.DEBUG) {
                    Log.d(TAG, "Handler ignored: update interval " + interval);
                }
                cancelRefreshHandler();
                return;
            }

            if (isActivityVisible()) {
                if (AndroidUtils.DEBUG) {
                    Log.d(TAG, "Fire Handler");
                }
                triggerRefresh(true);

                for (RefreshTriggerListener l : refreshTriggerListeners) {
                    l.triggerRefresh();
                }
            }

            if (AndroidUtils.DEBUG) {
                Log.d(TAG, "Handler fires in " + interval);
            }
            handler.postDelayed(this, interval * 1000);
        }
    };
    handler.postDelayed(handlerRunnable, interval * 1000);
}

From source file:com.networking.ApiTestActivity.java

public void setMaxAgeCacheControl(View view) {
    AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY).addPathParameter("pageNumber", "0")
            .addQueryParameter("limit", "3").setTag(this).setPriority(Priority.LOW)
            .setMaxAgeCacheControl(0, TimeUnit.SECONDS).build().setAnalyticsListener(new AnalyticsListener() {
                @Override/*from ww  w. j a 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);
                }
            }).getAsJSONArray(new JSONArrayRequestListener() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d(TAG, "onResponse array : " + 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:com.networking.OkHttpResponseTestActivity.java

public void setMaxStaleCacheControl(View view) {
    AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY).addPathParameter("pageNumber", "0")
            .addQueryParameter("limit", "3").setTag(this).setPriority(Priority.LOW)
            .setMaxStaleCacheControl(365, TimeUnit.SECONDS).build()
            .setAnalyticsListener(new AnalyticsListener() {
                @Override/*  w ww  .  j  ava  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);
                }
            }).getAsOkHttpResponseAndJSONArray(new OkHttpResponseAndJSONArrayRequestListener() {
                @Override
                public void onResponse(Response okHttpResponse, JSONArray response) {
                    Log.d(TAG, "onResponse object : " + response.toString());
                    Log.d(TAG, "onResponse isMainThread : "
                            + String.valueOf(Looper.myLooper() == Looper.getMainLooper()));
                    if (okHttpResponse.isSuccessful()) {
                        Log.d(TAG, "onResponse success headers : " + okHttpResponse.headers().toString());
                    } else {
                        Log.d(TAG, "onResponse not success headers : " + okHttpResponse.headers().toString());
                    }
                }

                @Override
                public void onError(ANError anError) {
                    Utils.logError(TAG, anError);
                }
            });
}

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

private void actuallyAddDirectConnection() {
    if ((null != directConnection) && (directConnection.isActive())) {
        // There is already an active direct connection, so ignore this
    } else {/*from   w  w  w . j a  va 2  s . c  om*/
        directConnection = new RespokeDirectConnection(this);
        endpoint.setDirectConnection(directConnection);

        new Handler(Looper.getMainLooper()).post(new Runnable() {
            public void run() {
                if (isActive() && (null != listenerReference)) {
                    Listener listener = listenerReference.get();
                    if (null != listener) {
                        listener.directConnectionAvailable(directConnection, endpoint);
                    }
                }
            }
        });

        if ((null != directConnection) && !caller && (null != signalingChannel)) {
            RespokeSignalingChannel.Listener signalingChannelListener = signalingChannel.GetListener();
            if (null != signalingChannelListener) {
                // Inform the client that a remote endpoint is attempting to open a direct connection
                signalingChannelListener.directConnectionAvailable(directConnection, endpoint);
            }
        }
    }
}

From source file:com.networking.ApiTestActivity.java

public void setMaxStaleCacheControl(View view) {
    AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY).addPathParameter("pageNumber", "0")
            .addQueryParameter("limit", "3").setTag(this).setPriority(Priority.LOW)
            .setMaxStaleCacheControl(365, TimeUnit.SECONDS).build()
            .setAnalyticsListener(new AnalyticsListener() {
                @Override//from w ww .java  2 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);
                }
            }).getAsJSONArray(new JSONArrayRequestListener() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d(TAG, "onResponse array : " + 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());
                    }
                }
            });
}