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:com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUser.java

/**
 * Verify an attribute with the verification code, in background.
 * <p>// w w  w.  j  a  v  a 2s .c om
 * Call this method to verify an attribute with the "verification code". To
 * request for a "verification code" call the method
 * {@link CognitoUser#getAttributeVerificationCodeInBackground(String, VerificationHandler)}
 * .
 * </p>
 *
 * @param attributeName REQUIRED: The attribute that is being verified.
 * @param verificationCode REQUIRED: The code for verification.
 * @param callback REQUIRED: Callback
 */
public void verifyAttributeInBackground(final String attributeName, final String verificationCode,
        final GenericHandler callback) {
    if (callback == null) {
        throw new CognitoParameterInvalidException("callback is null");
    }
    final CognitoUser user = this;

    new Thread(new Runnable() {
        @Override
        public void run() {
            final Handler handler = new Handler(context.getMainLooper());
            Runnable returnCallback;
            try {
                final CognitoUserSession session = user.getCachedSession();
                verifyAttributeInternal(attributeName, verificationCode, session);
                returnCallback = new Runnable() {
                    @Override
                    public void run() {
                        callback.onSuccess();
                    }
                };
            } catch (final Exception e) {
                returnCallback = new Runnable() {
                    @Override
                    public void run() {
                        callback.onFailure(e);
                    }
                };
            }
            handler.post(returnCallback);
        }
    }).start();
}

From source file:com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUser.java

/**
 * Request to change password for this user, in background.
 * <p>/*from www  .j av a  2 s.c o m*/
 * This operation requires a valid accessToken
 * {@link CognitoUserSession#accessToken}. Un-authenticated users will have
 * to be authenticated before calling this method.
 * </p>
 *
 * @param oldUserPassword REQUIRED: Current password of this user.
 * @param newUserPassword REQUIRED: New password for this user.
 * @param callback REQUIRED: {@link GenericHandler} callback handler.
 */
public void changePasswordInBackground(final String oldUserPassword, final String newUserPassword,
        final GenericHandler callback) {
    if (callback == null) {
        throw new CognitoParameterInvalidException("callback is null");
    }

    final CognitoUser user = this;

    new Thread(new Runnable() {
        @Override
        public void run() {
            final Handler handler = new Handler(context.getMainLooper());
            Runnable returnCallback;
            try {
                final CognitoUserSession session = user.getCachedSession();
                changePasswordInternal(oldUserPassword, newUserPassword, session);
                returnCallback = new Runnable() {
                    @Override
                    public void run() {
                        callback.onSuccess();
                    }
                };
            } catch (final Exception e) {
                returnCallback = new Runnable() {
                    @Override
                    public void run() {
                        callback.onFailure(e);
                    }
                };
            }
            handler.post(returnCallback);
        }
    }).start();
}

From source file:com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUser.java

/**
 * Sign-out from all devices associated with this user, in background.
 *
 * @param callback REQUIRED: {@link GenericHandler} callback.
 *///from  w ww. ja va 2 s .c o m
public void globalSignOutInBackground(final GenericHandler callback) {

    if (callback == null) {
        throw new CognitoParameterInvalidException("callback is null");
    }
    final CognitoUser user = this;

    new Thread(new Runnable() {
        @Override
        public void run() {
            final Handler handler = new Handler(context.getMainLooper());
            Runnable returnCallback;
            try {
                final CognitoUserSession session = user.getCachedSession();
                globalSignOutInternal(session);
                returnCallback = new Runnable() {
                    @Override
                    public void run() {
                        signOut();
                        callback.onSuccess();
                    }
                };
            } catch (final Exception e) {
                returnCallback = new Runnable() {
                    @Override
                    public void run() {
                        callback.onFailure(e);
                    }
                };
            }
            handler.post(returnCallback);
        }
    }).start();
}

From source file:com.amaze.carbonfilemanager.activities.MainActivity.java

void sendScroll(final HorizontalScrollView scrollView) {
    final Handler handler = new Handler();
    new Thread(new Runnable() {
        @Override//from w  w  w. jav a 2 s .com
        public void run() {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
            }
            handler.post(new Runnable() {
                @Override
                public void run() {
                    scrollView.fullScroll(View.FOCUS_RIGHT);
                }
            });
        }
    }).start();
}

From source file:com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUser.java

/**
 * Retrieves the current user attributes. Runs in background.
 * <p>/*  ww w .  ja  va  2 s.c  o  m*/
 * All attributes, which are set for this user, are fetched. This method
 * requires valid accessToken.
 * </p>
 *
 * @param callback REQUIRED: {@link GetDetailsHandler} callback
 */
public void getDetailsInBackground(final GetDetailsHandler callback) {

    if (callback == null) {
        throw new CognitoParameterInvalidException("callback is null");
    }
    final CognitoUser user = this;

    new Thread(new Runnable() {
        @Override
        public void run() {
            final Handler handler = new Handler(context.getMainLooper());
            Runnable returnCallback;
            try {
                final CognitoUserSession session = user.getCachedSession();
                final CognitoUserDetails userDetails = getUserDetailsInternal(session);
                returnCallback = new Runnable() {
                    @Override
                    public void run() {
                        callback.onSuccess(userDetails);
                    }
                };
            } catch (final Exception e) {
                returnCallback = new Runnable() {
                    @Override
                    public void run() {
                        callback.onFailure(e);
                    }
                };
            }
            handler.post(returnCallback);
        }
    }).start();
}

From source file:com.android.settings.applications.CanBeOnSdCardChecker.java

@Override
public void onClick(DialogInterface dialog, int which) {
    if (mResetDialog == dialog) {
        final PackageManager pm = getActivity().getPackageManager();
        final IPackageManager mIPm = IPackageManager.Stub.asInterface(ServiceManager.getService("package"));
        final INotificationManager nm = INotificationManager.Stub
                .asInterface(ServiceManager.getService(Context.NOTIFICATION_SERVICE));
        final NetworkPolicyManager npm = NetworkPolicyManager.from(getActivity());
        final AppOpsManager aom = (AppOpsManager) getActivity().getSystemService(Context.APP_OPS_SERVICE);
        final Handler handler = new Handler(getActivity().getMainLooper());
        (new AsyncTask<Void, Void, Void>() {
            @Override/*w  w w.  j ava 2s .  c om*/
            protected Void doInBackground(Void... params) {
                List<ApplicationInfo> apps = pm
                        .getInstalledApplications(PackageManager.GET_DISABLED_COMPONENTS);
                for (int i = 0; i < apps.size(); i++) {
                    ApplicationInfo app = apps.get(i);
                    try {
                        if (DEBUG)
                            Log.v(TAG, "Enabling notifications: " + app.packageName);
                        nm.setNotificationsEnabledForPackage(app.packageName, app.uid, true);
                    } catch (android.os.RemoteException ex) {
                    }
                    if (!app.enabled) {
                        if (DEBUG)
                            Log.v(TAG, "Enabling app: " + app.packageName);
                        if (pm.getApplicationEnabledSetting(
                                app.packageName) == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
                            pm.setApplicationEnabledSetting(app.packageName,
                                    PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
                                    PackageManager.DONT_KILL_APP);
                        }
                    }
                }
                try {
                    mIPm.resetPreferredActivities(UserHandle.myUserId());
                } catch (RemoteException e) {
                }
                aom.resetAllModes();
                final int[] restrictedUids = npm.getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND);
                final int currentUserId = ActivityManager.getCurrentUser();
                for (int uid : restrictedUids) {
                    // Only reset for current user
                    if (UserHandle.getUserId(uid) == currentUserId) {
                        if (DEBUG)
                            Log.v(TAG, "Clearing data policy: " + uid);
                        npm.setUidPolicy(uid, POLICY_NONE);
                    }
                }
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (DEBUG)
                            Log.v(TAG, "Done clearing");
                        if (getActivity() != null && mActivityResumed) {
                            if (DEBUG)
                                Log.v(TAG, "Updating UI!");
                            for (int i = 0; i < mTabs.size(); i++) {
                                TabInfo tab = mTabs.get(i);
                                if (tab.mApplications != null) {
                                    tab.mApplications.pause();
                                }
                            }
                            if (mCurTab != null) {
                                mCurTab.resume(mSortOrder);
                            }
                        }
                    }
                });
                return null;
            }
        }).execute();
    }
}

From source file:com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUser.java

/**
 * Request to resend registration confirmation code for a user, in
 * background.// w  w  w .j a va  2 s  .  c o m
 *
 * @param callback REQUIRED: {@link VerificationHandler} callback handler.
 */
public void resendConfirmationCodeInBackground(final VerificationHandler callback) {
    if (callback == null) {
        throw new CognitoParameterInvalidException("callback is null");
    }
    new Thread(new Runnable() {
        @Override
        public void run() {
            final Handler handler = new Handler(context.getMainLooper());
            Runnable returnCallback;
            try {
                final ResendConfirmationCodeResult resendConfirmationCodeResult = resendConfirmationCodeInternal();
                returnCallback = new Runnable() {
                    @Override
                    public void run() {
                        callback.onSuccess(new CognitoUserCodeDeliveryDetails(
                                resendConfirmationCodeResult.getCodeDeliveryDetails()));
                    }
                };
            } catch (final Exception e) {
                returnCallback = new Runnable() {
                    @Override
                    public void run() {
                        callback.onFailure(e);
                    }
                };
            }
            handler.post(returnCallback);
        }
    }).start();
}

From source file:com.sentaroh.android.SMBSync.SMBSyncMain.java

private void autoTerminateDlg(final String result_code, final String result_msg) {
    final ThreadCtrl threadCtl = new ThreadCtrl();
    threadCtl.setEnabled();//enableAsyncTask();

    final LinearLayout ll_bar = (LinearLayout) findViewById(R.id.profile_progress_bar);
    ll_bar.setVisibility(LinearLayout.VISIBLE);
    ll_bar.setBackgroundColor(Color.BLACK);
    ll_bar.bringToFront();//from  ww w  . j a  v a  2s.  c om

    final TextView title = (TextView) findViewById(R.id.profile_progress_bar_msg);
    title.setText("");
    final Button btnCancel = (Button) findViewById(R.id.profile_progress_bar_btn_cancel);
    btnCancel.setText(getString(R.string.msgs_progress_bar_dlg_aterm_cancel));
    final Button btnImmed = (Button) findViewById(R.id.profile_progress_bar_btn_immediate);
    btnImmed.setText(getString(R.string.msgs_progress_bar_dlg_aterm_immediate));

    // CANCEL?
    btnCancel.setEnabled(true);
    btnCancel.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            mGp.settingAutoTerm = false;
            btnCancel.setText(getString(R.string.msgs_progress_dlg_canceling));
            btnCancel.setEnabled(false);
            threadCtl.setDisabled();//disableAsyncTask();
            util.addLogMsg("W", getString(R.string.msgs_aterm_canceling));
            showNotificationMsg(getString(R.string.msgs_aterm_canceling));
        }
    });

    final NotifyEvent at_ne = new NotifyEvent(mContext);
    at_ne.setListener(new NotifyEventListener() {
        @Override
        public void positiveResponse(Context c, Object[] o) {
            util.addLogMsg("I", getString(R.string.msgs_aterm_expired));
            if (mGp.settingAutoTerm || (isExtraSpecAutoStart && extraValueAutoStart)) {
                svcStopForeground(true);
                //Wait until stopForeground() completion 
                Handler hndl = new Handler();
                hndl.post(new Runnable() {
                    @Override
                    public void run() {
                        util.addDebugLogMsg(1, "I", "Auto termination was invoked.");
                        if (!mGp.settingBgTermNotifyMsg.equals(SMBSYNC_BG_TERM_NOTIFY_MSG_NO)) {
                            //                        Log.v("","result code="+result_code+", result_msg="+result_msg);
                            if (mGp.settingBgTermNotifyMsg.equals(SMBSYNC_BG_TERM_NOTIFY_MSG_ALWAYS))
                                NotificationUtil.showNoticeMsg(mContext, mGp, result_msg);
                            else {
                                if (!result_code.equals("OK")) {
                                    NotificationUtil.showNoticeMsg(mContext, mGp, result_msg);
                                } else {
                                    NotificationUtil.clearNotification(mGp);
                                }
                            }
                        } else {
                            NotificationUtil.clearNotification(mGp);
                        }
                        //                     saveTaskData();
                        util.flushLogFile();
                        terminateApplication();
                    }
                });
            }
        }

        @Override
        public void negativeResponse(Context c, Object[] o) {
            util.addLogMsg("W", getString(R.string.msgs_aterm_cancelled));
            showNotificationMsg(getString(R.string.msgs_aterm_cancelled));
            util.rotateLogFile();
            mGp.mirrorThreadActive = false;
        }
    });

    // Immediate?
    btnImmed.setEnabled(true);
    btnImmed.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            mRequestAutoTimerExpired = true;
            threadCtl.setDisabled();//disableAsyncTask();
        }
    });

    //      Log.v("","e="+extraDataSpecifiedAutoTerm);
    util.addLogMsg("I", getString(R.string.msgs_aterm_started));
    if (extraValueAutoTerm) {
        util.addLogMsg("I", getString(R.string.msgs_aterm_back_ground_term));
        at_ne.notifyToListener(true, null);
    } else if (!util.isActivityForeground()) {
        util.addLogMsg("I", getString(R.string.msgs_aterm_back_ground_term));
        at_ne.notifyToListener(true, null);
    } else {
        mRequestAutoTimerExpired = false;
        autoTimer(threadCtl, at_ne, getString(R.string.msgs_aterm_terminate_after));
    }
}

From source file:com.grazerss.EntryManager.java

private void runSimpleJob(final String name, final Runnable runnable, final Handler handler) {
    new Thread(new Runnable() {
        public void run() {
            try {
                runJob(new Job(name, EntryManager.this) {

                    @Override/* w  w w  .j a  v a  2 s .  c  o  m*/
                    public void run() throws Exception {

                        try {
                            Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);

                            synchronized (this) {
                                if (isModelCurrentlyUpdated()) {
                                    return;
                                }
                                lockModel(name);
                            }
                            runnable.run();
                        } finally {
                            synchronized (this) {
                                unlockModel(name);
                            }
                        }
                    }
                });
            } catch (final Throwable e) {
                if (handler != null) {
                    handler.post(new Runnable() {

                        public void run() {
                            showExceptionToast(name, e);
                        }
                    });
                }
            }

        }
    }).start();
}

From source file:com.njlabs.amrita.aid.info.Calender.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private void setCustomResourceForDates() {

    final Handler dataHandler = new Handler();
    (new Thread(new Runnable() {
        @Override//w  w w  .  jav  a  2 s .com
        public void run() {

            try {

                InputStream icsInput = getAssets().open("ASECalendar.ics");
                CalendarBuilder builder = new CalendarBuilder();
                net.fortuna.ical4j.model.Calendar calendar = builder.build(icsInput);

                for (Object calendarComponentObject : calendar.getComponents()) {
                    CalendarComponent calendarComponent = (CalendarComponent) calendarComponentObject;
                    String title = calendarComponent.getProperty(Property.SUMMARY).getValue();
                    if (title.length() > 4) {
                        Date startDate = parseDate(calendarComponent.getProperty(Property.DTSTART).getValue());
                        Date endDate = parseDate(calendarComponent.getProperty(Property.DTEND).getValue());
                        title = title.replaceAll("^CD\\d\\d:\\s", "").replaceAll("^CD\\d:\\s", "").replace("*",
                                "");

                        int color = R.color.calendar_green;

                        if (containsAny(title,
                                new String[] { "assessment", "exam", "test", "assesment", "end semester" })) {
                            color = R.color.calendar_red;
                        } else if (containsAny(title,
                                new String[] { "institution day", "amritotsavam", "amritotasavam", "classes",
                                        "working", "instruction", "enrolment", "Birthday", "Talent", "TABLE",
                                        "orientation", "counselling" })) {
                            color = R.color.calendar_blue;
                        } else if (containsAny(title, new String[] { "anokha", "tech fest" })) {
                            color = R.color.calendar_anokha_orange;
                        }

                        Calendar start = Calendar.getInstance();
                        start.setTime(startDate);
                        Calendar end = Calendar.getInstance();
                        end.setTime(endDate);

                        //noinspection WrongConstant
                        if (start.get(Calendar.DAY_OF_MONTH) == end.get(Calendar.DAY_OF_MONTH)
                                || end.get(Calendar.DAY_OF_MONTH) == start.get(Calendar.DAY_OF_MONTH) + 1) {
                            backgroundColors.put(startDate, color);
                            textColors.put(startDate, R.color.white);
                            descriptions.put(formatter.format(startDate), title);
                        } else {
                            for (Date date = start.getTime(); start.before(end); start.add(Calendar.DATE,
                                    1), date = start.getTime()) {
                                backgroundColors.put(date, color);
                                textColors.put(date, R.color.white);
                                descriptions.put(formatter.format(date), title);
                            }
                        }
                    }
                }

            } catch (Exception e) {
                FirebaseCrash.report(e);
            }

            dataHandler.post(new Runnable() {
                @Override
                public void run() {
                    if (caldroidFragment != null) {
                        caldroidFragment.setBackgroundResourceForDates(backgroundColors);
                        caldroidFragment.setTextColorForDates(textColors);
                        caldroidFragment.refreshView();
                        findViewById(R.id.calendar_holder).setVisibility(View.VISIBLE);
                        findViewById(R.id.progress).setVisibility(View.GONE);
                    }
                }
            });
        }
    })).start();
}