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.rks.musicx.services.MusicXService.java

/**
 * Fade In/*from   ww  w  .  ja va  2s  . com*/
 *
 * @param _player
 * @param duration
 */
public void fadeIn(final MediaPlayer _player, final int duration) {
    final float deviceVolume = getDeviceVolume();
    final Handler h = new Handler();
    h.postDelayed(new Runnable() {
        private float time = 0.0f;
        private float volume = 0.0f;

        @Override
        public void run() {
            _player.start();
            // can call h again after work!
            time += 100;
            volume = (deviceVolume * time) / duration;
            _player.setVolume(volume, volume);
            if (time < duration)
                h.postDelayed(this, 100);
        }
    }, 100); // 1 second delay (takes millis)

}

From source file:com.rks.musicx.services.MusicXService.java

/**
 * FadeOut//from ww w.  j a  v  a 2  s.co  m
 *
 * @param _player
 * @param duration
 */
public void fadeOut(final MediaPlayer _player, final int duration) {
    final float deviceVolume = getDeviceVolume();
    final Handler h = new Handler();
    h.postDelayed(new Runnable() {
        private float time = duration;
        private float volume = 0.0f;

        @Override
        public void run() {
            // can call h again after work!
            time -= 100;
            volume = (deviceVolume * time) / duration;
            _player.setVolume(volume, volume);
            if (time > 0)
                h.postDelayed(this, 100);
            else {
                _player.pause();
            }
        }
    }, 100); // 1 second delay (takes millis)
}

From source file:com.primalpond.hunt.TheHunt.java

private void beginTutorial() {
    mInTutorial = true;//www  .j  ava 2 s  .  c o m

    if (mGLView != null) {
        mGLView.onPause();
    }
    final RelativeLayout rootLayout = (RelativeLayout) findViewById(R.id.root_layout);
    Handler handler = new Handler();
    class RefreshRunnable implements Runnable {

        public RefreshRunnable() {

        }

        public void run() {
            rootLayout.removeView(findViewById(R.id.glSurfaceView));

            D3GLSurfaceView surfaceview = new D3GLSurfaceView(getApplication(), null,
                    new TutorialRenderer(TheHunt.this));
            surfaceview.setId(R.id.glSurfaceView);
            rootLayout.addView(surfaceview);

            View actionBarPart = findViewById(R.id.actionBarPart);
            actionBarPart.bringToFront();

            mGLView = (D3GLSurfaceView) findViewById(R.id.glSurfaceView);

            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            mTutorialFragment = new TutorialFragment();
            ft.add(R.id.root_layout, mTutorialFragment);
            ft.commit();
            mGLView.mRenderer.setActivity(TheHunt.this);
            onToHideNavigation();
        }
    }
    ;

    RefreshRunnable r = new RefreshRunnable();
    handler.postDelayed(r, 500);
}

From source file:com.ibm.pickmeup.activities.MapActivity.java

/**
 * Update map with the new coordinates for the driver
 * @param intent containing driver coordinates
 */// w w w.  j a  v  a2 s  . c  o m
private void updateMap(final Intent intent) {
    // not logging entry as it will flood the logs

    // getting driver LatLng values from the intent
    final LatLng driverLatLng = new LatLng(intent.getFloatExtra(Constants.LATITUDE, 0),
            intent.getFloatExtra(Constants.LONGITUDE, 0));

    // create driver marker if it doesn't exist and move the camera accordingly
    if (driverMarker == null) {
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(driverLatLng, 10));
        driverMarker = mMap.addMarker(new MarkerOptions().position(driverLatLng)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_driver)));
        return;
    }

    // update driver location with LatLng
    driverLocation.setLatitude(driverLatLng.latitude);
    driverLocation.setLongitude(driverLatLng.longitude);

    // calculate current distance to the passenger
    float distance = passengerLocation.distanceTo(driverLocation) / 1000;

    // set the distance text
    distanceDetails.setText(String.format(getResources().getString(R.string.distance_with_value), distance));

    // calculating ETA - we are assuming here that the car travels at 20mph to simplify the calculations
    calendar = Calendar.getInstance();
    calendar.add(Calendar.MINUTE, Math.round(distance / 20 * 60));

    // set AM/PM to a relevant value
    AM_PM = getString(R.string.am);
    if (calendar.get(Calendar.AM_PM) == 1) {
        AM_PM = getString(R.string.pm);
    }

    // format ETA string to HH:MM
    String eta = String.format(getResources().getString(R.string.eta_with_value),
            calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), AM_PM);

    // set the ETA text
    etaDetails.setText(eta);

    // as we are throttling updates to the coordinates, we might need to smooth out the moving
    // of the driver's marker. To do so we are going to draw temporary markers between the
    // previous and the current coordinates. We are going to use interpolation for this and
    // use handler/looper to set the marker's position

    // get hold of the handler
    final Handler handler = new Handler();
    final long start = SystemClock.uptimeMillis();

    // get map projection and the driver's starting point
    Projection proj = mMap.getProjection();
    Point startPoint = proj.toScreenLocation(driverMarker.getPosition());
    final LatLng startLatLng = proj.fromScreenLocation(startPoint);
    final long duration = 150;

    // create new Interpolator
    final Interpolator interpolator = new LinearInterpolator();

    // post a Runnable to the handler
    handler.post(new Runnable() {
        @Override
        public void run() {
            // calculate how soon we need to redraw the marker
            long elapsed = SystemClock.uptimeMillis() - start;
            float t = interpolator.getInterpolation((float) elapsed / duration);
            double lng = t * intent.getFloatExtra(Constants.LONGITUDE, 0) + (1 - t) * startLatLng.longitude;
            double lat = t * intent.getFloatExtra(Constants.LATITUDE, 0) + (1 - t) * startLatLng.latitude;

            // set the driver's marker position
            driverMarker.setPosition(new LatLng(lat, lng));
            if (t < 1.0) {
                handler.postDelayed(this, 10);
            }
        }
    });
}

From source file:com.simadanesh.isatis.ScreenSlideActivity.java

private void showfilterMenu() {
    View p = findViewById(R.id.anchorer);
    progressbar.setVisibility(View.GONE);

    final PopupMenu popup = new PopupMenu(this, p);
    //Inflating the Popup using xml file  
    popup.getMenuInflater().inflate(R.menu.filter, popup.getMenu());
    for (int i = 0; i < popup.getMenu().size(); i++) {
        MenuItem item = popup.getMenu().getItem(i);
        String countstr = "0";
        switch (item.getItemId()) {
        case R.id.filter_no_filter:
            countstr = countFilterNofilter();
            break;
        case R.id.filter_no_data:
            countstr = countFilterNodata();
            break;
        case R.id.filter_valid_reading:
            countstr = countFilterValid();
            break;
        case R.id.filter_hilow:
            countstr = countFilterHilow();
            break;
        case R.id.filter_maneh:
            countstr = countFilterManeh();

            break;
        case R.id.filter_inspection:
            countstr = countFilterInspection();
            break;
        case R.id.filter_register_field:
            countstr = countFilterRegisterField();
            break;
        case R.id.filter_not_register_field:
            countstr = countFilterRegisterNotField();
            break;

        }/*from  ww w  .  ja va2  s . c  om*/
        item.setTitle(item.getTitle() + "\t" + countstr);
    }

    //registering popup with OnMenuItemClickListener  
    popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
        public boolean onMenuItemClick(MenuItem item) {
            switch (item.getItemId()) {
            case R.id.filter_no_filter:
                filterNofilter();
                break;
            case R.id.filter_no_data:
                filterNodata();
                break;
            case R.id.filter_valid_reading:
                filterValid();
                break;
            case R.id.filter_hilow:
                filterHilow();
                break;
            case R.id.filter_maneh:
                //filterManeh();
                showManehMenu();
                break;
            case R.id.filter_inspection:
                filterInspection();
                break;
            case R.id.filter_register_field:
                filterRegisterField();
                break;
            case R.id.filter_not_register_field:
                filterRegisterNotField();
                break;

            }
            return true;
        }
    });

    final Handler handler1 = new Handler();
    progressbar.setVisibility(View.GONE);
    //android.R.attr.progressBarStyleLarge
    handler1.postDelayed(new Runnable() {
        @Override
        public void run() {
            popup.show();
        }
    }, 100);
}

From source file:com.filemanager.free.fragments.Main.java

public void onSearchCompleted() {
    if (!results) {
        LIST_ELEMENTS.clear();//from  w  ww. ja  v  a2 s .  co  m
    }
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            Collections.sort(LIST_ELEMENTS, new FileListSorter(dsort, sortby, asc, ROOT_MODE));
            return null;
        }

        @Override
        public void onPostExecute(Void c) {
            createViews(LIST_ELEMENTS, true, (CURRENT_PATH), openMode, true, !IS_LIST);
            pathname.setText(MAIN_ACTIVITY.getString(R.string.empty));
            mFullPath.setText(MAIN_ACTIVITY.getString(R.string.searchresults));
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    MainActivity.showInterstitial();
                }
            }, 600);
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}

From source file:com.mooshim.mooshimeter.main.ScanActivity.java

public synchronized void startScan() {
    if (mScanOngoing)
        return;//from  w  ww.j  av  a  2s . co  m
    mScanOngoing = true;

    final Handler h = new Handler();
    mBtnScan.setEnabled(false);
    updateScanningButton(false);
    // Prune disconnected meters
    List<MooshimeterDevice> remove = new ArrayList<MooshimeterDevice>();
    for (MooshimeterDevice m : mMeterList) {
        if (m.mConnectionState == BluetoothProfile.STATE_DISCONNECTED) {
            remove.add(m);
        }
    }
    for (MooshimeterDevice m : remove) {
        mDeviceScrollView.removeView(mTileList.remove(mMeterList.indexOf(m)));
        mMeterList.remove(m);
        mMeterDict.remove(m.getAddress());
    }
    refreshAllMeterTiles();

    final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (!bluetoothAdapter.startLeScan(mLeScanCallback)) {
        // Starting the scan failed!
        Log.e(TAG, "Failed to start BLE Scan");
        setError("Failed to start scan");
    }
    h.postDelayed(new Runnable() {
        @Override
        public void run() {
            mBtnScan.setEnabled(true);
            updateScanningButton(false);
            final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            bluetoothAdapter.stopLeScan(mLeScanCallback);
            mScanOngoing = false;
        }
    }, 5000);
}

From source file:org.getlantern.firetweet.activity.support.ComposeActivity.java

private void refreshHomeTimeline() {
    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override/*w ww. j  a  v a 2  s .  co  m*/
        public void run() {
            Log.d(LOG_TAG, "Sent tweet. Refreshing home timeline..");
            final long default_id = mPreferences.getLong(KEY_DEFAULT_ACCOUNT_ID, -1);
            mTwitterWrapper.refreshAll(new long[] { default_id });
        }
    }, 300);

}

From source file:org.sirimangalo.meditationplus.ActivityMain.java

@Override
public void onClick(View view) {
    int id = view.getId();
    ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
    switch (id) {
    case R.id.chat_send:

        smiliesShell.setVisibility(View.GONE);
        EditText message = (EditText) findViewById(R.id.chat_text);
        String messageT = message.getText().toString();
        if (messageT.length() == 0) {
            Toast.makeText(this, R.string.no_message, Toast.LENGTH_SHORT).show();
            return;
        }// w  w w.  ja v a 2  s.c  o m
        if (messageT.length() > 140) {
            Toast.makeText(this, R.string.message_too_long, Toast.LENGTH_SHORT).show();
            return;
        }
        nvp.add(new BasicNameValuePair("message", messageT));
        doSubmit("chatform", nvp, true);
        doChatScroll = true;
        break;
    case R.id.med_send:
        int w = walkingPicker.getValue();
        int s = sittingPicker.getValue();

        if (w == 0 && s == 0) {
            Toast.makeText(this, R.string.no_time, Toast.LENGTH_SHORT).show();
            return;
        }

        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt("walking", w);
        editor.putInt("sitting", s);
        editor.apply();

        lastWalking = w * 5;
        lastSitting = s * 5;

        startMeditating = true;

        nvp.add(new BasicNameValuePair("walking", lastWalking + ""));
        nvp.add(new BasicNameValuePair("sitting", lastSitting + ""));
        doSubmit("timeform", nvp, true);
        break;
    case R.id.med_cancel:

        Intent rIntent = new Intent(this, ReceiverAlarm.class);
        PendingIntent walkPendingIntent = PendingIntent.getBroadcast(context, 0, rIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        PendingIntent sitPendingIntent = PendingIntent.getBroadcast(context, 1, rIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        mAlarmMgr.cancel(walkPendingIntent);
        mAlarmMgr.cancel(sitPendingIntent);
        mNM.cancelAll();

        doSubmit("cancelform", nvp, true);
        break;
    case R.id.smily_button:
        if (smiliesShell.getVisibility() == View.GONE)
            smiliesShell.setVisibility(View.VISIBLE);
        else
            smiliesShell.setVisibility(View.GONE);
        break;
    case R.id.chat_text:
        smiliesShell.setVisibility(View.GONE);
        singleClick++;
        Handler handler = new Handler();
        Runnable r = new Runnable() {

            @Override
            public void run() {
                singleClick = 0;
            }
        };

        if (singleClick == 1) {
            //Single click
            handler.postDelayed(r, 250);
        } else if (singleClick == 2) {
            //Double click
            singleClick = 0;
            ((EditText) findViewById(R.id.chat_text)).setText("");
        }
        break;
    case R.id.new_commit:
        Intent i = new Intent(this, ActivityCommit.class);
        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(i);
        break;
    default:
        smiliesShell.setVisibility(View.GONE);
        break;
    }
}

From source file:com.simadanesh.isatis.ScreenSlideActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    CommonPlace.manehCodes = ManehCodeDA.getInstance(this).getAll();
    CommonPlace.inspectionCodes = InspectionCodeDA.getInstance(this).getAll();
    CommonPlace.CurrentRegisterFields = RegisterFieldDA.getInstance(this).getAll("fldPartitionCode=?", "",
            new String[] { CommonPlace.currentCityPartition.getFldPartitionCode() });
    LoadValidationCriterias();/* w  w  w.  ja  v a 2s .  c om*/

    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread paramThread, Throwable paramThrowable) {
            Log.e("Alert", "Lets See if it Works !!!" + paramThrowable.toString());
        }
    });
    Utility.InitializeDefatultSettings(this);
    CommonPlace.slideActivity = this;
    getActionBar().setDisplayHomeAsUpEnabled(true);

    setContentView(R.layout.activity_screen_slide);
    mtextProgress = (TextView) findViewById(R.id.txtProgress);

    Utility.applyFont(findViewById(R.id.reading_page));
    LinearLayout taskbarLayout = (LinearLayout) findViewById(R.id.taskbarpanel);
    taskbarLayout.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            Button btnCamera = (Button) findViewById(R.id.btnCamera);
            if (btnCamera.getTextSize() > 0) {
                btnCamera.setTextSize(0);
            } else {
                btnCamera.setTextSize(20);
            }

        }
    });
    progressbar = (ProgressBar) findViewById(R.id.reading_progress);
    progressbar.setProgress(0);

    Button btnSubmit = (Button) findViewById(R.id.btnSubmit);
    btnSubmit.setOnClickListener(new View.OnClickListener() {

        Dialog mydialog;

        public void onClick(View v) {
            ShowSubmitDialog();
        }
    });

    Button btnCamera = (Button) findViewById(R.id.btnCamera);
    btnCamera.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            dispatchTakePictureIntentOrShowPicture();
        }

    });

    Button btnInspection = (Button) findViewById(R.id.btnInspection);
    btnInspection.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            ShowInspectionDialog();
        }

    });

    Button btnonlineControl = (Button) findViewById(R.id.btnOnline_control);
    btnonlineControl.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            ShowOnlineControl();
        }

    });

    Button btnOnlineCalculation = (Button) findViewById(R.id.btnCalculation);
    btnOnlineCalculation.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            ShowOnlineCalculation();
        }

    });

    // Instantiate a ViewPager and a PagerAdapter.
    mPager = (ViewPager) findViewById(R.id.pager);
    mPagerAdapter = new ScreenSlidePagerAdapter(getFragmentManager());
    mPager.setAdapter(mPagerAdapter);
    mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {

            // When changing pages, reset the action bar actions since they are dependent
            // on which page is currently active. An alternative approach is to have each
            // fragment expose actions itself (rather than the activity exposing actions),
            // but for simplicity, the activity provides the actions in this sample.
            invalidateOptionsMenu();
        }
    });
    try {
        // int last = mSavedBundle.getInt("Reading-" + CommonPlace.currentReadingList.getId());
        // mPager.setCurrentItem(last);
    } catch (Exception ex) {
        ex.toString();
    }

    final Handler handler1 = new Handler();
    try {
        final int pos = Integer.parseInt(CommonPlace.currentReadingList.Position);
        handler1.postDelayed(new Runnable() {
            @Override
            public void run() {
                mPager.setCurrentItem(pos);
            }
        }, 500);
    } catch (Exception ex) {

    }
}