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.digium.respokesdk.RespokeClient.java

private void getGroupHistoriesError(final GroupHistoriesCompletionListener completionListener,
        final String errorMessage) {
    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override//from   w  w  w. j a v a 2s .co m
        public void run() {
            if (completionListener != null) {
                completionListener.onError(errorMessage);
            }
        }
    });
}

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

private void getGroupHistoryError(final GroupHistoryCompletionListener completionListener,
        final String errorMessage) {
    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override//  w w  w .java2 s  . com
        public void run() {
            if (completionListener != null) {
                completionListener.onError(errorMessage);
            }
        }
    });
}

From source file:com.networking.ApiTestActivity.java

public void checkCacheForCustomClient(View view) {
    String url = "http://www.colorado.edu/conflict/peace/download/peace_problem.ZIP";
    AndroidNetworking.download(url, Utils.getRootDirPath(getApplicationContext()), "file1.zip")
            .setPriority(Priority.HIGH).setTag(this).setOkHttpClient(new OkHttpClient()).build()
            .setAnalyticsListener(new AnalyticsListener() {
                @Override//from  ww w . j a v  a2 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);
                }
            }).setDownloadProgressListener(new DownloadProgressListener() {
                @Override
                public void onProgress(long bytesDownloaded, long totalBytes) {
                    Log.d(TAG, "bytesDownloaded : " + bytesDownloaded + " totalBytes : " + totalBytes);
                    Log.d(TAG, "setDownloadProgressListener isMainThread : "
                            + String.valueOf(Looper.myLooper() == Looper.getMainLooper()));
                }
            }).startDownload(new DownloadListener() {
                @Override
                public void onDownloadComplete() {
                    Log.d(TAG, "File download Completed");
                    Log.d(TAG, "onDownloadComplete 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 an 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.android.mail.ui.AnimatedAdapter.java

@Override
public void notifyDataSetChanged() {
    // This may be a temporary catch for a problem, or we may leave it here.
    // b/9527863/*from  w w w .j  av  a 2s . com*/
    if (Looper.getMainLooper() != Looper.myLooper()) {
        LogUtils.wtf(LOG_TAG, "notifyDataSetChanged() called off the main thread");
    }

    updateSpecialViews();
    super.notifyDataSetChanged();
}

From source file:com.microsoft.rightsmanagement.sampleapp.MsipcTaskFragment.java

/**
 * Update task status.//from w ww .j  a  v  a 2 s.  c om
 * 
 * @param taskStatus the task status
 */
private void updateTaskStatus(final TaskStatus taskStatus) {
    if (taskStatus.mPostToCaller) {
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (mTaskEventCallback != null) {
                    mLatestUnpostedTaskStatus = null;
                    mTaskEventCallback.onMsipcTaskUpdate(taskStatus);
                } else {
                    mLatestUnpostedTaskStatus = taskStatus;
                }
            }
        });
    }
}

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

/**
 *  Attempt to reconnect the client if it is not already trying in another thread
 *///from  ww  w .  j  a va2 s . c  o  m
private void actuallyReconnect() {
    if (((null == signalingChannel) || !signalingChannel.connected) && reconnect) {
        if (connectionInProgress) {
            // The client app must have initiated a connection manually during the timeout period. Try again later
            performReconnect();
        } else {
            Log.d(TAG, "Trying to reconnect...");
            connect(localEndpointID, applicationID, reconnect, presence, appContext,
                    new ConnectCompletionListener() {
                        @Override
                        public void onError(final String errorMessage) {
                            // A REST API call failed. Socket errors are handled in the onError callback
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    Listener listener = listenerReference.get();
                                    if (null != listener) {
                                        listener.onError(RespokeClient.this, errorMessage);
                                    }
                                }
                            });

                            // Try again later
                            performReconnect();
                        }
                    });
        }
    }
}

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

/**
 *  Register for presence updates for the specified endpoint ID. Registration will not occur immediately, 
 *  it will be queued and performed asynchronously. Queuing allows for large numbers of presence 
 *  registration requests to occur in batches, minimizing the number of network transactions (and overall 
 *  time required).//from  w  w  w .  j a v  a2s. c  om
 *
 *  @param endpointID  The ID of the endpoint for which to register for presence updates
 */
private void queuePresenceRegistration(String endpointID) {
    if (null != endpointID) {
        Boolean shouldSpawnRegistrationTask = false;

        synchronized (this) {
            Boolean alreadyRegistered = presenceRegistered.get(endpointID);
            if ((null == alreadyRegistered) || !alreadyRegistered) {
                presenceRegistrationQueue.add(endpointID);

                // If a Runnable to register presence has not already been scheduled, note that one will be shortly
                if (!registrationTaskWaiting) {
                    shouldSpawnRegistrationTask = true;
                    registrationTaskWaiting = true;
                }
            }
        }

        if (shouldSpawnRegistrationTask) {
            // Schedule a Runnable to register presence on the next context switch, which should allow multiple subsequent calls to queuePresenceRegistration to get batched into a single socket transaction for efficiency
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    final HashMap<String, Boolean> endpointIDMap = new HashMap<String, Boolean>();

                    synchronized (this) {
                        // Build a list of the endpointIDs that have been scheduled for registration, and have not already been taken care of by a previous loop of this task
                        while (presenceRegistrationQueue.size() > 0) {
                            String nextEndpointID = presenceRegistrationQueue.remove(0);
                            Boolean alreadyRegistered = presenceRegistered.get(nextEndpointID);
                            if ((null == alreadyRegistered) || !alreadyRegistered) {
                                endpointIDMap.put(nextEndpointID, true);
                            }
                        }

                        // Now that the batch of endpoint IDs to register has been determined, indicate to the client that any new registration calls should schedule a new Runnable
                        registrationTaskWaiting = false;
                    }

                    // Build an array from the map keySet to ensure there are no duplicates in the list
                    final ArrayList<String> endpointIDsToRegister = new ArrayList<String>(
                            endpointIDMap.keySet());

                    if ((endpointIDsToRegister.size() > 0) && isConnected()) {
                        signalingChannel.registerPresence(endpointIDsToRegister,
                                new RespokeSignalingChannel.RegisterPresenceListener() {
                                    @Override
                                    public void onSuccess(JSONArray initialPresenceData) {
                                        // Indicate that registration was successful for each endpoint ID in the list
                                        synchronized (RespokeClient.this) {
                                            for (String eachID : endpointIDsToRegister) {
                                                presenceRegistered.put(eachID, true);
                                            }
                                        }

                                        if (null != initialPresenceData) {
                                            for (int ii = 0; ii < initialPresenceData.length(); ii++) {
                                                try {
                                                    JSONObject eachEndpointData = (JSONObject) initialPresenceData
                                                            .get(ii);
                                                    String dataEndpointID = eachEndpointData
                                                            .getString("endpointId");
                                                    RespokeEndpoint endpoint = getEndpoint(dataEndpointID,
                                                            true);

                                                    if (null != endpoint) {
                                                        JSONObject connectionData = eachEndpointData
                                                                .getJSONObject("connectionStates");
                                                        Iterator<?> keys = connectionData.keys();

                                                        while (keys.hasNext()) {
                                                            String eachConnectionID = (String) keys.next();
                                                            JSONObject presenceDict = connectionData
                                                                    .getJSONObject(eachConnectionID);
                                                            Object newPresence = presenceDict.get("type");
                                                            RespokeConnection connection = endpoint
                                                                    .getConnection(eachConnectionID, false);

                                                            if ((null != connection) && (null != newPresence)) {
                                                                connection.presence = newPresence;
                                                            }
                                                        }
                                                    }
                                                } catch (JSONException e) {
                                                    // Silently skip this problem
                                                }
                                            }
                                        }

                                        for (String eachID : endpointIDsToRegister) {
                                            RespokeEndpoint endpoint = getEndpoint(eachID, true);

                                            if (null != endpoint) {
                                                endpoint.resolvePresence();
                                            }
                                        }
                                    }

                                    @Override
                                    public void onError(final String errorMessage) {
                                        Log.d(TAG, "Error registering presence: " + errorMessage);
                                    }
                                });
                    }
                }
            });
        }
    }
}

From source file:com.networking.OkHttpResponseTestActivity.java

public void checkOkHttpResponse(View view) {

    AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY).addPathParameter("pageNumber", "0")
            .addQueryParameter("limit", "3").setTag(this).setPriority(Priority.LOW).build()
            .setAnalyticsListener(new AnalyticsListener() {
                @Override/*from www . 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);
                }
            }).getAsOkHttpResponse(new OkHttpResponseListener() {
                @Override
                public void onResponse(Response response) {
                    if (response != null) {
                        if (response.isSuccessful()) {
                            Log.d(TAG, "response is successful");
                            try {
                                Log.d(TAG, "response : " + response.body().source().readUtf8());
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        } else {
                            Log.d(TAG, "response is not successful");
                        }
                    } else {
                        Log.d(TAG, "response is null");
                    }
                }

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

    AndroidNetworking.post(ApiEndPoint.BASE_URL + ApiEndPoint.POST_CREATE_AN_USER)
            .addBodyParameter("firstname", "Suman").addBodyParameter("lastname", "Shekhar").setTag(this)
            .setPriority(Priority.LOW).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);
                }
            }).getAsOkHttpResponse(new OkHttpResponseListener() {
                @Override
                public void onResponse(Response response) {
                    if (response != null) {
                        if (response.isSuccessful()) {
                            Log.d(TAG, "response is successful");
                            try {
                                Log.d(TAG, "response : " + response.body().source().readUtf8());
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        } else {
                            Log.d(TAG, "response is not successful");
                        }
                    } else {
                        Log.d(TAG, "response is null");
                    }
                }

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

    AndroidNetworking.upload(ApiEndPoint.BASE_URL + ApiEndPoint.UPLOAD_IMAGE).setPriority(Priority.MEDIUM)
            .addMultipartFile("image",
                    new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "test.png"))
            .setTag(this).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);
                }
            }).setUploadProgressListener(new UploadProgressListener() {
                @Override
                public void onProgress(long bytesUploaded, long totalBytes) {
                    Log.d(TAG, "bytesUploaded : " + bytesUploaded + " totalBytes : " + totalBytes);
                    Log.d(TAG, "setUploadProgressListener isMainThread : "
                            + String.valueOf(Looper.myLooper() == Looper.getMainLooper()));
                }
            }).getAsOkHttpResponse(new OkHttpResponseListener() {
                @Override
                public void onResponse(Response response) {
                    if (response != null) {
                        if (response.isSuccessful()) {
                            Log.d(TAG, "response is successful");
                            try {
                                Log.d(TAG, "response : " + response.body().source().readUtf8());
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        } else {
                            Log.d(TAG, "response is not successful");
                        }
                    } else {
                        Log.d(TAG, "response is null");
                    }
                }

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

From source file:com.onesignal.OneSignal.java

static void runOnUiThread(Runnable action) {
    Handler handler = new Handler(Looper.getMainLooper());
    handler.post(action);
}