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.thaliproject.p2p.btconnectorlib.internal.wifi.WifiServiceWatcher.java

/**
 * Starts the service discovery.//from w  w w  .j  ava  2 s  .c  o m
 */
public synchronized void start() {
    mIsRestarting = false;
    WifiP2pDnsSdServiceRequest request = WifiP2pDnsSdServiceRequest.newInstance(mServiceType);
    final WifiServiceWatcher thisInstance = this;
    final Handler handler = new Handler();

    mP2pManager.addServiceRequest(mP2pChannel, request, new WifiP2pManager.ActionListener() {
        @Override
        public void onSuccess() {
            Log.i(TAG, "Service request added successfully");

            // There is supposedly a possible race-condition bug with the service discovery.
            // Thus, to avoid it, we are delaying the service discovery initialization here.
            handler.postDelayed(new Runnable() {
                public void run() {
                    thisInstance.mP2pManager.discoverServices(thisInstance.mP2pChannel,
                            new WifiP2pManager.ActionListener() {
                                @Override
                                public void onSuccess() {
                                    Log.d(TAG, "Service discovery started successfully");
                                }

                                @Override
                                public void onFailure(int reason) {
                                    Log.e(TAG,
                                            "Failed to start the service discovery, got error code: " + reason);

                                    // Uncomment the following to auto-restart
                                    //thisInstance.stop(true); // Restart
                                }
                            });
                }
            }, START_SERVICE_DISCOVERY_DELAY_IN_MILLISECONDS);
        }

        @Override
        public void onFailure(int reason) {
            Log.e(TAG, "Failed to add a service request, got error code: " + reason);

            // Uncomment the following to auto-restart
            //thisInstance.stop(true); // Restart
        }
    });
}

From source file:br.org.funcate.dynamicforms.views.GPictureView.java

public void refresh(final Context context) throws Exception {

    imageLayout.removeAllViewsInLayout();
    int increaseTime = 0;// using on runnable

    if (_pictures != null && _pictures.size() > 0) {

        Set<String> imageKeys = _pictures.keySet();
        for (final String imageId : imageKeys) {

            if (!_pictures.containsKey(imageId)) {
                // TODO: Here, write a log in logfile
                continue;
            } else {
                Map<String, String> imagePaths = _pictures.get(imageId);
                final String imagePath = imagePaths.get("thumbnail");
                final ProgressBar pgBar = getProgressBar(context);
                imageLayout.addView(pgBar);
                increaseTime++;/*from   w  w  w.j  a  v a2 s.c  o  m*/

                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    public void run() {
                        /*
                                                    byte[] image = ImageUtilities.getImageFromPath(imagePath, 2);
                                                    if (image != null && image.length > 0) {
                        Bitmap imageBitmap = ImageUtilities.getBitmapFromBlob(image);
                        try {
                            image = null;
                        } catch (Throwable t) {
                            t.printStackTrace();
                            getDefaultBitmap();
                            return;
                        }
                                
                        Bitmap thumbnail = ImageUtilities.makeThumbnail(imageBitmap);
                        if (imageBitmap.isRecycled()) imageBitmap.recycle();
                        */
                        if (imagePath != null && !imagePath.isEmpty() && (new File(imagePath)).exists()) {
                            pgBar.setVisibility(View.GONE);
                            imageLayout.addView(getImageView(context, imagePath, imageId));
                            imageLayout.invalidate();
                            //if (thumbnail.isRecycled()) thumbnail.recycle();
                        } else {
                            getDefaultBitmap();
                        }
                    }

                    public void getDefaultBitmap() {
                        pgBar.setVisibility(View.GONE);
                        Bitmap bitmapError = BitmapFactory.decodeResource(getResources(),
                                R.drawable.ic_stat_action_highlight_remove);
                        imageLayout.addView(getImageView(context, bitmapError, imageId));
                        imageLayout.invalidate();
                        // if (bitmapError.isRecycled()) bitmapError.recycle();
                    }
                }, increaseTime * 1000 + 1000);
            }
        }
    }
    if (newImagesFromCamera != null && newImagesFromCamera.size() > 0) {
        Set<String> imageKeys = newImagesFromCamera.keySet();
        for (final String imageId : imageKeys) {

            final String imagePath = newImagesFromCamera.get(imageId);
            final ProgressBar pgBar = getProgressBar(context);
            imageLayout.addView(pgBar);
            increaseTime++;

            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                public void run() {
                    try {

                        if (imagePath != null && !imagePath.isEmpty() && (new File(imagePath)).exists()) {

                            pgBar.setVisibility(View.GONE);
                            imageLayout.addView(getImageView(context, imagePath, imageId));
                            imageLayout.invalidate();

                            /*
                            if (!ImageUtilities.resampleImage(imagePath)) {
                            getDefaultBitmap();
                            return;
                            }
                            byte[] image = ImageUtilities.getImageFromPath(imagePath, 2);
                            if (image != null) {
                            Bitmap imageBitmap = ImageUtilities.getBitmapFromBlob(image);
                            image = null;
                            Bitmap thumbnail = ImageUtilities.makeThumbnail(imageBitmap);
                            imageBitmap = null;
                            pgBar.setVisibility(View.GONE);
                            imageLayout.addView(getImageView(context, thumbnail, imageId));
                            thumbnail = null;
                            imageLayout.invalidate();
                            } else {
                            getDefaultBitmap();
                            }
                            */
                        }
                    } catch (Throwable e) {
                        e.printStackTrace();
                        getDefaultBitmap();
                    }
                }

                public void getDefaultBitmap() {
                    pgBar.setVisibility(View.GONE);
                    Bitmap bitmapError = BitmapFactory.decodeResource(getResources(),
                            R.drawable.ic_stat_action_highlight_remove);
                    imageLayout.addView(getImageView(context, bitmapError, imageId));
                    imageLayout.invalidate();
                }
            }, increaseTime * 1000 + 1000);

            if (!addedIdsToImageViews.containsValue(imagePath))
                addedIdsToImageViews.put(imageId, imagePath);
        }
    }

    imageLayout.invalidate();

}

From source file:com.iss.android.wearable.datalayer.MainActivity.java

private void initializeSWBatteryChecker() {
    final TextView SWBatteryStatus = (TextView) findViewById(R.id.SWbatteryLabel);
    final Handler h = new Handler();
    final int delay = 20000; //milliseconds
    final boolean[] warned_evening = { false };

    // Timer's fine for Java, but kills android apps.

    h.postDelayed(new Runnable() {
        public void run() {
            IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
            Intent batteryStatus = registerReceiver(null, ifilter);

            int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

            int batteryPct = (int) (level / (float) scale * 100);
            SWBatteryStatus.setText("SW: " + batteryPct + "%");
            Calendar clnd = Calendar.getInstance();
            if (clnd.get(Calendar.HOUR_OF_DAY) >= 20) {
                if (batteryPct < 75 && !warned_evening[0]) {
                    warned_evening[0] = true;
                    displaySWBatteryWarning();
                } else if (batteryPct >= 75 && warned_evening[0]) {
                    warned_evening[0] = false;
                }//from   www. j  a va  2  s  .c o  m
            }
            h.postDelayed(this, delay);
        }
    }, 0);
}

From source file:org.odk.collect.android.activities.GeoShapeOsmMapActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.geoshape_osm_layout);
    setTitle(getString(R.string.geoshape_title)); // Setting title of the action
    ImageButton saveButton = (ImageButton) findViewById(R.id.save);
    clearButton = (ImageButton) findViewById(R.id.clear);

    map = (MapView) findViewById(R.id.geoshape_mapview);
    helper = new MapHelper(this, map, GeoShapeOsmMapActivity.this);
    map.setMultiTouchControls(true);// ww w . j  a va2  s.c o m
    map.setBuiltInZoomControls(true);
    map.setMapListener(mapViewListener);
    overlayPointPathListener();
    saveButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            returnLocation();
        }
    });
    clearButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mapMarkers.size() != 0) {
                showClearDialog();
            }
        }
    });
    ImageButton layersButton = (ImageButton) findViewById(R.id.layers);
    layersButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            helper.showLayersDialog(GeoShapeOsmMapActivity.this);

        }
    });
    locationButton = (ImageButton) findViewById(R.id.gps);
    locationButton.setEnabled(false);
    locationButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View v) {
            showZoomDialog();
        }
    });

    GpsMyLocationProvider imlp = new GpsMyLocationProvider(this.getBaseContext());
    imlp.setLocationUpdateMinDistance(1000);
    imlp.setLocationUpdateMinTime(60000);
    myLocationOverlay = new MyLocationNewOverlay(map);

    Intent intent = getIntent();
    if (intent != null && intent.getExtras() != null) {
        if (intent.hasExtra(GeoShapeWidget.SHAPE_LOCATION)) {
            clearButton.setEnabled(true);
            dataLoaded = true;
            String s = intent.getStringExtra(GeoShapeWidget.SHAPE_LOCATION);
            overlayIntentPolygon(s);
            //zoomToCentroid();
            locationButton.setEnabled(true);
            zoomToBounds();
        }
    } else {
        myLocationOverlay.runOnFirstFix(centerAroundFix);
        clearButton.setEnabled(false);
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            public void run() {
                GeoPoint point = new GeoPoint(34.08145, -39.85007);
                map.getController().setZoom(3);
                map.getController().setCenter(point);
            }
        }, 100);

    }

    map.invalidate();

    zoomDialogView = getLayoutInflater().inflate(R.layout.geoshape_zoom_dialog, null);

    zoomLocationButton = (Button) zoomDialogView.findViewById(R.id.zoom_location);
    zoomLocationButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            zoomToMyLocation();
            map.invalidate();
            zoomDialog.dismiss();
        }
    });

    zoomPointButton = (Button) zoomDialogView.findViewById(R.id.zoom_shape);
    zoomPointButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            //zoomToCentroid();
            zoomToBounds();
            map.invalidate();
            zoomDialog.dismiss();
        }
    });
}

From source file:net.olejon.mdapp.MainActivity.java

@Override
protected void onResume() {
    super.onResume();

    // Input manager
    Handler handler = new Handler();

    handler.postDelayed(new Runnable() {
        @Override//from www  . j a v  a2 s.  c o  m
        public void run() {
            mInputMethodManager.hideSoftInputFromWindow(mDrawerLayout.getWindowToken(), 0);
        }
    }, 250);

    // Rate
    if (!mTools.getSharedPreferencesBoolean("MAIN_HIDE_RATE_DIALOG_140")) {
        long currentTime = mTools.getCurrentTime();
        long installedTime = mTools.getSharedPreferencesLong("INSTALLED");

        if (currentTime - installedTime > 1000 * 3600 * 48) {
            mTools.setSharedPreferencesBoolean("MAIN_HIDE_RATE_DIALOG_140", true);

            new MaterialDialog.Builder(mContext).title(getString(R.string.main_rate_dialog_title))
                    .content(getString(R.string.main_rate_dialog_message))
                    .positiveText(getString(R.string.main_rate_dialog_positive_button))
                    .negativeText(getString(R.string.main_rate_dialog_negative_button))
                    .callback(new MaterialDialog.ButtonCallback() {
                        @Override
                        public void onPositive(MaterialDialog dialog) {
                            Intent intent = new Intent(Intent.ACTION_VIEW,
                                    Uri.parse("market://details?id=net.olejon.mdapp"));
                            startActivity(intent);
                        }
                    }).contentColorRes(R.color.black).positiveColorRes(R.color.dark_blue)
                    .negativeColorRes(R.color.black).show();
        }
    }

    // Donate
    if (!mTools.getSharedPreferencesBoolean("MAIN_HIDE_DONATE_DIALOG_140")) {
        long currentTime = mTools.getCurrentTime();
        long installedTime = mTools.getSharedPreferencesLong("INSTALLED");

        if (currentTime - installedTime > 1000 * 3600 * 96) {
            mTools.setSharedPreferencesBoolean("MAIN_HIDE_DONATE_DIALOG_140", true);

            new MaterialDialog.Builder(mContext).title(getString(R.string.main_donate_dialog_title))
                    .content(getString(R.string.main_donate_dialog_message))
                    .positiveText(getString(R.string.main_donate_dialog_positive_button))
                    .negativeText(getString(R.string.main_donate_dialog_negative_button))
                    .callback(new MaterialDialog.ButtonCallback() {
                        @Override
                        public void onPositive(MaterialDialog dialog) {
                            Intent intent = new Intent(mContext, DonateActivity.class);
                            startActivity(intent);
                        }
                    }).contentColorRes(R.color.black).positiveColorRes(R.color.dark_blue)
                    .negativeColorRes(R.color.black).show();
        }
    }
}

From source file:de.quadrillenschule.azocamsynca.job.JobProcessor.java

public void processingLoop() {

    if (getRequestStatus() == ProcessorStatus.PAUSED) {
        setStatus(ProcessorStatus.PAUSED);
        return;//from  w  ww .  j a va 2s .co  m
    }
    setStatus(ProcessorStatus.PROCESSING);
    TriggerPhotoSerie currentJobT = null;
    for (TriggerPhotoSerie j : jobs) {
        if (j.getTriggerStatus() != TriggerPhotoSerie.TriggerJobStatus.FINISHED_TRIGGERING) {
            currentJobT = j;
            if ((j.getTriggerStatus() == PhotoSerie.TriggerJobStatus.WAITFORUSER)
                    && ((alertDialog != null) && (alertDialog.isShowing()))) {
                return;
            }
            if ((j.getTriggerStatus() == PhotoSerie.TriggerJobStatus.WAITFORUSER)) {
                currentJobT.setTriggerStatus(PhotoSerie.TriggerJobStatus.NEW);
            }
            break;
        }
    }
    if (currentJobT == null) {
        setStatus(ProcessorStatus.PAUSED);
        return;
    }

    final TriggerPhotoSerie currentJob = currentJobT;
    final NikonIR camera = ((AzoTriggerServiceApplication) getActivity().getApplication()).getCamera();

    if (currentJob.getTriggerStatus() == PhotoSerie.TriggerJobStatus.NEW) {
        currentJob.setTriggerStatus(PhotoSerie.TriggerJobStatus.WAITFORUSER);
        if (currentJob.getSeriesName().equals(PhotoSerie.TESTSHOTS)) {
            doTestShots(currentJob);
            return;
        }
        AlertDialog.Builder ad = new AlertDialog.Builder(getActivity(), R.style.dialog);
        ad.setTitle(currentJob.getProject() + ": " + currentJob.getSeriesName());
        ad.setMessage(
                currentJob.getNumber() + " x " + (int) (currentJob.getExposure() / 1000) + "s\n\n"
                        + "Delay after each exposure:" + currentJob.getDelayAfterEachExposure() / 1000 + "s\n"
                        + "Camera controls time: " + camera.isExposureSetOnCamera(currentJob.getExposure())
                        + "\n" + "Total time: "
                        + ((currentJob.getNumber()
                                * (currentJob.getExposure() + currentJob.getDelayAfterEachExposure())) / 1000)
                        + "s");

        ad.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface arg0, int arg1) {
                currentJob.setTriggerStatus(PhotoSerie.TriggerJobStatus.PREPARED);
                processingLoop();
            }
        });
        ad.setNegativeButton("Pause", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface arg0, int arg1) {
                currentJob.setTriggerStatus(PhotoSerie.TriggerJobStatus.NEW);
                pause();
            }
        });

        MediaPlayer mediaPlayer = MediaPlayer.create(activity, R.raw.oida_peda);
        mediaPlayer.start();
        ad.create();
        alertDialog = ad.show();

    }

    final Handler handler = new Handler();

    if ((currentJob.getTriggerStatus() == PhotoSerie.TriggerJobStatus.PREPARED
            || currentJob.getTriggerStatus() == PhotoSerie.TriggerJobStatus.RUNNING)) {
        handler.postDelayed(new Runnable() {

            public void run() {
                if ((((AzoTriggerServiceApplication) getActivity().getApplication()).getJobProcessor()
                        .getStatus() == ProcessorStatus.PAUSED) && (!currentJob.isToggleIsOpen())) {

                    return;
                }
                camera.trigger();
                for (JobProgressListener j : jobProgressListeners) {
                    j.jobProgressed(currentJob);
                }
                if (currentJob.getFirstTriggerTime() == 0) {
                    currentJob.setFirstTriggerTime(System.currentTimeMillis());
                }
                currentJob.setTriggerStatus(PhotoSerie.TriggerJobStatus.RUNNING);

                if (!camera.isExposureSetOnCamera(currentJob.getExposure())) {
                    if (!currentJob.isToggleIsOpen()) {
                        currentJob.setToggleIsOpen(!currentJob.isToggleIsOpen());

                        currentJob.setLastTriggerTime(System.currentTimeMillis());
                    } else {
                        currentJob.setToggleIsOpen(!currentJob.isToggleIsOpen());
                        currentJob.setTriggered(currentJob.getTriggered() + 1);

                    }
                } else {

                    currentJob.setTriggered(currentJob.getTriggered() + 1);

                }
                if (currentJob.getTriggered() < currentJob.getNumber()) {
                    long time;
                    if (camera.isExposureSetOnCamera(currentJob.getExposure())) {
                        time = currentJob.getExposure() + currentJob.getDelayAfterEachExposure();
                    } else {
                        if (currentJob.isToggleIsOpen()) {
                            time = currentJob.getExposure();
                        } else {
                            time = currentJob.getDelayAfterEachExposure();
                        }
                    }
                    handler.postDelayed(this, time);
                } else {
                    currentJob.setTriggerStatus(PhotoSerie.TriggerJobStatus.FINISHED_TRIGGERING);
                    processingLoop();
                }
            }
        }, currentJob.getInitialDelay());
    } else {
    }

}

From source file:com.agustinprats.myhrv.fragment.MonitorFragment.java

/** Starts so many heart beat animations as specified in the parameter @count.
 *  Each animation duration is based on the RR intervals
 *  passed in the @intervals parameter */
private void heartBeats(RrIntervalList intervals, int count) {

    heartBeat();//  ww w  .j av  a  2  s .c  o  m
    for (int i = intervals.size() - count; i < intervals.size(); i++) {

        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {

                heartBeat();
            }
        }, intervals.get(i).getRRInterval());
    }
}

From source file:com.ideateam.plugin.Version.java

public void checkForUpdates() {

    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override/*from w w  w .j av  a 2  s.  c  om*/
        public void run() {
            //activity.sendJavascript("UART.system.Helper.fromNative()");
            getVersion(true);
        }
    }, 10000);

}

From source file:com.open.file.manager.MainActivity.java

/**
 * @return Actionmode for cut/copy/*  ww w  .j  a  v a2  s .  co m*/
 */
public Callback getCutCopyCallback() {

    return new Callback() {

        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            mode.getMenuInflater().inflate(R.layout.menuactions, menu);
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            switch (item.getItemId()) {
            case (R.id.cut):
                currentaction = Consts.ACTION_CUT;
                operationqueue.addAll(selectedfiles);
                delaystartpaste();
                mode.finish();
                return true;
            case (R.id.copy):
                currentaction = Consts.ACTION_COPY;
                operationqueue.addAll(selectedfiles);
                delaystartpaste();
                mode.finish();
                return true;
            case (R.id.delete):
                operator.removefiles(selectedfiles);
                mode.finish();
                return true;
            case (R.id.rename):
                operator.renamefile(selectedfiles);
                mode.finish();
                return true;
            case (R.id.info):
                getFileInfo(selectedfiles.get(0));
                mode.finish();
                return true;
            }
            return false;
        }

        /**
         * Delay start (~10ms) of copy actionmode due to a bug in sherlock library
         */
        public void delaystartpaste() {
            Handler modeHandler = new Handler();
            modeHandler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    copycutmode = startActionMode(getPasteCallback());

                }
            }, 10);
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            // clear selection
            int fragindex = MainActivity.mPager.getCurrentItem();
            MainActivity.selectedfiles.clear();
            MainActivity.selectedcount = 0;
            MainActivity.mMode = null;
            if (MainActivity.mAdapter.getItem(fragindex).getClass() == (GridFragment.class)) {
                ((GridFragment) MainActivity.mAdapter.getItem(fragindex)).clearselection();
            }
        }

    };
}

From source file:de.dmxcontrol.activity.ControlActivity.java

public void dismissSplashDelayed() {
    Handler h = new Handler();

    h.postDelayed(new Runnable() {

        @Override/*ww  w  . j  a  v  a 2 s.c  om*/
        public void run() {
            try {
                ControlActivity.this.removeDialog(DIALOG_SPLASH);
            } catch (IllegalArgumentException e) {
                // We ignore this here - race condition error
            }
        }

    }, DIALOG_SPLASH_DELAY);

}