Example usage for java.util TimerTask TimerTask

List of usage examples for java.util TimerTask TimerTask

Introduction

In this page you can find the example usage for java.util TimerTask TimerTask.

Prototype

protected TimerTask() 

Source Link

Document

Creates a new timer task.

Usage

From source file:com.xiaoyu.DoctorHelp.chat.chatuidemo.adapter.MessageAdapter.java

/**
 * ?//from  ww w . j  a  v  a  2  s . com
 *
 * @param message
 * @param holder
 * @param position
 * @param convertView
 */
private void handleImageMessage(final EMMessage message, final ViewHolder holder, final int position,
        View convertView) {
    holder.pb.setTag(position);
    holder.iv.setOnLongClickListener(new OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            activity.startActivityForResult((new Intent(activity, ContextMenu.class))
                    .putExtra("position", position).putExtra("type", EMMessage.Type.IMAGE.ordinal()),
                    ChatActivity.REQUEST_CODE_CONTEXT_MENU);
            return true;
        }
    });

    // ??
    if (message.direct == EMMessage.Direct.RECEIVE) {
        // "it is receive msg";
        if (message.status == EMMessage.Status.INPROGRESS) {
            // "!!!! back receive";
            holder.iv.setImageResource(R.drawable.default_image);
            showDownloadImageProgress(message, holder);
            // downloadImage(message, holder);
        } else {
            // "!!!! not back receive, show image directly");
            holder.pb.setVisibility(View.GONE);
            holder.tv.setVisibility(View.GONE);
            holder.iv.setImageResource(R.drawable.default_image);
            ImageMessageBody imgBody = (ImageMessageBody) message.getBody();
            if (imgBody.getLocalUrl() != null) {
                // String filePath = imgBody.getLocalUrl();
                String remotePath = imgBody.getRemoteUrl();
                String filePath = ImageUtils.getImagePath(remotePath);
                String thumbRemoteUrl = imgBody.getThumbnailUrl();
                String thumbnailPath = ImageUtils.getThumbnailImagePath(thumbRemoteUrl);
                showImageView(thumbnailPath, holder.iv, filePath, imgBody.getRemoteUrl(), message);
            }
        }
        return;
    }

    // ???
    // process send message
    // send pic, show the pic directly
    ImageMessageBody imgBody = (ImageMessageBody) message.getBody();
    String filePath = imgBody.getLocalUrl();
    if (filePath != null && new File(filePath).exists()) {
        showImageView(ImageUtils.getThumbnailImagePath(filePath), holder.iv, filePath, null, message);
    } else {
        showImageView(ImageUtils.getThumbnailImagePath(filePath), holder.iv, filePath, IMAGE_DIR, message);
    }

    switch (message.status) {
    case SUCCESS:
        holder.pb.setVisibility(View.GONE);
        holder.tv.setVisibility(View.GONE);
        holder.staus_iv.setVisibility(View.GONE);
        break;
    case FAIL:
        holder.pb.setVisibility(View.GONE);
        holder.tv.setVisibility(View.GONE);
        holder.staus_iv.setVisibility(View.VISIBLE);
        break;
    case INPROGRESS:
        holder.staus_iv.setVisibility(View.GONE);
        holder.pb.setVisibility(View.VISIBLE);
        holder.tv.setVisibility(View.VISIBLE);
        if (timers.containsKey(message.getMsgId()))
            return;
        // set a timer
        final Timer timer = new Timer();
        timers.put(message.getMsgId(), timer);
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                activity.runOnUiThread(new Runnable() {
                    public void run() {
                        holder.pb.setVisibility(View.VISIBLE);
                        holder.tv.setVisibility(View.VISIBLE);
                        holder.tv.setText(message.progress + "%");
                        if (message.status == EMMessage.Status.SUCCESS) {
                            holder.pb.setVisibility(View.GONE);
                            holder.tv.setVisibility(View.GONE);
                            // message.setSendingStatus(Message.SENDING_STATUS_SUCCESS);
                            timer.cancel();
                        } else if (message.status == EMMessage.Status.FAIL) {
                            holder.pb.setVisibility(View.GONE);
                            holder.tv.setVisibility(View.GONE);
                            // message.setSendingStatus(Message.SENDING_STATUS_FAIL);
                            // message.setProgress(0);
                            holder.staus_iv.setVisibility(View.VISIBLE);
                            Toast.makeText(activity,
                                    activity.getString(R.string.send_fail)
                                            + activity.getString(R.string.connect_failuer_toast),
                                    Toast.LENGTH_SHORT).show();
                            timer.cancel();
                        }

                    }
                });

            }
        }, 0, 500);
        break;
    default:
        sendPictureMessage(message, holder);
    }
}

From source file:com.onebus.view.MainActivity.java

private void exitBy2Click() {
    Timer tExit = null;/*from www  .jav a2 s .c om*/
    if (isExit == false) {
        isExit = true; // 
        Toast.makeText(this, "??", Toast.LENGTH_SHORT).show();
        tExit = new Timer();
        tExit.schedule(new TimerTask() {

            public void run() {
                isExit = false; // ?
            }
        }, 2000); // 2???
    } else {
        finish();
        System.exit(0);
    }
}

From source file:com.t2.compassionMeditation.Graphs1Activity.java

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

    mIsActive = true;//ww  w  .j a v  a  2 s .  c o  m

    // we need to register a SPINEListener implementation to the SPINE manager instance
    // to receive sensor node data from the Spine server
    // (I register myself since I'm a SPINEListener implementation!)
    mManager.addListener(this);

    Log.i(TAG, this.getClass().getSimpleName() + ".onStart()");

    // Set up filter intents so we can receive broadcasts
    IntentFilter filter = new IntentFilter();
    filter.addAction("com.t2.biofeedback.service.status.BROADCAST");
    this.registerReceiver(this.mCommandReceiver, filter);

    int displaySampleTime = 1000;
    String s = SharedPref.getString(this, "display_sample_rate", "1");
    mDisplaySampleRate = Integer.parseInt(s);

    switch (mDisplaySampleRate) {
    default:
    case 1:
        displaySampleTime = 1000;
        Log.d(TAG, "Setting display sample rate to " + mDisplaySampleRate + " Hz");
        break;
    case 10:
        displaySampleTime = 100;
        Log.d(TAG, "Setting display sample rate to " + mDisplaySampleRate + " Hz");
        break;
    case 100:
        displaySampleTime = 10;
        Log.d(TAG, "Setting display sample rate to " + mDisplaySampleRate + " Hz");
        break;
    case 9999:
        displaySampleTime = 9999;
        Log.d(TAG, "Setting display sample rate to match sensor sample rate");
        break;
    }

    if (mDisplaySampleRate != 9999) {
        // Set up a timer to do graphical updates
        mDataUpdateTimer = new Timer();
        mDataUpdateTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                TimerMethod();
            }

        }, 0, displaySampleTime);
    }

    // Set up a timer for GSR average reporting (10 seconds

    mRespRateAverageTimer = new Timer();
    mRespRateAverageTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            respRateAverageMethod();
        }

    }, 0, 10000);

    if (mAntHrmEnabled) {
        mAntServiceBound = bindService(new Intent(this, ANTPlusService.class), mConnection, BIND_AUTO_CREATE);
    }

}

From source file:flex.android.magiccube.activity.ActivityBattleMode.java

private void SetupGame() throws JSONException {
    if (MagiccubePreference.GetPreference(MagiccubePreference.ServerOrClient, this) == 1) {
        JSONObject jobj = new JSONObject();

        // 1. setup the messup
        String MessUpCmd1 = "";
        String MessUpCmd2 = "";

        switch (MagiccubePreference.GetPreference(MagiccubePreference.Difficulty, this)) {
        case 0://from  w  ww . j a v  a 2  s.  c  o  m
            nMessUp = 4;
            break;
        case 50:
            nMessUp = 10;
            break;
        case 100:
            nMessUp = 30;
            break;
        }

        if (MagiccubePreference.GetPreference(MagiccubePreference.IsSameMessup, this) == 1) {
            MessUpCmd1 = glView.MessUp(nMessUp);
            glView2.MessUp(MessUpCmd1);
            jobj.put(BluetoothSignal.MessUpCmd2, MessUpCmd1);
            jobj.put(BluetoothSignal.MessUpCmd1, MessUpCmd1);
        } else {
            MessUpCmd1 = glView.MessUp(nMessUp);
            MessUpCmd2 = glView2.MessUp(nMessUp);

            jobj.put(BluetoothSignal.MessUpCmd2, MessUpCmd1);
            jobj.put(BluetoothSignal.MessUpCmd1, MessUpCmd2);
        }

        // 2. setup the obervetime
        // Log.e("2", "2");
        TotalObTime = MagiccubePreference.GetPreference(MagiccubePreference.ObserveTime, this);
        // Toast.makeText(this, TotalObTime+"", Toast.LENGTH_SHORT).show();
        jobj.put(BluetoothSignal.ObserveTime, TotalObTime + "");

        // 3. end up
        // Log.e("3", "3");
        jobj.put(BluetoothSignal.EndSetUp, "end");

        this.sendMessage(jobj.toString());

    } else if (MagiccubePreference.GetPreference(MagiccubePreference.ServerOrClient, this) == 0) {
        long waittime = 6000;
        Timer t = new Timer();
        t.schedule(new TimerTask() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                if (!HeartBeating) {
                    mHandler.sendEmptyMessage(NOT_HEART_BEATING);

                }
            }
        }, waittime);
    }
}

From source file:com.t2.compassionMeditation.MeditationActivity.java

@Override
protected void onStart() {
    super.onStart();
    mIsActive = true;//from w ww.j  av a2 s.  c o  m
    Log.i(TAG, this.getClass().getSimpleName() + ".onStart()");

    //      mPauseButton.setText("Start");
    mPauseButton.setImageResource(R.drawable.start);

    // Set up filter intents so we can receive broadcasts
    IntentFilter filter = new IntentFilter();
    filter.addAction("com.t2.biofeedback.service.status.BROADCAST");
    this.registerReceiver(this.mCommandReceiver, filter);

    // Set up a timer to do graphical updates
    mDataUpdateTimer = new Timer();
    mDataUpdateTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            TimerMethod();
        }

    }, 0, 10);

    if (mMediaPlayer != null) {
        mMediaPlayer.stop();
    }

    int resource = 0;
    if (mAudioTrackResourceName.contains("Air Synth"))
        resource = R.raw.dave_luxton_air_synth_meditation;
    if (mAudioTrackResourceName.contains("Entity and Echo"))
        resource = R.raw.dave_luxton_entity_and_echo_meditation;
    if (mAudioTrackResourceName.contains("Starlit Lake"))
        resource = R.raw.dave_luxton_starlit_lake_meditation;

    if (resource != 0) {
        mMediaPlayer = MediaPlayer.create(this, resource);
        if (mMediaPlayer != null) {
            mMediaPlayer.start();
            mMediaPlayer.setLooping(true);
        }

    }

    if (mAntHrmEnabled) {
        mAntServiceBound = bindService(new Intent(this, ANTPlusService.class), mConnection, BIND_AUTO_CREATE);
    }
}

From source file:edu.ku.brc.specify.utilapps.sp5utils.Sp5Forms.java

/**
 * /*from w  ww  . ja v a  2 s . c o  m*/
 */
public synchronized void advance() {
    if (timer != null) {
        System.out.println("Task Cancelled. " + timer.hashCode());
        timer.cancel();
    }

    if (formIndex >= 0) {
        generate();
    }

    boolean doSkip = false;
    if (doSkip) {
        FormInfo fi;
        do {
            formIndex++;
            System.out.println(formIndex);
            if (formIndex >= forms.size()) {
                System.out.println("***** Done");
                generate();
                return;
            }
            fi = forms.get(formIndex);

        } while (!fi.isFull() && formIndex < forms.size());
    } else {
        formIndex++;
        System.out.println(formIndex);
        if (formIndex >= forms.size()) {
            System.out.println("***** Done");
            generate();
            createIndex();
            return;
        }
    }

    timer = new Timer();
    System.out.println("Scheduling next task. " + timer.hashCode());
    timer.schedule(new TimerTask() {
        public void run() {
            System.out.println("***** Timer Done");
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    advance();
                }
            });

        }
    }, 1500);
}

From source file:com.undatech.opaque.RemoteCanvasActivity.java

public void displayInputModeInfo(boolean showLonger) {
    if (showLonger) {
        final Toast t = Toast.makeText(this, inputHandler.getDescription(), Toast.LENGTH_LONG);
        TimerTask tt = new TimerTask() {
            @Override//from  w  ww. j a v  a 2  s  . com
            public void run() {
                t.show();
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                }
                t.show();
            }
        };
        new Timer().schedule(tt, 2000);
        t.show();
    } else {
        Toast t = Toast.makeText(this, inputHandler.getDescription(), Toast.LENGTH_SHORT);
        t.show();
    }
}

From source file:com.irccloud.android.NetworkConnection.java

public void logout(final String sk) {
    idleTimer.schedule(new TimerTask() {
        @Override/*w w  w  .jav  a 2s.  c om*/
        public void run() {
            try {
                Log.i("IRCCloud", "Invalidating session");
                fetch(new URL("https://" + IRCCLOUD_HOST + "/chat/logout"), "session=" + sk, sk, null, null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }, 50);
}

From source file:ca.weblite.jdeploy.JDeploy.java

private void init_old(String commandName) throws IOException {
    try {//from  w ww. j a v  a 2 s .  co m
        File packageJson = new File(directory, "package.json");
        if (!packageJson.exists()) {
            ProcessBuilder pb = new ProcessBuilder();
            pb.command(npm, "init");
            pb.inheritIO();
            final Process p = pb.start();
            Timer t = new Timer();

            TimerTask tt = new TimerTask() {

                @Override
                public void run() {
                    if (packageJson.exists()) {
                        p.destroy();
                        cancel();
                    }
                }

            };
            t.schedule(tt, new Date(System.currentTimeMillis() + 1000), 1000);

            int code = p.waitFor();

            if (!packageJson.exists() && code != 0) {
                System.err.println("Stopped init because npm init failed");
                System.exit(code);
            }
        }

        String pkgJsonStr = FileUtils.readFileToString(packageJson, "UTF-8");
        if (!pkgJsonStr.contains("shelljs")) {
            System.out.println("Installing shelljs");
            ProcessBuilder pb = new ProcessBuilder();
            pb.inheritIO();
            pb.command(npm, "install", "shelljs", "--save");
            Process p = pb.start();
            int result = p.waitFor();
            if (result != 0) {
                System.err.println("Failed to install shelljs");
                System.exit(result);
            }
        }

        // For some reason it never sticks in the package.json file the first time
        pkgJsonStr = FileUtils.readFileToString(packageJson, "UTF-8");
        if (!pkgJsonStr.contains("shelljs")) {
            System.out.println("Installing shelljs");
            ProcessBuilder pb = new ProcessBuilder();
            pb.inheritIO();
            pb.command(npm, "install", "shelljs", "--save");
            Process p = pb.start();
            int result = p.waitFor();
            if (result != 0) {
                System.err.println("Failed to install shelljs");
                System.exit(result);
            }
        }

        JSONParser parser = new JSONParser();
        Map contents = parser.parseJSON(new StringReader(pkgJsonStr));
        if (commandName == null) {
            commandName = (String) contents.get("name");
        }

        if (!contents.containsKey("bin")) {
            contents.put("bin", new HashMap());
        }
        Map bins = (Map) contents.get("bin");

        if (!bins.values().contains(getBinDir() + "/jdeploy.js")) {
            contents.put("preferGlobal", true);
            bins.put(commandName, getBinDir() + "/jdeploy.js");
            Result res = Result.fromContent(contents);
            FileUtils.writeStringToFile(packageJson, res.toString(), "UTF-8");
        }

        if (!contents.containsKey("files")) {
            contents.put("files", new ArrayList());
        }
        List files = (List) contents.get("files");
        if (!files.contains(getBinDir())) {
            files.add(getBinDir());
            Result res = Result.fromContent(contents);
            FileUtils.writeStringToFile(packageJson, res.toString(), "UTF-8");
        }

    } catch (InterruptedException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.gmail.boiledorange73.ut.map.MapActivityBase.java

/**
 * Starts location services and timer to stop after specfied time.
 * /* w ww .  ja v a2  s  . c om*/
 * @see http://d.hatena.ne.jp/orangesignal/20101223/1293079002
 */
private void startLocationService(boolean highaccuracy) {
    //
    this.stopLocationService();
    this.mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    if (this.mLocationManager == null) {
        // this device has no location service. DOES NOTHING.
        return;
    }

    // gets active location providers.
    // if requires high accuracy, creates filtered provider list.
    List<String> providerList = this.mLocationManager.getProviders(true);
    if (highaccuracy) {
        ArrayList<String> candidateList = new ArrayList<String>();
        if (providerList != null) {
            for (String providerName : providerList) {
                if (providerName != null) {
                    LocationProvider provider = this.mLocationManager.getProvider(providerName);
                    if (provider != null && provider.getAccuracy() == Criteria.ACCURACY_FINE) {
                        candidateList.add(providerName);
                    }
                }
            }
        }
        providerList = candidateList;
    }
    // checks whether at least one location provider is available.
    if (providerList == null || !(providerList.size() > 0)) {
        // Shows the dialog which let user to open system preference.
        AlertDialogHelper.showConfirmationDialog(this, Messages.getString("P_LOCATION_PROVIDER_ERROR"),
                Messages.getString("P_CONFIRM_OPEN_LOACTIONPROVIDER_SETTINGS"),
                android.R.drawable.ic_dialog_info, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(final DialogInterface dialog, final int which) {
                        try {
                            startActivity(new Intent("android.settings.LOCATION_SOURCE_SETTINGS"));
                        } catch (final ActivityNotFoundException e) {
                            // DOES NOTHING
                            e.printStackTrace();
                        }
                    }
                });
        this.stopLocationService();
        return;
    }
    // Starts timer. Checks whether timed out frequently,
    // and stops location services when specified time comes.
    final boolean onlyPassive = (providerList.size() == 1 && "passive".equals(providerList.get(0)));
    this.mLocationTimer = new Timer(true);
    this.mTimedOut = System.currentTimeMillis() + 30000L;
    final Handler handler = new Handler();
    this.mToast = Toast.makeText(this, Messages.getString("P_MYLOCATION_FINDING"), Toast.LENGTH_SHORT);
    this.mToast.show();
    this.mLocationTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            // Sends the procedure checks whether timed out.
            handler.post(new Runnable() {
                @Override
                public void run() {
                    long current = System.currentTimeMillis();
                    if (current >= MapActivityBase.this.mTimedOut) {
                        // timed out.
                        MapActivityBase.this.onLocationServiceTimedout(onlyPassive);
                    } else {
                        // NOT timed out. Shows the TOAST.
                        MapActivityBase.this.mToast.show();
                    }
                }
            });
        }
    }, 0L, 1000L);
    // starts
    this.mLocationListener = new LocationListener() {
        @Override
        public void onLocationChanged(final Location location) {
            // New location got. Sends it to JS.
            setLocation(location, true);
        }

        @Override
        public void onProviderDisabled(final String provider) {
            // DOES NOTHING.
        }

        @Override
        public void onProviderEnabled(final String provider) {
            // DOES NOTHING.
        }

        @Override
        public void onStatusChanged(final String provider, final int status, final Bundle extras) {
            // DOES NOTHING.
        }
    };
    for (String provider : providerList) {
        this.mLocationManager.requestLocationUpdates(provider, 0, 0, this.mLocationListener);
    }
}