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.intel.xdk.player.Player.java

public void playSound(final String strRelativeFileURL) {
    Integer id = soundPoolMapName2Id.get(strRelativeFileURL);

    if (id == null) {
        Object path = pathToFile(strRelativeFileURL);
        if (path instanceof AssetFileDescriptor) {
            id = soundPool.load((AssetFileDescriptor) path, 1);
        } else {/*from ww  w .  j  a  va2  s. co m*/
            id = soundPool.load((String) path, 1);
        }
        if (id == 0) { // unable to load the sound
            return;
        }
        soundPoolMapName2Id.put(strRelativeFileURL, id);
        soundPoolMapId2Name.put(id, strRelativeFileURL);
        soundPoolShouldPlay.put(strRelativeFileURL, true);

        //hack for pre-froyo: wait 250 ms to play sound first time through
        if (!hasLoadSoundCallback) {
            final int soundId = id;
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {

                public void run() {
                    soundLoaded(soundId, 0);
                }

            }, 250);
        }
    } else {
        playSoundById(id.intValue());
    }
}

From source file:org.dharmaseed.android.PlayTalkActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_play_talk);

    // Turn on action bar up/home button
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
    }//  w ww .  j  a va  2s .c  om

    // Get the ID of the talk to display
    Intent i = getIntent();
    talkID = (int) i.getLongExtra(NavigationActivity.TALK_DETAIL_EXTRA, 0);

    dbManager = DBManager.getInstance(this);

    // only hit the DB again if we know the talk is different than the one
    // we have saved.
    // for example, if the user selects a talk, exits, and re-opens it, no need
    // to hit the DB again, since we already have that talk saved
    if (talk == null || talk.getId() != talkID) {
        Cursor cursor = getCursor();
        if (cursor.moveToFirst()) {
            // convert DB result to an object
            talk = new Talk(cursor);
            talk.setId(talkID);
        } else {
            Log.e(LOG_TAG, "Could not look up talk, id=" + talkID);
            cursor.close();
            return;
        }
        cursor.close();
    } // else we already have the talk, just re-draw the page

    // Set the talk title
    TextView titleView = (TextView) findViewById(R.id.play_talk_talk_title);
    titleView.setText(talk.getTitle());

    // Set the teacher name
    TextView teacherView = (TextView) findViewById(R.id.play_talk_teacher);
    teacherView.setText(talk.getTeacherName());

    // Set the center name
    TextView centerView = (TextView) findViewById(R.id.play_talk_center);
    centerView.setText(talk.getCenterName());

    // Set the talk description
    TextView descriptionView = (TextView) findViewById(R.id.play_talk_talk_description);
    descriptionView.setText(talk.getDescription());

    // Set teacher photo
    String photoFilename = talk.getPhotoFileName();
    ImageView photoView = (ImageView) findViewById(R.id.play_talk_teacher_photo);
    Log.i(LOG_TAG, "photoFilename: " + photoFilename);
    try {
        FileInputStream photo = openFileInput(photoFilename);
        photoView.setImageBitmap(BitmapFactory.decodeStream(photo));
    } catch (FileNotFoundException e) {
        Drawable icon = ContextCompat.getDrawable(this, R.drawable.dharmaseed_icon);
        photoView.setImageDrawable(icon);
    }

    // set the image of the download button based on whether the talk is
    // downloaded or not
    toggleDownloadImage();

    // Set date
    TextView dateView = (TextView) findViewById(R.id.play_talk_date);
    String recDate = talk.getDate();
    SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try {
        dateView.setText(DateFormat.getDateInstance().format(parser.parse(recDate)));
    } catch (ParseException e) {
        dateView.setText("");
        Log.w(LOG_TAG, "Could not parse talk date for talk ID " + talkID);
    }

    // Get/create a persistent fragment to manage the MediaPlayer instance
    FragmentManager fm = getSupportFragmentManager();
    talkPlayerFragment = (TalkPlayerFragment) fm.findFragmentByTag("talkPlayerFragment");
    if (talkPlayerFragment == null) {
        // add the fragment
        talkPlayerFragment = new TalkPlayerFragment();
        fm.beginTransaction().add(talkPlayerFragment, "talkPlayerFragment").commit();
    } else if (talkPlayerFragment.getMediaPlayer().isPlaying()) {
        setPPButton("ic_media_pause");
    }

    // Set the talk duration
    final TextView durationView = (TextView) findViewById(R.id.play_talk_talk_duration);
    double duration = talk.getDurationInMinutes();
    String durationStr = DateUtils.formatElapsedTime((long) (duration * 60));
    durationView.setText(durationStr);

    // Start a handler to periodically update the seek bar and talk time
    final SeekBar seekBar = (SeekBar) findViewById(R.id.play_talk_seek_bar);
    seekBar.setMax((int) (duration * 60 * 1000));
    userDraggingSeekBar = false;
    userSeekBarPosition = 0;
    seekBar.setOnSeekBarChangeListener(this);
    final Handler handler = new Handler();
    final MediaPlayer mediaPlayer = talkPlayerFragment.getMediaPlayer();
    handler.post(new Runnable() {
        @Override
        public void run() {
            handler.postDelayed(this, 1000);
            if (talkPlayerFragment.getMediaPrepared() && !userDraggingSeekBar) {
                try {
                    int pos = mediaPlayer.getCurrentPosition();
                    int mpDuration = mediaPlayer.getDuration();
                    seekBar.setMax(mpDuration);
                    seekBar.setProgress(pos);
                    String posStr = DateUtils.formatElapsedTime(pos / 1000);
                    String mpDurStr = DateUtils.formatElapsedTime(mpDuration / 1000);
                    durationView.setText(posStr + "/" + mpDurStr);
                } catch (IllegalStateException e) {
                }
            }
        }
    });
}

From source file:org.storymaker.app.PublishFragment.java

@Override
public void jobSucceeded(Job job) {
    PublishJob publishJob = job.getPublishJob();
    if (job.getType().equals(JobTable.TYPE_RENDER)) {
        if (mPlaying) {
            showUploadSpinner(false);/*from  w w w.  j av  a2s  .  c o  m*/
            showPlaySpinner(false);

            String path = publishJob.getLastRenderFilePath(); // FIXME this can be null
            if (path != null) { // FIXME this won't work when a upload job succeeds
                mFileLastExport = new File(path);
                Handler handlerTimer = new Handler();
                mProgressText.setText("Complete!");
                handlerTimer.postDelayed(new Runnable() {
                    public void run() {
                        showPlayAndUpload(true);
                    }
                }, 200);
            } else {
                Timber.d("last rendered path is empty!");
            }

            if (mFileLastExport != null && mFileLastExport.exists()) { // FIXME replace this with a check to make sure render is suitable
                mActivity.mMPM.mMediaHelper.playMedia(mFileLastExport, null);
            }
            mPlaying = false;
        }
        if (mUploading) {
            startUpload(publishJob);
        }
    } else if (job.getType().equals(JobTable.TYPE_UPLOAD)) {
        // FIXME ???
    }
}

From source file:com.cranberrygame.cordova.plugin.ad.admob.Util.java

private void addEvent_split() {
    if (bannerView != null) {
        //if banner is showing
        ViewGroup parentView = (ViewGroup) bannerView.getParent();
        if (parentView != null) {
            //parentView.removeView(bannerView);
            //bannerView.destroy();
            //bannerView = null;
            Log.d(LOG_TAG, String.format("position: %s, size: %s", position, size));
            //Util.alert(cordova.getActivity(), String.format("position: %s, size: %s", position, size));

            //http://stackoverflow.com/questions/3072173/how-to-call-a-method-after-a-delay-in-android
            final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override// w  w  w.j av  a2  s .co  m
                public void run() {
                    _showBannerAd(position, size);
                }
            }, 1);//after 1ms            
        }
    }
}

From source file:com.cranberrygame.cordova.plugin.ad.admob.Util.java

private void addEvent_overlap() {
    //http://stackoverflow.com/questions/11281562/android-admob-resize-on-landscape
    if (bannerView != null) {
        //if banner is showing
        RelativeLayout bannerViewLayout = (RelativeLayout) bannerView.getParent();
        if (bannerViewLayout != null) {
            //bannerViewLayout.removeView(bannerView);
            //bannerView.destroy();
            //bannerView = null;            
            Log.d(LOG_TAG, String.format("position: %s, size: %s", position, size));
            //Util.alert(cordova.getActivity(), String.format("position: %s, size: %s", position, size));

            //http://stackoverflow.com/questions/3072173/how-to-call-a-method-after-a-delay-in-android
            final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override//from   w  w  w . ja va2s  .  c  o m
                public void run() {
                    _showBannerAd(position, size);
                }
            }, 1);//after 1ms
        }
    }
}

From source file:com.synox.android.ui.fragment.OCFileListFragment.java

/**
 * {@inheritDoc}//from   ww w  .  j  a  v  a2 s. c o m
 */
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    setHasOptionsMenu(true);

    Bundle args = getArguments();
    mJustFolders = (args != null) && args.getBoolean(ARG_JUST_FOLDERS, false);

    final Handler h = new Handler();

    // New file fab on click listener
    newFileFab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            fabMenu.close(true);
            h.postDelayed(new Runnable() {
                @Override
                public void run() {
                    UploadSourceDialogFragment dialog = UploadSourceDialogFragment
                            .newInstance(((FileDisplayActivity) getActivity()).getAccount());
                    dialog.show(getActivity().getSupportFragmentManager(), DIALOG_UPLOAD_SOURCE);
                }
            }, 250);
        }
    });

    // New folder on click listener
    newFolderFab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            fabMenu.close(true);
            h.postDelayed(new Runnable() {
                @Override
                public void run() {
                    CreateFolderDialogFragment dialog = CreateFolderDialogFragment
                            .newInstance(getCurrentFile());
                    dialog.show(getActivity().getSupportFragmentManager(), DIALOG_CREATE_FOLDER);
                }
            }, 250);
        }
    });

    mAdapter = new FileListListAdapter(getContext(), this, mContainerActivity);
    setListAdapter(mAdapter);
    mAdapter.notifyDataSetChanged();

    if (mJustFolders) {
        fabMenu.hideMenu(false);
        fabMenu = null;
    }
}

From source file:org.mitre.svmp.activities.AppRTCVideoActivity.java

private void createTopPanel() {
    // TODO Auto-generated method stub

    ll.setOnClickListener(new View.OnClickListener() {

        @Override/*from   www  .  ja va  2 s  . c  o  m*/
        public void onClick(View v) {
            // TODO Auto-generated method stub

        }
    });

    ImageView homeStreamingBtn = (ImageView) findViewById(R.id.homeStreamingBtn);
    homeStreamingBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            Intent intent = new Intent(AppRTCVideoActivity.this, OvalDrawerActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
            disconnectAndExit();

        }
    });
    ImageView stopStreamingBtn = (ImageView) findViewById(R.id.stopStreamingBtn);

    stopStreamingBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            disconnectAndExit();
        }
    });

    scrollUpImgVw.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            // TODO Auto-generated method stub
            if (scrollClicked == false) {
                scrollClicked = true;
                Vibrator vb = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                vb.vibrate(50);
                //   vsv.onPause();
                vsvProgrssBar.setVisibility(View.VISIBLE);

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

                    @Override
                    public void run() {
                        vsvProgrssBar.setVisibility(View.INVISIBLE);
                        //   vsv.onResume();
                        scrollClicked = false;
                    }
                }, 2000);

                SVMPProtocol.Request.Builder msg = SVMPProtocol.Request.newBuilder();
                SVMPProtocol.TouchEvent.Builder eventmsg = SVMPProtocol.TouchEvent.newBuilder();

                eventmsg.setAction(51);
                msg.setType(RequestType.TOUCHEVENT);
                msg.addTouch(eventmsg); // TODO: batch touch events

                // Send touch event to VM

                sendMessage(msg.build());
            }

        }
    });

    scrolldownImgVw.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            // TODO Auto-generated method stub
            if (scrollClicked == false) {
                scrollClicked = true;

                Vibrator vb = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                vb.vibrate(50);
                //   vsv.onPause();
                vsvProgrssBar.setVisibility(View.VISIBLE);

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

                    @Override
                    public void run() {
                        vsvProgrssBar.setVisibility(View.INVISIBLE);
                        //vsv.onResume();
                        scrollClicked = false;
                    }
                }, 2000);

                SVMPProtocol.Request.Builder msg = SVMPProtocol.Request.newBuilder();
                SVMPProtocol.TouchEvent.Builder eventmsg = SVMPProtocol.TouchEvent.newBuilder();

                eventmsg.setAction(50);
                msg.setType(RequestType.TOUCHEVENT);
                msg.addTouch(eventmsg); // TODO: batch touch events

                // Send touch event to VM

                sendMessage(msg.build());
            }

        }
    });

    ((ViewGroup) scrollBtnsRLayout.getParent()).removeView(scrollBtnsRLayout);

    ((ViewGroup) ll.getParent()).removeView(ll);

}

From source file:org.matrix.androidsdk.fragments.MatrixMessagesFragment.java

/**
 * Warn the listener that this fragment is ready.
 *///from   ww  w . j av  a  2 s  . c  o m
private void sendInitialMessagesLoaded() {
    final android.os.Handler handler = new android.os.Handler(Looper.getMainLooper());

    // add a delay to avoid calling MatrixListFragment before it is fully initialized
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            if (null != mMatrixMessagesListener) {
                mMatrixMessagesListener.onInitialMessagesLoaded();
            }
        }
    }, 100);
}

From source file:org.videolan.vlc.gui.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    if (!LibVlcUtil.hasCompatibleCPU(this)) {
        Log.e(TAG, LibVlcUtil.getErrorMsg());
        Intent i = new Intent(this, CompatErrorActivity.class);
        startActivity(i);/*w  w w .  j  a v  a 2  s. co m*/
        finish();
        super.onCreate(savedInstanceState);
        return;
    }

    /* Get the current version from package */
    PackageInfo pinfo = null;
    try {
        pinfo = getPackageManager().getPackageInfo(getPackageName(), 0);
    } catch (NameNotFoundException e) {
        Log.e(TAG, "package info not found.");
    }
    if (pinfo != null)
        mVersionNumber = pinfo.versionCode;

    /* Get settings */
    mSettings = PreferenceManager.getDefaultSharedPreferences(this);

    /* Check if it's the first run */
    mFirstRun = mSettings.getInt(PREF_FIRST_RUN, -1) != mVersionNumber;
    if (mFirstRun) {
        Editor editor = mSettings.edit();
        editor.putInt(PREF_FIRST_RUN, mVersionNumber);
        editor.commit();
    }

    try {
        // Start LibVLC
        Util.getLibVlcInstance();
    } catch (LibVlcException e) {
        e.printStackTrace();
        Intent i = new Intent(this, CompatErrorActivity.class);
        i.putExtra("runtimeError", true);
        i.putExtra("message", "LibVLC failed to initialize (LibVlcException)");
        startActivity(i);
        finish();
        super.onCreate(savedInstanceState);
        return;
    }

    super.onCreate(savedInstanceState);

    /*** Start initializing the UI ***/

    /* Enable the indeterminate progress feature */
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

    // Set up the sliding menu
    setContentView(R.layout.sliding_menu);
    mMenu = (SlidingMenu) findViewById(R.id.sliding_menu);
    changeMenuOffset();

    View v_main = LayoutInflater.from(this).inflate(R.layout.main, null);
    mMenu.setContent(v_main);

    View sidebar = LayoutInflater.from(this).inflate(R.layout.sidebar, null);
    final ListView listView = (ListView) sidebar.findViewById(android.R.id.list);
    listView.setFooterDividersEnabled(true);
    mSidebarAdapter = new SidebarAdapter();
    listView.setAdapter(mSidebarAdapter);
    mMenu.setMenu(sidebar);

    /* Initialize UI variables */
    mInfoLayout = v_main.findViewById(R.id.info_layout);
    mInfoProgress = (ProgressBar) v_main.findViewById(R.id.info_progress);
    mInfoText = (TextView) v_main.findViewById(R.id.info_text);

    /* Set up the action bar */
    mActionBar = getSupportActionBar();
    mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    mActionBar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
    mActionBar.setDisplayHomeAsUpEnabled(true);

    /* Add padding between the home button and the arrow */
    ImageView home = (ImageView) findViewById(Util.isHoneycombOrLater() ? android.R.id.home : R.id.abs__home);
    if (home != null)
        home.setPadding(20, 0, 0, 0);

    /* Set up the sidebar click listener */
    listView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            SidebarAdapter.SidebarEntry entry = (SidebarEntry) listView.getItemAtPosition(position);
            Fragment current = getSupportFragmentManager().findFragmentById(R.id.fragment_placeholder);

            if (current == null || current.getTag().equals(entry.id)) { /* Already selected */
                mMenu.showContent();
                return;
            }

            /*
             * Clear any backstack before switching tabs. This avoids
             * activating an old backstack, when a user hits the back button
             * to quit
             */
            for (int i = 0; i < getSupportFragmentManager().getBackStackEntryCount(); i++) {
                getSupportFragmentManager().popBackStack();
            }

            /**
             * Do not move this getFragment("audio")!
             * This is to ensure that if audio is not already loaded, it
             * will be loaded ahead of the detach/attach below.
             * Otherwise if you add() a fragment after an attach/detach,
             * it will take over the placeholder and you will end up with
             * the audio fragment when some other fragment should be there.
             */
            Fragment audioFragment = getFragment("audio");

            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.detach(current);
            ft.attach(getFragment(entry.id));
            ft.commit();
            mCurrentFragment = entry.id;

            /*
             * Set user visibility hints to work around weird Android
             * behaviour of duplicate context menu events.
             */
            current.setUserVisibleHint(false);
            getFragment(mCurrentFragment).setUserVisibleHint(true);
            // HACK ALERT: Set underlying audio browser to be invisible too.
            if (current.getTag().equals("tracks"))
                audioFragment.setUserVisibleHint(false);

            mMenu.showContent();
        }
    });

    /* Set up the mini audio player */
    // TODO use mini player
    //        mAudioPlayer = new AudioMiniPlayer(); 
    mAudioController = MediaServiceController.getInstance();
    //        mAudioPlayer.setAudioPlayerControl(mAudioController);
    //        mAudioPlayer.update();
    //
    //        getSupportFragmentManager().beginTransaction()
    //            .replace(R.id.audio_mini_player, mAudioPlayer)
    //            .commit();

    /* Show info/alpha/beta Warning */
    if (mSettings.getInt(PREF_SHOW_INFO, -1) != mVersionNumber)
        showInfoDialog();
    else if (mFirstRun) {
        /*
         * The sliding menu is automatically opened when the user closes
         * the info dialog. If (for any reason) the dialog is not shown,
         * open the menu after a short delay.
         */
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mMenu.showMenu();
            }
        }, 500);
    }

    /* Prepare the progressBar */
    IntentFilter filter = new IntentFilter();
    filter.addAction(ACTION_SHOW_PROGRESSBAR);
    filter.addAction(ACTION_HIDE_PROGRESSBAR);
    filter.addAction(ACTION_SHOW_TEXTINFO);
    registerReceiver(messageReceiver, filter);

    /* Reload the latest preferences */
    reloadPreferences();
}

From source file:io.v.android.apps.reader.db.SyncbaseDB.java

/**
 * Creates a syncgroup at cloudsync with the following name:
 * "users/[user_email]/reader/cloudsync/%%sync/cloudsync"
 *//*from  www. j a  v  a 2s  . co m*/
private void createSyncgroup(Database db) {
    mSyncgroupName = NamingUtil.join("users", mUsername, "reader/cloudsync/%%sync/cloudsync");

    Syncgroup group = db.getSyncgroup(mSyncgroupName);

    List<TableRow> prefixes = ImmutableList.of(new TableRow(TABLE_FILES, ""), new TableRow(TABLE_DEVICES, ""),
            new TableRow(TABLE_DEVICE_SETS, ""));

    List<String> mountTables = ImmutableList.of(NamingUtil.join("users", mUsername, "reader/rendezvous"));

    SyncgroupSpec spec = new SyncgroupSpec("reader syncgroup", mPermissions, prefixes, mountTables, false);

    try {
        sync(group.create(mVContext, spec, new SyncgroupMemberInfo()));
        Log.i(TAG, "Syncgroup is created successfully.");
    } catch (ExistException e) {
        Log.i(TAG, "Syncgroup already exists.");
    } catch (VException e) {
        handleError("Syncgroup could not be created: " + e.getMessage());
        return;
    }

    // TODO(youngseokyoon): investigate why this is needed.
    // Join the syncgroup a few seconds later to make sure that the syncgroup is ready.
    Handler handler = new Handler();
    handler.postDelayed(() -> joinSyncgroup(), SYNCGROUP_JOIN_DELAY);
}