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:org.wso2.carbon.iot.android.sense.beacon.BeaconDetactorService.java

@Override
public void onCreate() {
    super.onCreate();

    final Handler handler = new Handler();
    final Runnable runnable = new Runnable() {

        @Override/*from  ww w  . j av  a2 s.c  o m*/
        public void run() {
            //stopSelf();
        }
    };
    handler.postDelayed(runnable, 10000);
}

From source file:com.jmstudios.redmoon.receiver.AutomaticFilterChangeReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    if (DEBUG)//from  www  .ja  v  a  2  s .  c  om
        Log.i(TAG, "Alarm received");
    FilterCommandSender commandSender = new FilterCommandSender(context);
    FilterCommandFactory commandFactory = new FilterCommandFactory(context);
    Intent onCommand = commandFactory.createCommand(ScreenFilterService.COMMAND_ON);
    Intent pauseCommand = commandFactory.createCommand(ScreenFilterService.COMMAND_PAUSE);

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    SettingsModel settingsModel = new SettingsModel(context.getResources(), sharedPreferences);

    boolean turnOn = intent.getData().toString().equals("turnOnIntent");

    if (turnOn) {
        commandSender.send(onCommand);
        cancelTurnOnAlarm(context);
        scheduleNextOnCommand(context);
    } else {
        commandSender.send(pauseCommand);
        cancelPauseAlarm(context);
        scheduleNextPauseCommand(context);

        // We want to dismiss the notification if the filter is paused
        // automatically.
        // However, the filter fades out and the notification is only
        // refreshed when this animation has been completed.  To make sure
        // that the new notification is removed we create a new runnable to
        // be excecuted 100 ms after the filter has faded out.
        Handler handler = new Handler();

        DismissNotificationRunnable runnable = new DismissNotificationRunnable(context);
        handler.postDelayed(runnable, ScreenFilterPresenter.FADE_DURATION_MS + 100);
    }

    if (settingsModel.getAutomaticFilterMode().equals("sun")) {
        // Update times for the next time (fails silently)
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
                && ContextCompat.checkSelfPermission(context,
                        Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            LocationListener listener = new LocationUpdateListener(context);
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
        }
    }
}

From source file:com.orange.ocara.ui.activity.BaseActivityManagingAudit.java

public void showAuditObjectProgress(AuditObject auditObject, final boolean terminateActivityWhenDone) {
    CharSequence info = getText(com.orange.ocara.R.string.auditing_progress_info);

    Spannable auditingStatus = new SpannableString("");
    int color = getResources().getColor(com.orange.ocara.R.color.black);
    switch (auditObject.getResponse()) {
    case OK:/*from   w  ww . j ava 2 s .c om*/
        auditingStatus = new SpannableString(getText(com.orange.ocara.R.string.auditing_progress_status_ok));
        color = getResources().getColor(com.orange.ocara.R.color.green);
        break;
    case NOK:
        if (auditObject.hasAtLeastOneBlockingRule()) {
            auditingStatus = new SpannableString(
                    getText(com.orange.ocara.R.string.auditing_progress_status_nok));
            color = getResources().getColor(com.orange.ocara.R.color.red);
        } else {

            auditingStatus = new SpannableString(
                    getText(com.orange.ocara.R.string.auditing_progress_status_anoying));
            color = getResources().getColor(com.orange.ocara.R.color.orange);
        }
        break;
    case DOUBT:
        auditingStatus = new SpannableString(getText(com.orange.ocara.R.string.auditing_progress_status_doubt));
        color = getResources().getColor(com.orange.ocara.R.color.yellow);
        break;
    case NoAnswer:
        auditingStatus = new SpannableString(
                getText(com.orange.ocara.R.string.auditing_progress_status_no_answer));
        color = getResources().getColor(com.orange.ocara.R.color.blue);
        break;
    }

    auditingStatus.setSpan(new ForegroundColorSpan(color), info.length(), auditingStatus.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    StringBuffer stringBuffer = new StringBuffer(info);
    stringBuffer.append("<br>").append(auditingStatus);

    // get application preference to know if he wants to audit object now

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    int displayAuditingProgessDialog = Integer.parseInt(sharedPreferences
            .getString(getString(com.orange.ocara.R.string.setting_display_auditing_progress_key), "1"));

    switch (displayAuditingProgessDialog) {
    case 1:
        final NotificationDialogBuilder dialogBuilder = new NotificationDialogBuilder(this);
        final AlertDialog dialog = dialogBuilder.setInfo(auditingStatus)
                .setOption(getString(com.orange.ocara.R.string.auditing_progress_option)).setCancelable(false)
                .setTitle(com.orange.ocara.R.string.auditing_progress_title)
                .setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {

                        auditingProgressDismiss(dialogBuilder.getOptionValue());

                        if (terminateActivityWhenDone) {
                            BaseActivityManagingAudit.this.finish();
                        }
                    }
                }).setPositiveButton(com.orange.ocara.R.string.action_close, null).create();

        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                dialog.dismiss();
            }

        }, 3500);
        dialog.show();

        break;
    default:
        if (terminateActivityWhenDone) {
            BaseActivityManagingAudit.this.finish();
        }
        break;
    }

}

From source file:dk.spaceblog.thenicobomb.MainActivity.java

/** Called when the user clicks the Send button */
public void sendNicoBomb(View view) {
    // Do something in response to button
    Log.d("NicoBomb:MainActivity", "Nico Bomb activated!");

    // First check whether there is any text entered ..
    EditText editText = (EditText) findViewById(R.id.edit_message);
    if (editText.getText().toString().length() >= 1) {
        textMessage = editText.getText().toString();
    } else {//from  www  .  j  av a2  s .  co m
        Toast.makeText(this, "You have to enter a message, dickhead !", Toast.LENGTH_SHORT).show();
    }

    // First check whether there is any number entered ..
    EditText editText2 = (EditText) findViewById(R.id.phone_number);
    if (editText2.getText().toString().length() >= 1) {
        phoneNumber = editText2.getText().toString();
    } else {
        Toast.makeText(this, "You have to enter a phone number, you idiot!", Toast.LENGTH_SHORT).show();
    }
    // We display a notification if there is a message
    if (null != textMessage && null != phoneNumber) {
        //Small message to confirm that the NicoBomb started
        Toast.makeText(this, "TheNicoBomb started!", Toast.LENGTH_SHORT).show();
        for (int i = 0; i < repeat; i++) {
            // Execute some code after 2 seconds have passed
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                public void run() {
                    Log.d("NicoBomb:MainActivity", "Delay loop entered");
                    sendSMSMessage();
                }
            }, delay + i * interval);
        }
    }
}

From source file:gao.shun.sg.classicalmusicquiz.QuizActivity.java

/**
 * The OnClick method for all of the answer buttons. The method uses the index of the button
 * in button array to to get the ID of the sample from the array of question IDs. It also
 * toggles the UI to show the correct answer.
 *
 * @param v The button that was clicked.
 *///  w  ww  . j  av  a  2 s  .c  om
@Override
public void onClick(View v) {

    // Show the correct answer.
    showCorrectAnswer();

    // Get the button that was pressed.
    Button pressedButton = (Button) v;

    // Get the index of the pressed button
    int userAnswerIndex = -1;
    for (int i = 0; i < mButtons.length; i++) {
        if (pressedButton.getId() == mButtonIDs[i]) {
            userAnswerIndex = i;
        }
    }

    // Get the ID of the sample that the user selected.
    int userAnswerSampleID = mQuestionSampleIDs.get(userAnswerIndex);

    // If the user is correct, increase there score and update high score.
    if (QuizUtils.userCorrect(mAnswerSampleID, userAnswerSampleID)) {
        mCurrentScore++;
        QuizUtils.setCurrentScore(this, mCurrentScore);
        if (mCurrentScore > mHighScore) {
            mHighScore = mCurrentScore;
            QuizUtils.setHighScore(this, mHighScore);
        }
    }

    // Remove the answer sample from the list of all samples, so it doesn't get asked again.
    mRemainingSampleIDs.remove(Integer.valueOf(mAnswerSampleID));

    // Wait some time so the user can see the correct answer, then go to the next question.
    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            simpleExoPlayer.stop();
            Intent nextQuestionIntent = new Intent(QuizActivity.this, QuizActivity.class);
            nextQuestionIntent.putExtra(REMAINING_SONGS_KEY, mRemainingSampleIDs);
            finish();
            startActivity(nextQuestionIntent);
        }
    }, CORRECT_ANSWER_DELAY_MILLIS);

}

From source file:com.hmatalonga.greenhub.ui.MainActivity.java

private void refreshStatus() {
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override/*from w  w  w.  ja va2s . com*/
        public void run() {
            EventBus.getDefault().post(new StatusEvent(getString(R.string.event_idle)));
        }
    }, Config.REFRESH_STATUS_ERROR);
}

From source file:com.bluros.music.fragments.ArtistDetailFragment.java

private void setUpArtistDetails() {

    final Artist artist = ArtistLoader.getArtist(getActivity(), artistID);

    collapsingToolbarLayout.setTitle(artist.name);

    LastFmClient.getInstance(getActivity()).getArtistInfo(new ArtistQuery(artist.name),
            new ArtistInfoListener() {
                @Override//from   w ww  . ja va 2s.co  m
                public void artistInfoSucess(final LastfmArtist artist) {
                    if (artist != null) {

                        ImageLoader.getInstance().displayImage(artist.mArtwork.get(4).mUrl, artistArt,
                                new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisk(true)
                                        .showImageOnFail(R.drawable.ic_empty_music2).build(),
                                new SimpleImageLoadingListener() {
                                    @Override
                                    public void onLoadingComplete(String imageUri, View view,
                                            Bitmap loadedImage) {
                                        largeImageLoaded = true;
                                        try {
                                            new Palette.Builder(loadedImage)
                                                    .generate(new Palette.PaletteAsyncListener() {
                                                        @Override
                                                        public void onGenerated(Palette palette) {
                                                            Palette.Swatch swatch = palette.getVibrantSwatch();
                                                            if (swatch != null) {
                                                                primaryColor = swatch.getRgb();
                                                                collapsingToolbarLayout
                                                                        .setContentScrimColor(primaryColor);
                                                                if (getActivity() != null)
                                                                    ATEUtils.setStatusBarColor(getActivity(),
                                                                            Helpers.getATEKey(getActivity()),
                                                                            primaryColor);
                                                            } else {
                                                                Palette.Swatch swatchMuted = palette
                                                                        .getMutedSwatch();
                                                                if (swatchMuted != null) {
                                                                    primaryColor = swatchMuted.getRgb();
                                                                    collapsingToolbarLayout
                                                                            .setContentScrimColor(primaryColor);
                                                                    if (getActivity() != null)
                                                                        ATEUtils.setStatusBarColor(
                                                                                getActivity(),
                                                                                Helpers.getATEKey(
                                                                                        getActivity()),
                                                                                primaryColor);
                                                                }
                                                            }

                                                        }
                                                    });
                                        } catch (Exception ignored) {

                                        }
                                    }
                                });
                        Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                setBlurredPlaceholder(artist);
                            }
                        }, 100);

                    }
                }

                @Override
                public void artistInfoFailed() {

                }
            });

}

From source file:com.musiqueplayer.playlistequalizerandroidwear.fragments.ArtistDetailFragment.java

private void setUpArtistDetails() {

    final Artist artist = ArtistLoader.getArtist(getActivity(), artistID);

    collapsingToolbarLayout.setTitle(artist.name);

    LastFmClient.getInstance(getActivity()).getArtistInfo(new ArtistQuery(artist.name),
            new ArtistInfoListener() {
                @Override//from www  .  j av  a  2s.c  o m
                public void artistInfoSucess(final LastfmArtist artist) {
                    if (artist != null) {

                        ImageLoader.getInstance().displayImage(artist.mArtwork.get(4).mUrl, artistArt,
                                new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisk(true)
                                        .showImageOnFail(R.drawable.icons).build(),
                                new SimpleImageLoadingListener() {
                                    @Override
                                    public void onLoadingComplete(String imageUri, View view,
                                            Bitmap loadedImage) {
                                        largeImageLoaded = true;
                                        try {
                                            new Palette.Builder(loadedImage)
                                                    .generate(new Palette.PaletteAsyncListener() {
                                                        @Override
                                                        public void onGenerated(Palette palette) {
                                                            Palette.Swatch swatch = palette.getVibrantSwatch();
                                                            if (swatch != null) {
                                                                primaryColor = swatch.getRgb();
                                                                collapsingToolbarLayout
                                                                        .setContentScrimColor(primaryColor);
                                                                if (getActivity() != null)
                                                                    ATEUtils.setStatusBarColor(getActivity(),
                                                                            Helpers.getATEKey(getActivity()),
                                                                            primaryColor);
                                                            } else {
                                                                Palette.Swatch swatchMuted = palette
                                                                        .getMutedSwatch();
                                                                if (swatchMuted != null) {
                                                                    primaryColor = swatchMuted.getRgb();
                                                                    collapsingToolbarLayout
                                                                            .setContentScrimColor(primaryColor);
                                                                    if (getActivity() != null)
                                                                        ATEUtils.setStatusBarColor(
                                                                                getActivity(),
                                                                                Helpers.getATEKey(
                                                                                        getActivity()),
                                                                                primaryColor);
                                                                }
                                                            }

                                                        }
                                                    });
                                        } catch (Exception ignored) {

                                        }
                                    }
                                });
                        Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                setBlurredPlaceholder(artist);
                            }
                        }, 100);

                    }
                }

                @Override
                public void artistInfoFailed() {

                }
            });

}

From source file:com.rohan.app.fragments.ArtistDetailFragment.java

private void setUpArtistDetails() {

    final Artist artist = ArtistLoader.getArtist(getActivity(), artistID);

    collapsingToolbarLayout.setTitle(artist.name);

    LastFmClient.getInstance(getActivity()).getArtistInfo(new ArtistQuery(artist.name),
            new ArtistInfoListener() {
                @Override//from   w  w  w . j av  a2  s.c  o m
                public void artistInfoSucess(final LastfmArtist artist) {
                    if (artist != null) {

                        ImageLoader.getInstance().displayImage(artist.mArtwork.get(4).mUrl, artistArt,
                                new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisk(true)
                                        .showImageOnFail(R.drawable.ic_dribble).build(),
                                new SimpleImageLoadingListener() {
                                    @Override
                                    public void onLoadingComplete(String imageUri, View view,
                                            Bitmap loadedImage) {
                                        largeImageLoaded = true;
                                        try {
                                            new Palette.Builder(loadedImage)
                                                    .generate(new Palette.PaletteAsyncListener() {
                                                        @Override
                                                        public void onGenerated(Palette palette) {
                                                            Palette.Swatch swatch = palette.getVibrantSwatch();
                                                            if (swatch != null) {
                                                                primaryColor = swatch.getRgb();
                                                                collapsingToolbarLayout
                                                                        .setContentScrimColor(primaryColor);
                                                                if (getActivity() != null)
                                                                    ATEUtils.setStatusBarColor(getActivity(),
                                                                            Helpers.getATEKey(getActivity()),
                                                                            primaryColor);
                                                            } else {
                                                                Palette.Swatch swatchMuted = palette
                                                                        .getMutedSwatch();
                                                                if (swatchMuted != null) {
                                                                    primaryColor = swatchMuted.getRgb();
                                                                    collapsingToolbarLayout
                                                                            .setContentScrimColor(primaryColor);
                                                                    if (getActivity() != null)
                                                                        ATEUtils.setStatusBarColor(
                                                                                getActivity(),
                                                                                Helpers.getATEKey(
                                                                                        getActivity()),
                                                                                primaryColor);
                                                                }
                                                            }

                                                        }
                                                    });
                                        } catch (Exception ignored) {

                                        }
                                    }
                                });
                        Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                setBlurredPlaceholder(artist);
                            }
                        }, 100);

                    }
                }

                @Override
                public void artistInfoFailed() {

                }
            });

}

From source file:org.apache.cordova.SplashScreenInternal.java

/**
 * Shows the splash screen over the full Activity
 *//*from  w  ww .j  a  v a  2s.com*/
@SuppressWarnings("deprecation")
private void showSplashScreen(final boolean hideAfterDelay) {
    final int splashscreenTime = preferences.getInteger("SplashScreenDelay", 3000);
    final int drawableId = preferences.getInteger("SplashDrawableId", 0);

    // If the splash dialog is showing don't try to show it again
    if (this.splashDialog != null && splashDialog.isShowing()) {
        return;
    }
    if (drawableId == 0 || (splashscreenTime <= 0 && hideAfterDelay)) {
        return;
    }

    cordova.getActivity().runOnUiThread(new Runnable() {
        public void run() {
            // Get reference to display
            Display display = cordova.getActivity().getWindowManager().getDefaultDisplay();
            Context context = webView.getContext();

            // Create the layout for the dialog
            LinearLayout root = new LinearLayout(context);
            root.setMinimumHeight(display.getHeight());
            root.setMinimumWidth(display.getWidth());
            root.setOrientation(LinearLayout.VERTICAL);

            // TODO: Use the background color of the webview's parent instead of using the
            // preference.
            root.setBackgroundColor(preferences.getInteger("backgroundColor", Color.BLACK));
            root.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT, 0.0F));
            root.setBackgroundResource(drawableId);

            // Create and show the dialog
            splashDialog = new Dialog(context, android.R.style.Theme_Translucent_NoTitleBar);
            // check to see if the splash screen should be full screen
            if ((cordova.getActivity().getWindow().getAttributes().flags
                    & WindowManager.LayoutParams.FLAG_FULLSCREEN) == WindowManager.LayoutParams.FLAG_FULLSCREEN) {
                splashDialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                        WindowManager.LayoutParams.FLAG_FULLSCREEN);
            }
            splashDialog.setContentView(root);
            splashDialog.setCancelable(false);
            splashDialog.show();

            // Set Runnable to remove splash screen just in case
            if (hideAfterDelay) {
                final Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    public void run() {
                        removeSplashScreen();
                    }
                }, splashscreenTime);
            }
        }
    });
}