Example usage for android.os Handler post

List of usage examples for android.os Handler post

Introduction

In this page you can find the example usage for android.os Handler post.

Prototype

public final boolean post(Runnable r) 

Source Link

Document

Causes the Runnable r to be added to the message queue.

Usage

From source file:org.mobicents.restcomm.android.client.sdk.RCConnection.java

private void onRemoteDescription(final SessionDescription sdp) {
    final long delta = System.currentTimeMillis() - callStartedTimeMs;
    Handler mainHandler = new Handler(RCClient.getContext().getMainLooper());
    Runnable myRunnable = new Runnable() {
        @Override/*from w  ww .ja va2s  . c o m*/
        public void run() {
            RCLogger.i(TAG, "onRemoteDescription");
            if (peerConnectionClient == null) {
                RCLogger.e(TAG, "Received remote SDP for non-initilized peer connection.");
                return;
            }
            logAndToast("Received remote " + sdp.type + ", delay=" + delta + "ms");
            SignalingParameters params = SignalingParameters.extractCandidates(sdp);
            peerConnectionClient.setRemoteDescription(params.offerSdp);
            onRemoteIceCandidates(params.iceCandidates);

            if (!signalingParameters.initiator) {
                logAndToast("Creating ANSWER...");
                // Create answer. Answer SDP will be sent to offering client in
                // PeerConnectionEvents.onLocalDescription event.
                peerConnectionClient.createAnswer();
            }
        }
    };
    mainHandler.post(myRunnable);
}

From source file:org.mobicents.restcomm.android.client.sdk.RCConnection.java

@Override
public void onIceConnected() {
    final long delta = System.currentTimeMillis() - callStartedTimeMs;

    Handler mainHandler = new Handler(RCClient.getContext().getMainLooper());
    Runnable myRunnable = new Runnable() {
        @Override//w  ww.  j a  v a2  s .c  o m
        public void run() {
            RCLogger.i(TAG, "onIceConnected");

            // stop any calling or ringing sound
            audioManager.stop();

            // we 're connected, cancel any pending timeout timers
            timeoutHandler.removeCallbacksAndMessages(null);

            logAndToast("ICE connected, delay=" + delta + "ms");
            iceConnected = true;
            RCConnection.this.state = ConnectionState.CONNECTED;
            updateVideoView(VideoViewState.ICE_CONNECTED);

            HashMap<String, String> customHeaders = null;
            if (callParams.containsKey(ParameterKeys.CONNECTION_CUSTOM_INCOMING_SIP_HEADERS)) {
                customHeaders = (HashMap<String, String>) callParams
                        .get(ParameterKeys.CONNECTION_CUSTOM_INCOMING_SIP_HEADERS);
            }
            listener.onConnected(RCConnection.this, customHeaders);
        }
    };
    mainHandler.post(myRunnable);
}

From source file:org.mobicents.restcomm.android.client.sdk.RCConnection.java

@Override
public void onPeerConnectionError(final String description) {
    final RCConnection connection = this;
    Handler mainHandler = new Handler(RCClient.getContext().getMainLooper());
    Runnable myRunnable = new Runnable() {
        @Override/*from  www . j av  a2  s  .c  o m*/
        public void run() {
            RCLogger.e(TAG, "PeerConnection error: " + description);
            String reason = null;
            if (description.equals("ICE connection failed")) {
                // in cases where this is the result of IceConnectionState.FAILED, which means that media connectivity is lost we need to add proper reason header
                reason = "Connectivity-Drop";
            }
            handleDisconnect(reason);

            if (connection.listener != null) {
                connection.listener.onDisconnected(connection,
                        RCClient.ErrorCodes.ERROR_CONNECTION_WEBRTC_PEERCONNECTION_ERROR.ordinal(),
                        description);
            }
            // Phone state Intents to capture dropped call event
            sendQoSDisconnectErrorIntent(
                    RCClient.ErrorCodes.ERROR_CONNECTION_WEBRTC_PEERCONNECTION_ERROR.ordinal(), description);
        }
    };
    mainHandler.post(myRunnable);
}

From source file:info.guardianproject.otr.app.im.app.NewChatActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent resultIntent) {
    if (resultCode == RESULT_OK) {
        if (requestCode == REQUEST_SEND_IMAGE || requestCode == REQUEST_SEND_FILE
                || requestCode == REQUEST_SEND_AUDIO) {
            Uri uri = resultIntent.getData();
            if (uri == null) {
                return;
            }//from   w  w  w  .  j a v  a  2s .co  m
            boolean deleteAudioFile = (requestCode == REQUEST_SEND_AUDIO);
            handleSendDelete(uri, null, deleteAudioFile, false);
        } else if (requestCode == REQUEST_TAKE_PICTURE) {
            File file = new File(getRealPathFromURI(mLastPhoto));
            final Handler handler = new Handler();
            MediaScannerConnection.scanFile(this, new String[] { file.toString() }, null,
                    new MediaScannerConnection.OnScanCompletedListener() {
                        @Override
                        public void onScanCompleted(String path, final Uri uri) {

                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    handleSendDelete(mLastPhoto, "image/*", true, true);
                                }
                            });
                        }
                    });
        } else if (requestCode == REQUEST_TAKE_PICTURE_SECURE) {
            String filename = resultIntent.getStringExtra(SecureCameraActivity.FILENAME);
            String mimeType = resultIntent.getStringExtra(SecureCameraActivity.MIMETYPE);
            Uri uri = Uri.parse("file:" + filename);
            handleSend(uri, mimeType);
        } else if (requestCode == REQUEST_SETTINGS) {

            try {
                mApp.getRemoteImService().updateStateFromSettings();
            } catch (Exception e) {
                Log.e(ImApp.LOG_TAG, "unable to update service settings", e);
            }

            finish();
            Intent intent = new Intent(getApplicationContext(), NewChatActivity.class);
            startActivity(intent);

        } else if (requestCode == REQUEST_PICK_CONTACTS || requestCode == REQUEST_ADD_CONTACT) {

            String username = resultIntent.getStringExtra(ContactsPickerActivity.EXTRA_RESULT_USERNAME);
            long providerId = resultIntent.getLongExtra(ContactsPickerActivity.EXTRA_RESULT_PROVIDER, -1);

            //String message = resultIntent.getStringExtra(ContactsPickerActivity.EXTRA_RESULT_MESSAGE);
            try {

                IChatSession chatSession = this.getCurrentChatSession();
                if (chatSession != null && chatSession.isGroupChatSession()) {
                    chatSession.inviteContact(username);
                    showInvitationHasSent(username);
                } else {
                    startChat(providerId, username, Imps.ContactsColumns.TYPE_NORMAL, true, null);
                }
            } catch (RemoteException e) {
                mHandler.showServiceErrorAlert("Error picking contacts");
                Log.d(ImApp.LOG_TAG, "error picking contact", e);
            }
        }

        IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, resultIntent);

        if (scanResult != null) {
            String xmppUri = scanResult.getContents();
            String result = null;
            if (xmppUri.startsWith("xmpp"))
                result = XmppUriHelper.getOtrFingerprint(xmppUri);

            if (getCurrentChatView() != null && result != null)
                getCurrentChatView().verifyScannedFingerprint(result);
            else {
                //add new contact?
            }

        }
    }
}

From source file:com.echopf.ECHODataObject.java

/**
 * Does Push data to the remote server in a background thread.
 * // w ww  .j  a  va 2  s  .c om
 * @param sync if set TRUE, then the main (UI) thread is waited for complete the pushing in a background thread. 
 *              (a synchronous communication)
 * @param callback invoked after the pushing is completed
 * @throws ECHOException 
 */
protected void doPush(final boolean sync, final PushCallback<S> callback) throws ECHOException {

    final JSONObject obj = buildRequestContents();

    if (this.multipart == null)
        throw new IllegalStateException("`buildRequestContents()` had not been completed.");
    final boolean fMultipart = this.multipart;

    // Get ready a background thread
    final Handler handler = new Handler();
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Callable<Object> communictor = new Callable<Object>() {

        @Override
        public Object call() throws ECHOException {

            JSONObject data = null;
            ECHOException exception = null;

            try {
                synchronized (lock) {

                    if (refid == null) { // post
                        if (fMultipart == false) {
                            data = ECHOQuery.postRequest(getRequestURLPath(), obj);
                        } else {
                            data = ECHOQuery.multipartPostRequest(getRequestURLPath(), obj);
                        }
                    } else { // put
                        if (fMultipart == false) {
                            data = ECHOQuery.putRequest(getRequestURLPath(), obj);
                        } else {
                            data = ECHOQuery.multipartPutRequest(getRequestURLPath(), obj);
                        }
                    }

                    refid = data.optString("refid");
                    copyData(data);
                }

            } catch (ECHOException e) {
                exception = e;
            } catch (Exception e) {
                exception = new ECHOException(e);
            }

            if (sync == false) {

                // Execute a callback method in the main (UI) thread.
                if (callback != null) {
                    final ECHOException fException = exception;

                    handler.post(new Runnable() {
                        @Override
                        @SuppressWarnings("unchecked")
                        public void run() {
                            callback.done((S) ECHODataObject.this, fException);
                        }
                    });
                }

            } else {

                if (exception != null)
                    throw exception;

            }

            return null;
        }
    };

    Future<Object> future = executor.submit(communictor);

    if (sync) {
        try {
            future.get();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt(); // ignore/reset
        } catch (ExecutionException e) {
            Throwable e2 = e.getCause();

            if (e2 instanceof ECHOException) {
                throw (ECHOException) e2;
            }

            throw new RuntimeException(e2);
        }
    }
}

From source file:com.sentaroh.android.TaskAutomation.Config.ProfileMaintenanceActionProfile.java

public void reInitViewWidget() {
    if (DEBUG_ENABLE)
        Log.v(APPLICATION_TAG, "reInitViewWidget");
    if (!mTerminateRequired) {
        Handler hndl = new Handler();
        hndl.post(new Runnable() {
            @Override/*from   w  w w.  ja  va 2s  .c  o m*/
            public void run() {
                SavedViewContents sv = null;
                if (!mOpType.equals("BROWSE"))
                    sv = saveViewContents();

                initViewWidget();

                if (!mOpType.equals("BROWSE"))
                    restoreViewContents(sv);

                CommonDialog.setDlgBoxSizeLimit(mDialog, true);
            }
        });
    }
}

From source file:io.realm.TypeBasedNotificationsTests.java

@Test
@RunTestInLooperThread//from   w  ww .j a va2s  .c  om
public void callback_with_relevant_commit_from_different_looper_realmobject_async() {
    final CountDownLatch looperThread1Done = new CountDownLatch(1);
    final CountDownLatch looperThread2Done = new CountDownLatch(1);
    final CountDownLatch looperThread3Done = new CountDownLatch(1);
    final HandlerThread looperThread1 = new HandlerThread("looperThread1");
    final HandlerThread looperThread2 = new HandlerThread("looperThread2");
    final HandlerThread looperThread3 = new HandlerThread("looperThread3");
    looperThread1.start();
    looperThread2.start();
    looperThread3.start();
    final Handler looperHandler1 = new Handler(looperThread1.getLooper());
    final Handler looperHandler2 = new Handler(looperThread2.getLooper());
    final Handler looperHandler3 = new Handler(looperThread3.getLooper());
    final Realm realm = looperThread.realm;
    realm.addChangeListener(new RealmChangeListener() {
        @Override
        public void onChange() {
            globalCommitInvocations.incrementAndGet();
        }
    });

    final Dog dog = realm.where(Dog.class).findFirstAsync();
    assertTrue(dog.load());
    dog.addChangeListener(new RealmChangeListener() {
        @Override
        public void onChange() {
            switch (typebasedCommitInvocations.incrementAndGet()) {
            case 1: // triggered by COMPLETED_ASYNC_REALM_OBJECT from calling dog.load()
                assertTrue(dog.isLoaded());
                assertFalse(dog.isValid());

                looperHandler1.post(new Runnable() {
                    @Override
                    public void run() {
                        Realm realmLooperThread1 = Realm.getInstance(realm.getConfiguration());
                        realmLooperThread1.beginTransaction();
                        realmLooperThread1.commitTransaction();
                        realmLooperThread1.close();
                        looperThread1Done.countDown();
                    }
                });
                break;
            case 2: // triggered by the irrelevant commit (not affecting Dog table) from LooperThread1
                assertTrue(dog.isLoaded());
                assertFalse(dog.isValid());

                looperHandler2.post(new Runnable() {
                    @Override
                    public void run() {
                        Realm realmLooperThread2 = Realm.getInstance(realm.getConfiguration());
                        // trigger first callback invocation
                        realmLooperThread2.beginTransaction();
                        Dog dog = realmLooperThread2.createObject(Dog.class);
                        dog.setName("Akamaru");
                        realmLooperThread2.commitTransaction();
                        realmLooperThread2.close();
                        looperThread2Done.countDown();
                    }
                });
                break;

            case 3: // triggered by relevant commit from LooperThread2
                assertEquals("Akamaru", dog.getName());
                realm.handler.post(new Runnable() {
                    @Override
                    public void run() {
                        // trigger second callback invocation
                        looperHandler3.post(new Runnable() {
                            @Override
                            public void run() {
                                Realm realmLooperThread3 = Realm.getInstance(realm.getConfiguration());
                                realmLooperThread3.beginTransaction();
                                realmLooperThread3.where(Dog.class).findFirst().setAge(17);
                                realmLooperThread3.commitTransaction();
                                realmLooperThread3.close();
                                looperThread3Done.countDown();
                            }
                        });
                    }
                });
                break;
            case 4:
                assertEquals("Akamaru", dog.getName());
                assertEquals(17, dog.getAge());
                // posting as an event will give the handler a chance
                // to deliver the notification for globalCommitInvocations
                // otherwise, test will exit before the callback get a chance to be invoked
                realm.handler.post(new Runnable() {
                    @Override
                    public void run() {
                        assertEquals(3, globalCommitInvocations.get());
                        assertEquals(4, typebasedCommitInvocations.get());
                        looperThread1.quit();
                        looperThread2.quit();
                        looperThread3.quit();
                        TestHelper.awaitOrFail(looperThread1Done);
                        TestHelper.awaitOrFail(looperThread2Done);
                        TestHelper.awaitOrFail(looperThread3Done);
                        looperThread.testComplete();
                    }
                });
                break;
            }
        }
    });

}

From source file:org.mobicents.restcomm.android.client.sdk.RCConnection.java

@Override
public void onLocalDescription(final SessionDescription sdp) {
    final long delta = System.currentTimeMillis() - callStartedTimeMs;
    final RCConnection connection = this;
    Handler mainHandler = new Handler(RCClient.getContext().getMainLooper());
    Runnable myRunnable = new Runnable() {
        @Override/*w  w w . j  a  v a 2  s . com*/
        public void run() {
            RCLogger.i(TAG, "onLocalDescription");
            if (signalingParameters != null) { // && !signalingParameters.sipUrl.isEmpty()) {
                logAndToast("Sending " + sdp.type + ", delay=" + delta + "ms");
                if (signalingParameters.initiator) {
                    // keep it around so that we combine it with candidates before sending it over
                    connection.signalingParameters.offerSdp = sdp;
                    //appRtcClient.sendOfferSdp(sdp);
                } else {
                    //appRtcClient.sendAnswerSdp(sdp);
                    connection.signalingParameters.answerSdp = sdp;
                    // for an incoming call we have already stored the offer candidates there, now
                    // we are done with those and need to come up with answer candidates
                    // TODO: this might prove dangerous as the signalingParms struct used to be all const,
                    // but I changed it since with JAIN sip signalling where various parts are picked up
                    // at different points in time
                    connection.signalingParameters.iceCandidates.clear();
                }
            }
        }
    };
    mainHandler.post(myRunnable);
}

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);//from   ww  w.ja va2s  .c o m
    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:org.mobicents.restcomm.android.client.sdk.RCConnection.java

private void createPeerConnectionFactory() {
    final RCConnection connection = this;
    // Important: need to fire the event in UI context cause currently we 're in JAIN SIP thread
    Handler mainHandler = new Handler(RCClient.getContext().getMainLooper());
    Runnable myRunnable = new Runnable() {
        @Override//from  w ww  .  ja  va 2s . co  m
        public void run() {
            RCLogger.i(TAG, "createPeerConnectionFactory");
            if (peerConnectionClient == null) {
                final long delta = System.currentTimeMillis() - callStartedTimeMs;
                RCLogger.d(TAG, "Creating peer connection factory, delay=" + delta + "ms");
                peerConnectionClient = PeerConnectionClient.getInstance();
                peerConnectionClient.createPeerConnectionFactory(RCClient.getContext(),
                        peerConnectionParameters, connection);
                logAndToast("Created PeerConnectionFactory");
            }
            if (signalingParameters != null) {
                RCLogger.w(TAG, "EGL context is ready after room connection.");
                // #WEBRTC-VIDEO TODO: when I disabled the video view stuff, I also had to comment this out cause it turns out
                // that in that case this part of the code was executed (as if signalingParameters was null and now it isn't),
                // which resulted in onConnectedToRoomInternal being called twice for the same call! When I reinstate
                // video this should probably be uncommented:
                //onConnectedToRoomInternal(signalingParameters);
            }
        }
    };
    mainHandler.post(myRunnable);
}