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.mibr.android.intelligentreminder.INeedToo.java

/** Called when the activity is first created. */
@Override/*from   ww w .  j  a  v  a  2  s . c o  m*/
public void onCreate(Bundle savedInstanceState) {
    /* this was just a test      if(mLocationManager==null) {
             mLocationManager=(android.location.LocationManager) getSystemService(Context.LOCATION_SERVICE);
          }
    */
    //      TabHost host=this.getTabHost();
    //      host.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
    //         
    //         @Override
    //         public void onTabChanged(String tabId) {
    //            if(INeedToo.this._doingCreatingTabs==false) {
    //               if(tabId.equals("tab1")) {
    //                  INeedToo.this._forceNonCompany=true;
    //               }
    //            }
    //         }
    //      });
    super.onCreate(savedInstanceState);
    mLocationClient = new LocationClient(this, this, this);
    mLocationClient.connect();
    try {
        if (getIntent().getAction() != null && getIntent().getAction().equals("doPrimitiveDeletedNeed")) {
            transmitNetwork(getIntent().getStringExtra("phoneid"));
            return;
        }
    } catch (Exception eieio) {
        return;
    }
    try {
        /*
                    putExtra("needId",needId).
          putExtra("foreignNeedId",foreignNeedId).
          putExtra("phoneid",phoneid).
          putExtra("foreignLocationId",foreignLocationId)
                
         */
        if (getIntent().getAction() != null
                && getIntent().getAction().equals("transmitNetworkDeletedThisNeedByOnBehalfOf")) {
            long needId = getIntent().getLongExtra("needId", -11);
            long foreignNeedId = getIntent().getLongExtra("foreignNeedId", -11);
            String phoneId = getIntent().getStringExtra("phoneid");
            long foreignLocationId = getIntent().getLongExtra("foreignLocationId", -11);
            if (needId != -11 && foreignNeedId != -11 && foreignLocationId != -11 && isNothingNot(phoneId))
                transmitNetworkDeletedThisNeedByOnBehalfOf(needId, foreignNeedId, phoneId, foreignLocationId);
            return;
        }
    } catch (Exception ei3) {
        return;
    }

    /*bbhbb 2011-03-26*/ /*bbhbb2013_05_01 isn't this being done below?
                         *    Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler("")); */

    mHandler = new Handler();

    doBindService();
    mSingleton = this;
    ///////////mSingleton.log("onCreating_INeedToo", 1);

    if (getPackageName().toLowerCase().indexOf("trial") != -1 && !isSpecialPhone()) {
        if (!iveCheckedAuthorizationStatusForThisPhone) {
            doViewCount = true;
            iveCheckedAuthorizationStatusForThisPhone = true;
            final Timer jdTimer = new Timer("Registering");
            jdTimer.schedule(new TimerTask() {
                public void run() {
                    Thread thread = new Thread(new Runnable() {
                        public void run() {
                            Intent intent = new Intent(INeedToo.this, INeedWebService.class)
                                    .setAction("CheckStatus");
                            startService(intent);
                            jdTimer.cancel();
                        }
                    });
                    thread.setPriority(Thread.MIN_PRIORITY);
                    thread.run();
                }
            }, 3000, 1000 * 60 * 10);

        }
    } else {
        if (IS_ANDROID_VERSION) {
            if (!isSpecialPhone()
                    || INeedToo.mSingleton.getPhoneId().toLowerCase().equals("20013fc135cd6097xx")) {

                final Timer jdTimer = new Timer("Licensing");
                jdTimer.schedule(new TimerTask() {
                    public void run() {
                        Thread thread = new Thread(new Runnable() {
                            public void run() {
                                // Construct the LicenseCheckerCallback. The library calls this when done.        
                                mLicenseCheckerCallback = new MyLicenseCheckerCallback();
                                // Construct the LicenseChecker with a Policy.        
                                mChecker = new LicenseChecker(INeedToo.this,
                                        new ServerManagedPolicy(INeedToo.this,
                                                new AESObfuscator(SALT, getPackageName(),
                                                        //                           "com.mibr.android.intelligentreminder",
                                                        getDeviceId())),
                                        BASE64_PUBLIC_KEY // Your public licensing key.
                                );
                                mChecker.checkAccess(mLicenseCheckerCallback);
                            }
                        });
                        thread.setPriority(Thread.MIN_PRIORITY);
                        thread.run();
                    }
                }, 3000, 1000 * 60 * 10);
            }
        }
    }

    try {
        _logFilter = Integer
                .valueOf(getSharedPreferences(INeedToo.PREFERENCES_LOCATION, Preferences.MODE_PRIVATE)
                        .getString("LoggingLevel", "3"));
    } catch (Exception e) {
    }

    if (!INeedLocationService.USING_LOCATION_SERVICES) {

        int logFilter = 3;
        try {
            logFilter = Integer
                    .valueOf(getSharedPreferences(INeedToo.PREFERENCES_LOCATION, Preferences.MODE_PRIVATE)
                            .getString("LoggingLevel", "3"));
        } catch (Exception e) {
        }
        Intent jdIntent = new Intent(this, INeedTimerServices.class).putExtra("logFilter", logFilter);

        getApplicationContext().startService(jdIntent);
    }
    Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(""));
    if (INeedToo.mSingleton.getPhoneId().toLowerCase().equals("22a100000d9f25c5")) {
        DELAYPOSTTTS = 100;
    }

    // I don't need this because IHaveNeeds.onresume does it      getApplicationContext().startService(new Intent(this, INeedLocationService.class));
    if (!_doneSplashy) {
        _doneSplashy = true;
        if (!getVersionFile()) {
            stampVersion();
            showDialog(DIALOG_SPLASH);
        } else {
            //showDialog(DIALOG_SPLASH);
        }
    }
    if (allItems != null) {
        whereImAtInAllItems++;
        if (whereImAtInAllItems < allItems.size()) {
            showDialog(DOING_SAMPLE_NEEDS_DIALOG);
        } else {
            allItems = null;
        }
    }

    setTitle(getHeading());
    Bundle bundle = getIntent().getExtras();
    if (bundle != null) {
        _initialTabIndex = bundle.getInt("initialtabindex", 0);
        _didContact = bundle.getBoolean("iscontact", false);
        if (_initialTabIndex == 1) {
            _doingLocationCompany = bundle.getString("doingcompany");
        } else {
            _doingLocationCompany = null;
        }
    } else {
        _doingLocationCompany = null;
    }
    final TabHost tabHost = getTabHost();
    tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("Need",

            getResources().getDrawable(R.drawable.status_bar2_blackwhite))
            .setContent(new Intent(this, IHaveNeeds.class).putExtra("iscontact", this._didContact)));

    tabHost.addTab(tabHost.newTabSpec("tab2")
            .setIndicator("Location",
                    (BitmapDrawable) getResources().getDrawable(android.R.drawable.ic_menu_mapmode))
            .setContent(
                    new Intent(this, IHaveLocations.class).putExtra("doingcompany", _doingLocationCompany)));
    Intent intent = new Intent(this, NeedMap.class).putExtra("doingcompany", _doingLocationCompany);
    tabHost.addTab(tabHost.newTabSpec("tab2a")
            .setIndicator("Map", (BitmapDrawable) getResources().getDrawable(R.drawable.ic_dialog_map))
            .setContent(intent));
    /*
    tabHost.addTab(tabHost.newTabSpec("tab3").setIndicator(
    "History",(BitmapDrawable) getResources().getDrawable(
          R.drawable.chart)).setContent(
                new Intent(this, IHaveHistory.class)));
    */
    tabHost.addTab(tabHost.newTabSpec("tab4")
            .setIndicator("System",
                    (BitmapDrawable) getResources().getDrawable(R.drawable.status_bar1_blackwhite))
            .setContent(new Intent(this, ListPlus.class)));
    /*      tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator(
    "Need",
    scaleTo((BitmapDrawable) getResources().getDrawable(
          R.drawable.status_bar2_blackwhite), 36f)).setContent(
                new Intent(this, IHaveNeeds.class).putExtra("iscontact", this._didContact)));
            
    tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator(
       "Location",
       scaleTo((BitmapDrawable) getResources().getDrawable(
             android.R.drawable.ic_menu_mapmode), 36f)).setContent(
                   new Intent(this, IHaveLocations.class).putExtra("doingcompany", _doingLocationCompany)));
    tabHost.addTab(tabHost.newTabSpec("tab3").setIndicator(
    "History",
    scaleTo((BitmapDrawable) getResources().getDrawable(
          R.drawable.chart), 36f)).setContent(
                new Intent(this, IHaveHistory.class)));
    tabHost.addTab(tabHost.newTabSpec("tab4").setIndicator(
    "System",
    scaleTo((BitmapDrawable) getResources().getDrawable(
          R.drawable.status_bar1_blackwhite), 31f)).setContent(
                new Intent(this, ListPlus.class)));
    */
    tabHost.setCurrentTab(_initialTabIndex);
    boolean networkingOutbound = getSharedPreferences(INeedToo.PREFERENCES_LOCATION, Preferences.MODE_PRIVATE)
            .getBoolean("Networking_Outbound_Enabled", false);
    if (INeedWebService.mSingleton == null) {

        if (networkingOutbound) {
            enableTransmitting();
        }
        if (getSharedPreferences(INeedToo.PREFERENCES_LOCATION, Preferences.MODE_PRIVATE)
                .getBoolean("Networking_Inbound_Enabled", false)) {
            enableReceiving();
        }
    }
}

From source file:io.fabric8.mq.autoscaler.MQAutoScaler.java

private void startTimerTask() {
    if (started.get()) {
        if (timerTask != null) {
            timerTask.cancel();/*  w ww .j  ava2  s .  com*/
        }
        timerTask = new TimerTask() {
            @Override
            public void run() {
                LOG.info("Checking Load across Fabric8MQ group: " + getGroupName());
                validateMQLoad();
            }
        };
        long pollTime = getPollTime() * 1000;
        timer.schedule(timerTask, pollTime, pollTime);
    }
}

From source file:com.github.vatbub.tictactoe.view.Main.java

private void reloadImage(ImageView imageView, String imageURL, double newWidth, double newHeight) {
    if (loadTimerMap.get(imageURL) != null) {
        loadTimerMap.get(imageURL).cancel();
    }//www .j av  a  2s  . c o m

    Timer loadTimer = new Timer();
    loadTimerMap.put(imageURL, loadTimer);
    loadTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            Image image = new Image(imageURL, newWidth, newHeight, false, true);
            Platform.runLater(() -> imageView.setImage(image));
        }
    }, 300);
}

From source file:com.vladsch.idea.multimarkdown.editor.MultiMarkdownFxPreviewEditor.java

protected void delayedHtmlPreviewUpdate(final boolean fullKit) {
    if (updateDelayTimer != null) {
        updateDelayTimer.cancel();/*from  ww w  .ja  v a 2 s  .c  om*/
        updateDelayTimer = null;
    }

    if (project.isDisposed())
        return;

    if (!isEditorTabVisible)
        return;

    updateDelayTimer = new Timer();
    updateDelayTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            if (project.isDisposed())
                return;

            ApplicationManager.getApplication().invokeLater(new Runnable() {
                @Override
                public void run() {
                    if (project.isDisposed())
                        return;

                    previewIsObsolete = true;

                    if (fullKit) {
                        needStyleSheetUpdate = true;
                        //processor.remove();     // make it re-initialize when accessed
                    }
                    updateHtmlContent(isActive || isMyTabSelected());
                }
            }, ModalityState.any());
        }
    }, getUpdateDelay());
}

From source file:it.polimi.geinterface.GroupEntityManager.java

@Override
public void getAllEntitiesInProximity(final DistanceRange distance, Group g,
        final ActionOutcomeCallback callback, long millisec, final ArrayList<Entity> result) {

    //In this case, it means that a syncRequest is already running
    if (syncRespEntityList != null)
        return;/*from ww  w. j  a  v a 2 s.c  o m*/

    syncRespEntityList = result;

    //Creation of a unique topic where receive syncResp messages
    final String newTopic = new Random().nextInt(10000) + "-reqTopic";

    networkClient.susbcribe(newTopic);

    ArrayList<Entity> lastBeacons;

    synchronized (lastSeenBeacons) {
        lastBeacons = new ArrayList<>(lastSeenBeacons);
    }

    long timestamp = Calendar.getInstance().getTimeInMillis() + LoggerService.NTP_DELAY;
    String logId = selfEntity.getEntityID() + timestamp;

    networkClient.publishMessage(MessageTopic.BROADCAST.name(), MessageUtils
            .buildSyncReqMessage(selfEntity.getEntityID(), newTopic, lastBeacons, g, distance, logId));

    //logging
    String log = LogMessageUtils.buildMessageSentLog(logId, selfEntity.getEntityID(), Type.DEVICE,
            MessageType.SYNC_REQ, newTopic, false, timestamp);
    LoggerService.writeToFile(appCtx, log);

    if (checkInTimer == null)
        checkInTimer = new Timer(true);

    checkInTimer.schedule(new TimerTask() {

        @Override
        public void run() {
            networkClient.unsusbcribe(newTopic);

            synchronized (syncObj) {
                syncRespEntityList = null;
            }

            ArrayList<Entity> lastBeacons;

            synchronized (lastSeenBeacons) {
                lastBeacons = new ArrayList<>(lastSeenBeacons);
            }

            //Beacons in proximity added to result list
            ArrayList<Entity> beacons = lastBeacons;
            for (Entity e : beacons)
                if (e.getDistanceRange().ordinal() <= distance.ordinal())
                    result.add(e);

            callback.onCompleted();
        }
    }, millisec);
}

From source file:com.newsrob.EntryManager.java

private synchronized void updateWidgets() {

    if (updateWidgetsTimer == null)
        updateWidgetsTimer = new Timer("UpdateWidgetsTimer", false);

    if (updateWidgetsTimerTask != null) {
        updateWidgetsTimerTask.cancel();
        updateWidgetsTimerTask = null;/*from  w ww .  j av a 2  s  .c  o m*/
    }

    if (lastUpdateWidgetUpdate == null
            || (lastUpdateWidgetUpdate + (3 * 60 * 1000)) < System.currentTimeMillis()) {
        UnreadWidgetProvider.requestWidgetsUpdate(ctx);
        lastUpdateWidgetUpdate = System.currentTimeMillis();
    } else {
        updateWidgetsTimerTask = new TimerTask() {

            @Override
            public void run() {
                UnreadWidgetProvider.requestWidgetsUpdate(ctx);
                lastUpdateWidgetUpdate = System.currentTimeMillis();

                // ADW Notification
                if (isADWLauncherInterestedInNotifications()) {

                    Intent i = new Intent();
                    i.setAction("org.adw.launcher.counter.SEND");
                    i.putExtra("PNAME", "com.newsrob");
                    i.putExtra("COUNT", getUnreadArticleCount());
                    ctx.sendBroadcast(i);
                    PL.log("EntryManager.updateWidgets sent notification to ADW.", ctx);
                }

            }

        };
        updateWidgetsTimer.schedule(updateWidgetsTimerTask, 35 * 1000);
    }
}

From source file:com.insthub.O2OMobile.Activity.C1_PublishOrderActivity.java

/**
 * /*  w  w w  .j  a  v  a  2s. co m*/
 */
private void startRecording() {
    mFileName = newFileName();
    //
    try {
        mRecorder = new MediaRecorder();
        //?
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        //???
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
        mRecorder.setAudioSamplingRate(8000);
        mRecorder.setAudioEncodingBitRate(16);
        //??
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        mRecorder.setOutputFile(mFileName);
        mRecorder.prepare();
        mRecorder.start();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (IllegalStateException e2) {
        e2.printStackTrace();
    }

    mTimer = new Timer();
    TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            mMaxTime--;
            Message msg = new Message();
            msg.what = mMaxTime;
            handler.sendMessage(msg);
        }
    };
    mTimer.schedule(timerTask, 1000, 1000);
}

From source file:com.thebuzzmedia.exiftool.ExifTool.java

/**
 * Will attempt 3 times to use the running exif process, and if unable to
 * complete successfully will throw IOException
 *//*from   w ww  .j  a v a2  s  . c  o  m*/
private Map<String, String> processStayOpen(List<String> args) throws IOException {
    int attempts = 0;
    while (attempts < 3 && !shuttingDown.get()) {
        attempts++;
        // make sure process is started
        ensureProcessRunning();
        TimerTask attemptTimer = null;
        try {
            if (timeoutWhenKeepAlive > 0) {
                attemptTimer = new TimerTask() {
                    @Override
                    public void run() {
                        log.warn("Process ran too long closing, max " + timeoutWhenKeepAlive + " mills");
                        process.close();
                    }
                };
                cleanupTimer.schedule(attemptTimer, timeoutWhenKeepAlive);
            }
            log.debug("Streaming arguments to ExifTool process...");
            return process.sendArgs(args);
        } catch (IOException ex) {
            if (STREAM_CLOSED_MESSAGE.equals(ex.getMessage()) && !shuttingDown.get()) {
                // only catch "Stream Closed" error (happens when process
                // has died)
                log.warn(String.format("Caught IOException(\"%s\"), will restart daemon",
                        STREAM_CLOSED_MESSAGE));
                process.close();
            } else {
                throw ex;
            }
        } finally {
            if (attemptTimer != null)
                attemptTimer.cancel();
        }
    }
    if (shuttingDown.get()) {
        throw new IOException("Shutting Down");
    }
    throw new IOException("Ran out of attempts");
}

From source file:com.fullteem.yueba.app.adapter.MessageAdapter.java

/**
 * ?//  w ww . j a  v a  2 s. c om
 * 
 * @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() {
                    @Override
                    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), 0).show();
                            timer.cancel();
                        }

                    }
                });

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