Example usage for android.os Handler postDelayed

List of usage examples for android.os Handler postDelayed

Introduction

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

Prototype

public final boolean postDelayed(Runnable r, long delayMillis) 

Source Link

Document

Causes the Runnable r to be added to the message queue, to be run after the specified amount of time elapses.

Usage

From source file:com.zzisoo.toylibrary.fragment.ToyListViewFragment.java

private void getData() {
    AsyncHttpClient asyncHttpClient = new AsyncHttpClient();

    asyncHttpClient.get(getActivity(), Config.URL_BOOKS_LIST, new AsyncHttpResponseHandler() {
        private IntroProgressPopupDialog mIntroProgressPopup;

        @Override//from ww  w . ja  va2s .co  m
        public void onStart() {
            super.onStart();
            mIntroProgressPopup = new IntroProgressPopupDialog(getActivity());
            mIntroProgressPopup.setProgressBarVisible(false);
            mIntroProgressPopup.show();
        }

        @Override
        public void onPreProcessResponse(ResponseHandlerInterface instance, HttpResponse response) {
            super.onPreProcessResponse(instance, response);
        }

        @Override
        public void onProgress(int bytesWritten, int totalSize) {
            mIntroProgressPopup.setProgressBarVisible(true);

            super.onProgress(bytesWritten, totalSize);
            Log.v(TAG, bytesWritten + "/" + totalSize);
            mIntroProgressPopup.setProgress((int) (100 * bytesWritten / totalSize));
        }

        @Override
        public void onSuccess(int i, Header[] headers, byte[] bytes) {
            Log.d(TAG, "Http Get Success");
            String responseStr = new String(bytes);
            Log.d(TAG, "[" + i + "] Received Msg:" + responseStr);
            mIntroProgressPopup.dismiss();

            mPref.setUpdateMode();
            mPref.setStringPref(SharedPref.PREF_TOYS_LIST, responseStr);
            mPref.updateFinish();
            dataLoad(responseStr);
        }

        @Override
        public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
            Log.d(TAG, "Http Get Failure");
            Log.d(TAG, "Code [" + i + "] ");
            mIntroProgressPopup.setProgressBarVisible(false);
            mIntroProgressPopup.setText("ERROR Code: " + i);

            String oldData = mPref.getStringPref(SharedPref.PREF_TOYS_LIST);
            if (oldData.equals(SharedPref.NODATA_STRING)) {
                delayedFinish();
            } else {
                delayLoadOldData(oldData);
            }
        }

        private void delayedFinish() {
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mIntroProgressPopup.setText("Retry. Check Network.");
                }
            }, 1000);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mIntroProgressPopup.setText("Will Finish.");
                }
            }, 2000);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Message msg = new Message();
                    msg.arg1 = MSG_FINISH;
                    mActivityHandler.dispatchMessage(msg);
                }
            }, 5000);
        }

        private void delayLoadOldData(final String oldData) {
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mIntroProgressPopup.setText("ERROR But Found OldData.");
                }
            }, 1000);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mIntroProgressPopup.dismiss();
                    dataLoad(oldData);
                }
            }, 2000);

        }

    });

}

From source file:com.z299studio.pb.HomeActivity.java

private void startHome() {
    getSupportFragmentManager().beginTransaction()
            .setCustomAnimations(R.anim.expand_from_right, R.anim.collapse_to_left)
            .replace(R.id.container, HomeFragment.create(), null).commit();
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override/*w ww  .j av  a2 s  . c o  m*/
        public void run() {
            mPwdEdit = (EditText) findViewById(R.id.password);
            popInput();
        }

    }, 300);
}

From source file:com.eugene.fithealthmaingit.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (savedInstanceState != null) {
        mNavItemId = savedInstanceState.getInt(NAV_ITEM_ID);
        isFirstFragmentAdded = savedInstanceState.getBoolean(FIRST_FRAGMENT_ADDED);
    } else {//  ww w . ja  va2 s . c o m
        mNavItemId = R.id.nav_journal;
    }

    mNavigationDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);

    // Set menu header text to User Name
    TextView mHeaderText = (TextView) findViewById(R.id.txtName);
    mHeaderText.setText(PreferenceManager.getDefaultSharedPreferences(this).getString(Globals.USER_NAME, ""));

    /**
     * Initiate NavigationView
     * Inflate Menu based on FitBit connection status
     */
    NavigationView mNavigationView = (NavigationView) findViewById(R.id.nav);

    if (PreferenceManager.getDefaultSharedPreferences(this).getString("FITBIT_ACCESS_TOKEN", "").equals("")) {
        mNavigationView.inflateMenu(R.menu.drawer);
    } else {
        mNavigationView.inflateMenu(R.menu.drawer_fitbit);
    }
    mNavigationView.getMenu().findItem(mNavItemId).setChecked(true);
    mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {
            if (menuItem.getItemId() != R.id.nav_settings) {
                mNavItemId = menuItem.getItemId();
                switchFragment(menuItem.getItemId());
                menuItem.setChecked(true);
                Fragment loading = new FragmentBlankLoading();
                Bundle b = new Bundle();
                b.putInt(NAV_ITEM_ID, mNavItemId);
                loading.setArguments(b);
                getSupportFragmentManager().beginTransaction().replace(R.id.container, loading).commit();
            } else {
                startActivity(new Intent(MainActivity.this, UserInformationActivity.class));
            }
            handleNavigationDrawer();
            return false;
        }
    });

    // Nav Menu Fonts
    Menu m = mNavigationView.getMenu();
    for (int i = 0; i < m.size(); i++) {
        MenuItem mi = m.getItem(i);

        //for aapplying a font to subMenu ...
        SubMenu subMenu = mi.getSubMenu();
        if (subMenu != null && subMenu.size() > 0) {
            for (int j = 0; j < subMenu.size(); j++) {
                MenuItem subMenuItem = subMenu.getItem(j);
                applyFontToMenuItem(subMenuItem);
            }
        }

        //the method we have create in activity
        applyFontToMenuItem(mi);
    }
    switchFragment(mNavItemId);

    /**
     * Handles Home Screen Widget
     * Search and Add
     */
    Intent widgetIntent = this.getIntent();
    if (widgetIntent != null) {
        if (widgetIntent.getAction() != null && savedInstanceState == null) {
            if (widgetIntent.getAction().equals(FitHealthWidget.ACTION_SEARCH)) {
                // Post delay to allow the app to open and not interfere with animation
                final Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getSupportFragmentManager().beginTransaction()
                                .replace(R.id.containerSearch, new FragmentSearch()).addToBackStack(null)
                                .commit();
                    }
                }, 100);
            }
            if (widgetIntent.getAction().equals(FitHealthWidget.ACTION_ADD)) {
                widgetAdd();
            }
        }
    }
}

From source file:emu.project64.SplashActivity.java

public void StartExtraction() {
    if (mInit) {/* w  ww.jav a  2 s  . c  o m*/
        return;
    }
    mInit = true;
    String ConfigFile = AndroidDevice.PACKAGE_DIRECTORY + "/Config/Project64.cfg";
    if ((new File(ConfigFile)).exists()) {
        InitProject64();
    }

    ((Project64Application) getApplication()).getDefaultTracker().send(
            new HitBuilders.EventBuilder().setCategory("start").setLabel(NativeExports.appVersion()).build());

    // Extract the assets in a separate thread and launch the menu activity
    // Handler.postDelayed ensures this runs only after activity has resumed
    Log.e("Splash", "extractAssetsTaskLauncher - startup");
    final Handler handler = new Handler();
    if (!mAppInit
            || NativeExports.UISettingsLoadDword(UISettingID.Asserts_Version.getValue()) != ASSET_VERSION) {
        handler.post(extractAssetsTaskLauncher);
    } else {
        handler.postDelayed(startGalleryLauncher, SPLASH_DELAY);
    }
}

From source file:com.userhook.util.UHOperation.java

public void registerPushToken(final String deviceToken, int retryCount) {

    Map<String, Object> params = new HashMap<>();
    if (UHUser.getUserId() != null) {
        params.put("user", UHUser.getUserId());
    } else {//from  www  . j ava2s  .co m

        // we need a userId to register for push messages
        if (retryCount < 2) {

            final int newRetryCount = retryCount++;

            // wait 5 seconds and then try to register
            Handler handler = new Handler(Looper.getMainLooper());
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    registerPushToken(deviceToken, newRetryCount);
                }
            }, 5000);

        }

        return;
    }

    params.put("os", "android");
    params.put("sdk", UserHook.UH_SDK_VERSION);
    params.put("token", deviceToken);
    params.put("timezone_offset", UHDeviceInfo.getTimezoneOffset());

    if (UHUser.getUserId() == null) {
        Log.e(UserHook.TAG, "cannot register push token if user is null");
        return;
    }

    UHPostAsyncTask task = new UHPostAsyncTask(params, new UHAsyncTask.UHAsyncTaskListener() {
        @Override
        public void onSuccess(String result) {

            if (result == null) {
                Log.e("uh", "error registering push token, response was null");
                return;
            }

            try {

                JSONObject json = new JSONObject(result);

                if (json.has("status") && json.getString("status").equalsIgnoreCase("success")
                        && json.getJSONObject("data") != null
                        && json.getJSONObject("data").getBoolean("registered")) {

                    Log.i("uh", "push token registered");

                } else {
                    Log.e("uh", "userhook response status was error for register push token");

                }

            } catch (Exception e) {
                Log.e("uh", "error registering push token", e);

            }

        }
    });

    task.execute(UserHook.UH_API_URL + UH_PATH_PUSH_REGISTER);

}

From source file:com.openlocationcode.android.main.MainActivity.java

/**
 * Handles intent URIs, extracts the query part and sends it to the search function.
 * <p/>/*w  ww  . j a v a  2s.  c  om*/
 * URIs may be of the form:
 * <ul>
 * <li>{@code geo:37.802,-122.41962}
 * <li>{@code geo:37.802,-122.41962?q=7C66CM4X%2BC34&z=20}
 * <li>{@code geo:0,0?q=WF59%2BX67%20Praia}
 * </ul>
 * <p/>
 * Only the query string is used. Coordinates and zoom level are ignored. If the query string
 * is not recognised by the search function (say, it's a street address), it will fail.
 */
private void handleGeoIntent(Intent intent) {
    Uri uri = intent != null ? intent.getData() : null;
    if (uri == null) {
        return;
    }
    String schemeSpecificPart = uri.getEncodedSchemeSpecificPart();
    if (schemeSpecificPart == null || schemeSpecificPart.isEmpty()) {
        return;
    }
    // Get everything after q=
    int queryIndex = schemeSpecificPart.indexOf(URI_QUERY_SEPARATOR);
    if (queryIndex == -1) {
        return;
    }
    String searchQuery = schemeSpecificPart.substring(queryIndex + 2);
    if (searchQuery.contains(URI_ZOOM_SEPARATOR)) {
        searchQuery = searchQuery.substring(0, searchQuery.indexOf(URI_ZOOM_SEPARATOR));
    }
    final String searchString = Uri.decode(searchQuery);
    Log.i(TAG, "Search string is " + searchString);

    // Give the map some time to get ready.
    Handler h = new Handler();
    Runnable r = new Runnable() {
        @Override
        public void run() {
            if (mMainPresenter.getSearchActionsListener().searchCode(searchString)) {
                mMainPresenter.getSearchActionsListener().setSearchText(searchString);
            }
        }
    };
    h.postDelayed(r, 2000);
}

From source file:com.github.volley_examples.Act_JsonRequest.java

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.act__json_request);

    lvWeather = (ListView) findViewById(R.id.lvWeather);

    mQueue = Volley.newRequestQueue(this);
    //getWeatherInfo();
    //{"weatherinfo":{"city":"","cityid":"101280101","temp":"12","WD":"","WS":"2","SD":"95%",
    //"WSE":"2","time":"21:05","isRadar":"1","Radar":"JC_RADAR_AZ9200_JB"}}

    final Handler handler = new Handler() {
        @Override/*from  w  w w .  jav  a  2 s .  c o m*/
        public void handleMessage(Message msg) {
            // super.handleMessage(msg);
            init();
        }
    };

    Runnable update_thread = new Runnable() {
        public void run() {
            getWeatherInfo();
            handler.sendEmptyMessageDelayed(99, 2000);

        }
    };

    handler.postDelayed(update_thread, 300);

}

From source file:de.uni_weimar.mheinz.androidtouchscope.TouchScopeActivity.java

public void onAuto(View view) {
    mLearningView.doAnim(LearningView.Controls.AUTO_BUTTON);

    final ToggleButton button = (ToggleButton) view;
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override/*  w  w w  .j  av  a2s.co  m*/
        public void run() {
            if (mActiveScope != null)
                mActiveScope.doCommand(ScopeInterface.Command.DO_AUTO, 0, true, button.isChecked());

            Log.i(TAG, "Auto Completed");
            button.setChecked(false);
        }
    }, 0);

    mCursorStruct.cursorMode = CursorStruct.CursorMode.OFF;
    setCursorModeState(CursorStruct.CursorMode.OFF);
    mScopeView.setCursorsState(mCursorStruct);
}

From source file:com.jungle.widgets.view.JungleLanternView.java

private void scheduleLanternSwitch() {
    if (mLanternSwitchRunnable != null) {
        final Handler handler = ThreadManager.getInstance().getUIHandler();
        handler.removeCallbacks(mLanternSwitchRunnable);
        handler.post(new Runnable() {
            @Override/*from w w  w .j ava2 s.co m*/
            public void run() {
                handler.postDelayed(mLanternSwitchRunnable, mSwitchIntervalMs);
            }
        });
    }
}

From source file:org.chromium.chrome.browser.autofill.CardUnmaskPrompt.java

private void onTooltipIconClicked() {
    // Don't show the popup if there's already one showing (or one has been dismissed
    // recently). This prevents a tap on the (?) from hiding and then immediately re-showing
    // the popup.
    if (mStoreLocallyTooltipPopup != null)
        return;// w w w  .  j a  v a 2  s . c o m

    mStoreLocallyTooltipPopup = new PopupWindow(mDialog.getContext());
    TextView text = new TextView(mDialog.getContext());
    text.setText(R.string.autofill_card_unmask_prompt_storage_tooltip);
    // Width is the dialog's width less the margins and padding around the checkbox and
    // icon.
    text.setWidth(mMainView.getWidth() - ViewCompat.getPaddingStart(mStoreLocallyCheckbox)
            - ViewCompat.getPaddingEnd(mStoreLocallyTooltipIcon)
            - MarginLayoutParamsCompat
                    .getMarginStart((RelativeLayout.LayoutParams) mStoreLocallyCheckbox.getLayoutParams())
            - MarginLayoutParamsCompat
                    .getMarginEnd((RelativeLayout.LayoutParams) mStoreLocallyTooltipIcon.getLayoutParams()));
    text.setTextColor(Color.WHITE);
    Resources resources = mDialog.getContext().getResources();
    int hPadding = resources.getDimensionPixelSize(R.dimen.autofill_card_unmask_tooltip_horizontal_padding);
    int vPadding = resources.getDimensionPixelSize(R.dimen.autofill_card_unmask_tooltip_vertical_padding);
    text.setPadding(hPadding, vPadding, hPadding, vPadding);

    mStoreLocallyTooltipPopup.setContentView(text);
    mStoreLocallyTooltipPopup.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
    mStoreLocallyTooltipPopup.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
    mStoreLocallyTooltipPopup.setOutsideTouchable(true);
    mStoreLocallyTooltipPopup.setBackgroundDrawable(
            ApiCompatibilityUtils.getDrawable(resources, R.drawable.store_locally_tooltip_background));
    mStoreLocallyTooltipPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
        @Override
        public void onDismiss() {
            Handler h = new Handler();
            h.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mStoreLocallyTooltipPopup = null;
                }
            }, 200);
        }
    });
    mStoreLocallyTooltipPopup.showAsDropDown(mStoreLocallyCheckbox,
            ViewCompat.getPaddingStart(mStoreLocallyCheckbox), 0);
    text.announceForAccessibility(text.getText());
}