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.amazonaws.mobileconnectors.iot.AWSIotMqttManager.java

/**
 * Publish messages from the message queue.
 * Called to handle publishing messages accumulated in the message queue when the client was unable to publish.
 *//*w w  w  .  ja v  a2 s . c  o m*/
void publishMessagesFromQueue() {
    if (connectionState == MqttManagerConnectionState.Connected && mqttMessageQueue != null
            && !mqttMessageQueue.isEmpty()) {
        final AWSIotMqttQueueMessage message = mqttMessageQueue.remove(0);
        if (message != null) {
            try {
                if (message.getUserData() != null && message.getUserData().getUserCallback() != null) {
                    // this queued message has a callback, publish passing the user data
                    mqttClient.publish(message.getTopic(), message.getMessage(), message.getQos().asInt(),
                            false, message.getUserData(), null);
                } else {
                    // this queued message does not have a callback
                    mqttClient.publish(message.getTopic(), message.getMessage(), message.getQos().asInt(),
                            false);
                }
            } catch (final MqttException e) {
                // Call this message a failure.  It is possible that this is due to a
                // connection issue (we are in this path because the connection dropped),
                // however there are also exceptions inherent to the message (valid topic),
                // such that publishing this message would never succeed.  It is safer to
                // remove the message from the queue and notify failure than to block
                // the queue indefinitely.
                userPublishCallback(message.getUserData().getUserCallback(),
                        AWSIotMqttMessageDeliveryCallback.MessageDeliveryStatus.Fail,
                        message.getUserData().getUserData());
            }
        }

        (new Handler(Looper.getMainLooper())).postDelayed(new Runnable() {
            @Override
            public void run() {
                if (!mqttMessageQueue.isEmpty()) {
                    if (connectionState == MqttManagerConnectionState.Connected) {
                        publishMessagesFromQueue();
                    }
                }
            }
        }, drainingInterval);
    }
}

From source file:com.networking.OkHttpResponseTestActivity.java

public void checkSynchronousCall(View view) {
    new Thread(new Runnable() {
        @Override/*  ww  w .  j  a v a2 s  . c  o  m*/
        public void run() {

            String url = "http://www.colorado.edu/conflict/peace/download/peace_problem.ZIP";
            ANRequest requestOne = AndroidNetworking
                    .download(url, Utils.getRootDirPath(getApplicationContext()), "file1.zip")
                    .setPriority(Priority.HIGH).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);
                        }
                    }).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()));

                        }
                    });
            ANResponse<String> responseOne = requestOne.executeForDownload();

            if (responseOne.isSuccess()) {
                Log.d(TAG, "checkSynchronousCall : download success");
                Log.d(TAG, "checkSynchronousCall : download result " + responseOne.getResult());
                Response response = responseOne.getOkHttpResponse();
                Log.d(TAG, "checkSynchronousCall : headers : " + response.headers().toString());
            } else {
                Log.d(TAG, "checkSynchronousCall : download failed");
                Utils.logError(TAG, responseOne.getError());
            }

            ANRequest requestTwo = 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
                        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);
                        }
                    });
            ANResponse<List<User>> responseTwo = requestTwo.executeForParsed(new TypeToken<List<User>>() {
            });

            if (responseTwo.isSuccess()) {
                Log.d(TAG, "checkSynchronousCall : response success");
                List<User> users = responseTwo.getResult();
                Log.d(TAG, "userList size : " + users.size());
                for (User user : users) {
                    Log.d(TAG, "id : " + user.id);
                    Log.d(TAG, "firstname : " + user.firstname);
                    Log.d(TAG, "lastname : " + user.lastname);
                }
                Response response = responseTwo.getOkHttpResponse();
                Log.d(TAG, "checkSynchronousCall : headers : " + response.headers().toString());
            } else {
                Log.d(TAG, "checkSynchronousCall : response failed");
                Utils.logError(TAG, responseTwo.getError());
            }

            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("firstname", "Rohit");
                jsonObject.put("lastname", "Kumar");
            } catch (JSONException e) {
                e.printStackTrace();
            }

            ANRequest requestThree = AndroidNetworking
                    .post(ApiEndPoint.BASE_URL + ApiEndPoint.POST_CREATE_AN_USER).addJSONObjectBody(jsonObject)
                    .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);
                        }
                    });
            ANResponse<JSONObject> responseThree = requestThree.executeForJSONObject();

            if (responseThree.isSuccess()) {
                Log.d(TAG, "checkSynchronousCall : jsonObjectANResponse success");
                JSONObject jsonObjectFinal = responseThree.getResult();
                Log.d(TAG, "checkSynchronousCall : jsonObjectANResponse result " + jsonObjectFinal.toString());
                Response response = responseThree.getOkHttpResponse();
                Log.d(TAG, "checkSynchronousCall : headers : " + response.headers().toString());
            } else {
                Log.d(TAG, "checkSynchronousCall : jsonObjectANResponse failed");
                Utils.logError(TAG, responseThree.getError());
            }

            ANRequest requestFour = 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
                        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);
                        }
                    });
            ANResponse<Response> responseFour = requestFour.executeForOkHttpResponse();

            if (responseFour.isSuccess()) {
                Log.d(TAG, "checkSynchronousCall : okHttpResponse success");
                Response okHttpResponse = responseFour.getResult();
                if (okHttpResponse != null) {
                    if (okHttpResponse.isSuccessful()) {
                        Log.d(TAG, "response is successful");
                        try {
                            Log.d(TAG, "response : " + okHttpResponse.body().source().readUtf8());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } else {
                        Log.d(TAG, "response is not successful");
                    }
                } else {
                    Log.d(TAG, "response is null");
                }
            } else {
                Log.d(TAG, "checkSynchronousCall : okHttpResponse failed");
                Utils.logError(TAG, responseFour.getError());
            }
        }
    }).start();
}

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

private void postErrorToListener(final String errorMessage) {
    // All listener methods should be called from the UI thread
    new Handler(Looper.getMainLooper()).post(new Runnable() {
        public void run() {
            if ((isActive()) && (null != listenerReference)) {
                Listener listener = listenerReference.get();
                if (null != listener) {
                    listener.onError(errorMessage, RespokeCall.this);
                }//from www  . j a  v a 2 s.co m
            }
        }
    });
}

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

public void onConnect(RespokeSignalingChannel sender, String endpointID, String connectionID) {
    connectionInProgress = false;//from  ww  w  .  j  a  v a2 s. c  o m
    reconnectCount = 0;
    localEndpointID = endpointID;
    localConnectionID = connectionID;

    Respoke.sharedInstance().clientConnected(this);

    // Try to set the presence to the initial or last set state
    setPresence(presence, new Respoke.TaskCompletionListener() {
        @Override
        public void onSuccess() {
            // do nothing
        }

        @Override
        public void onError(String errorMessage) {
            // do nothing
        }
    });

    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            Listener listener = listenerReference.get();
            if (null != listener) {
                listener.onConnect(RespokeClient.this);
            }
        }
    });
}

From source file:com.popdeem.sdk.uikit.activity.PDUIClaimActivity.java

private void performClaimReward(final String message, final String encodedImage, final boolean fromInstagram,
        final boolean fromTwitter, final Boolean fromFacebook) {
    final ProgressBar progressBar = (ProgressBar) findViewById(R.id.pd_progress_bar);
    progressBar.setVisibility(View.VISIBLE);

    final Button shareButton = (Button) findViewById(R.id.pd_claim_share_button);
    shareButton.setEnabled(false);//  w ww. j a  va 2  s.c  om
    shareButton.animate().alpha(0.5f);
    shareButton.setVisibility(View.GONE);

    claiming = true;
    int postTime = 1;
    if (fromFacebook) {
        postTime = 3000;
    }

    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            String twitterToken = null;
            String twitterSecret = null;
            if (mTwitterSwitch.isChecked() && PDSocialUtils.isTwitterLoggedIn()
                    && TwitterCore.getInstance().getSessionManager().getActiveSession()
                            .getAuthToken().token != null
                    && TwitterCore.getInstance().getSessionManager().getActiveSession()
                            .getAuthToken().secret != null) {
                twitterToken = TwitterCore.getInstance().getSessionManager().getActiveSession()
                        .getAuthToken().token;
                twitterSecret = TwitterCore.getInstance().getSessionManager().getActiveSession()
                        .getAuthToken().secret;
            }

            Realm realm = Realm.getDefaultInstance();
            PDRealmUserLocation userLocation = realm.where(PDRealmUserLocation.class).findFirst();

            PDRealmUserDetails userDetails = realm.where(PDRealmUserDetails.class).findFirst();
            String instagramAccessToken = null;
            if (mInstagramSwitch.isChecked() && userDetails.getUserInstagram() != null
                    && userDetails.getUserInstagram().getAccessToken() != null
                    && !userDetails.getUserInstagram().getAccessToken().isEmpty()) {
                instagramAccessToken = userDetails.getUserInstagram().getAccessToken();
            }

            if (mTaggedNames.size() == 0) {
                PDAbraLogEvent.log(PDAbraConfig.ABRA_EVENT_ADDED_CLAIM_CONTENT,
                        new PDAbraProperties.Builder().add(PDAbraConfig.ABRA_PROPERTYNAME_TAGGED_FRIENDS, "Yes")
                                .add("Friends Count", String.valueOf(mTaggedNames.size())).create());
            }

            progressBar.setVisibility(View.GONE);
            shareButton.setVisibility(View.VISIBLE);
            shareButton.setEnabled(true);
            shareButton.animate().alpha(1.0f);

            if (fromTwitter) {
                finishActivityAfterClaim("twitter");
                realm.close();
                return;
            } else if (fromFacebook) {
                finishActivityAfterClaim("facebook");
                realm.close();
                return;
            } else if (fromInstagram) {
                finishActivityAfterClaim("instagram");
                realm.close();
                return;
            }

            PDAPIClient.instance().claimReward(PDUIClaimActivity.this,
                    mFacebookSwitch.isChecked() ? AccessToken.getCurrentAccessToken().getToken() : null,
                    twitterToken, twitterSecret, instagramAccessToken, mReward.getId(), message, mTaggedNames,
                    mTaggedIds, encodedImage, String.valueOf(userLocation.getLongitude()),
                    String.valueOf(userLocation.getLatitude()), new PDAPICallback<JsonObject>() {
                        @Override
                        public void success(JsonObject jsonObject) {
                            PDLog.d(PDUIClaimActivity.class, "claim: " + jsonObject.toString());
                            progressBar.setVisibility(View.GONE);
                            shareButton.setEnabled(true);
                            shareButton.animate().alpha(1.0f);

                            PDAbraLogEvent.log(PDAbraConfig.ABRA_EVENT_CLAIMED, new PDAbraProperties.Builder()
                                    .add(PDAbraConfig.ABRA_PROPERTYNAME_SOCIAL_NETWORKS,
                                            readableNetworksChosen())
                                    .add(PDAbraConfig.ABRA_PROPERTYNAME_PHOTO, mImageAdded ? "YES" : "NO")
                                    .add(PDAbraConfig.ABRA_PROPERTYNAME_REWARD_TYPE,
                                            PDAbraUtils.keyForRewardType(mReward.getRewardType()))
                                    .create());

                            if (fromInstagram) {
                                //                                    verifyReward();
                                finishActivityAfterClaim("instagram");
                            } else if (fromTwitter) {
                                finishActivityAfterClaim("twitter");
                            } else if (fromFacebook) {
                                finishActivityAfterClaim("facebook");
                            } else {
                                //                            new AlertDialog.Builder(PDUIClaimActivity.this)
                                //                                    .setTitle(R.string.pd_claim_reward_claimed_text)
                                //                                    .setMessage(mReward.getRewardType().equalsIgnoreCase(PDReward.PD_REWARD_TYPE_SWEEPSTAKE) ? R.string.pd_claim_sweepstakes_claimed_success_text : R.string.pd_claim_reward_claimed_success_text)
                                //                                    .setPositiveButton(R.string.pd_go_to_wallet_text, new DialogInterface.OnClickListener() {
                                //                                        @Override
                                //                                        public void onClick(DialogInterface dialog, int which) {
                                //                                            Intent data = new Intent();
                                //                                            data.putExtra("id", mReward.getId());
                                //                                            data.putExtra("verificationNeeded", mInstagramSwitch.isChecked());
                                //                                            setResult(RESULT_OK, data);
                                //                                            finish();
                                //                                        }
                                //                                    })
                                //                                    .create()
                                //                                    .show();
                                Intent data = new Intent();
                                data.putExtra("id", mReward.getId());
                                //                                    data.putExtra("verificationNeeded", mInstagramSwitch.isChecked());
                                data.putExtra("verificationNeeded", false);
                                setResult(RESULT_OK, data);
                                finish();
                                claiming = false;

                            }
                        }

                        @Override
                        public void failure(int statusCode, Exception e) {

                            if (fromInstagram) {
                                finishActivityAfterClaim("instagram");
                            } else if (fromTwitter) {
                                finishActivityAfterClaim("twitter");
                            } else if (fromFacebook) {
                                finishActivityAfterClaim("facebook");
                            }
                            Handler mainHandler = new Handler(Looper.getMainLooper());

                            Runnable myRunnable = new Runnable() {
                                @Override
                                public void run() {
                                    progressBar.setVisibility(View.GONE);
                                    shareButton.setEnabled(true);
                                    shareButton.animate().alpha(1.0f);
                                    if (!fromInstagram) {
                                        showBasicOKAlertDialog(R.string.pd_common_sorry_text,
                                                R.string.pd_common_something_wrong_text);
                                    }
                                }
                            };
                            mainHandler.post(myRunnable);

                        }
                    });
            realm.close();

        }
    }, postTime);

}

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

public void onDisconnect(RespokeSignalingChannel sender) {
    // Can only reconnect in development mode, not brokered mode
    final boolean willReconnect = reconnect && (applicationID != null);

    calls.clear();/*from  w ww  .j  av a2 s .c  om*/
    groups.clear();
    knownEndpoints.clear();
    presenceRegistrationQueue.clear();
    presenceRegistered.clear();
    registrationTaskWaiting = false;

    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            Listener listener = listenerReference.get();
            if (null != listener) {
                listener.onDisconnect(RespokeClient.this, willReconnect);
            }
        }
    });

    signalingChannel = null;

    if (willReconnect) {
        performReconnect();
    }
}

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

public void onIncomingCall(JSONObject sdp, String sessionID, String connectionID, String endpointID,
        String fromType, Date timestamp, RespokeSignalingChannel sender) {
    RespokeEndpoint endpoint = null;/*from  w  w  w  . j  a  v  a 2  s.  c o  m*/

    if (fromType.equals("web")) {
        /* Only create endpoints for type web */
        endpoint = getEndpoint(endpointID, false);

        if (null == endpoint) {
            Log.d(TAG, "Error: Could not create Endpoint for incoming call");
            return;
        }
    }

    final RespokeCall call = new RespokeCall(signalingChannel, sdp, sessionID, connectionID, endpointID,
            fromType, endpoint, false, timestamp);

    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            Listener listener = listenerReference.get();
            if (null != listener) {
                listener.onCall(RespokeClient.this, call);
            }
        }
    });
}

From source file:dev.ukanth.ufirewall.Api.java

/**
 * Runs a script as root (multiple commands separated by "\n")
* @param ctx mandatory context/*from  w w w.j  a v  a  2s.  c  o m*/
 * @param script the script to be executed
 * @param res the script output response (stdout + stderr)
 * @return the script exit code
 * @throws IOException on any error executing the script, or writing it to disk
 */
public static int runScriptAsRoot(Context ctx, List<String> script, StringBuilder res) throws IOException {
    int returnCode = -1;

    if ((Looper.myLooper() != null) && (Looper.myLooper() == Looper.getMainLooper())) {
        Log.e(TAG, "runScriptAsRoot should not be called from the main thread\nCall Trace:\n");
        for (StackTraceElement e : new Throwable().getStackTrace()) {
            Log.e(TAG, e.toString());
        }
    }

    try {
        returnCode = new RunCommand().execute(script, res, ctx).get();
    } catch (RejectedExecutionException r) {
        Log.e(TAG, "runScript failed: " + r.getLocalizedMessage());
    } catch (InterruptedException e) {
        Log.e(TAG, "Caught InterruptedException");
    } catch (ExecutionException e) {
        Log.e(TAG, "runScript failed: " + e.getLocalizedMessage());
    } catch (Exception e) {
        Log.e(TAG, "runScript failed: " + e.getLocalizedMessage());
    }

    return returnCode;
}

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

public void onError(final String errorMessage, RespokeSignalingChannel sender) {
    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override/*w  ww.ja  va2 s  . c  om*/
        public void run() {
            Listener listener = listenerReference.get();
            if (null != listener) {
                listener.onError(RespokeClient.this, errorMessage);
            }
        }
    });

    if ((null != signalingChannel) && (!signalingChannel.connected)) {
        connectionInProgress = false;

        if (reconnect) {
            performReconnect();
        }
    }
}