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.snappy.GCMIntentService.java

/**
 * Issues a notification to inform the user that server has sent a message.
 *//*from  w  w  w . j ava  2  s . co m*/
private void generateNotification(Context context, String message, String fromName, Bundle pushExtras,
        String body) {

    db = new LocalDB(context);
    List<LocalMessage> myMessages = db.getAllMessages();

    // Open a new activity called GCMMessageView
    Intent intento = new Intent(this, SplashScreenActivity.class);
    intento.replaceExtras(pushExtras);
    // Pass data to the new activity
    intento.putExtra(Const.PUSH_INTENT, true);
    intento.setAction(Long.toString(System.currentTimeMillis()));
    intento.addFlags(
            Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_FROM_BACKGROUND | Intent.FLAG_ACTIVITY_TASK_ON_HOME);

    // Starts the activity on notification click
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intento, PendingIntent.FLAG_UPDATE_CURRENT);

    // Create the notification with a notification builder
    NotificationCompat.Builder notification = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.icon_notification).setWhen(System.currentTimeMillis())
            .setContentTitle(myMessages.size() + " " + this.getString(R.string.push_new_message_message))
            .setStyle(new NotificationCompat.BigTextStyle().bigText("Mas mensajes")).setAutoCancel(true)
            .setDefaults(
                    Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS)
            .setContentText(body).setContentIntent(pIntent);

    NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
    inboxStyle.setBigContentTitle(myMessages.size() + " " + this.getString(R.string.push_new_message_message));

    for (int i = 0; i < myMessages.size(); i++) {

        inboxStyle.addLine(myMessages.get(i).getMessage());
    }

    notification.setStyle(inboxStyle);

    // Remove the notification on click
    //notification.flags |= Notification.FLAG_AUTO_CANCEL;
    //notification.defaults |= Notification.DEFAULT_VIBRATE;
    //notification.defaults |= Notification.DEFAULT_SOUND;
    //notification.defaults |= Notification.DEFAULT_LIGHTS;

    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    manager.notify(R.string.app_name, notification.build());
    {
        // Wake Android Device when notification received
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);

        final PowerManager.WakeLock mWakelock = pm
                .newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "GCM_PUSH");
        mWakelock.acquire();
        // Timer before putting Android Device to sleep mode.
        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            public void run() {
                mWakelock.release();
            }
        };
        timer.schedule(task, 5000);
    }
}

From source file:cl.tide.fm.sensonet.SensonetClient.java

private void checkingNetwork() {
    netTimer = new Timer();
    netTimer.schedule(new TimerTask() {
        @Override// w  ww .  jav  a  2  s .  co m
        public void run() {
            boolean status = netIsAvailable();
            if (status != isOnline) {
                isOnline = status;
                System.out.println("Network " + status);
                if (listener != null) {
                    listener.isOnline(isOnline);
                }
            }
        }
    }, 0, 5000);
}

From source file:src.com.nustats.pacelogger.RecordingActivity.java

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

    timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override/*w  w  w .  j a v  a  2  s.  c o m*/
        public void run() {
            mHandler.post(mUpdateTimer);
        }
    }, 0, 1000); // every second
}

From source file:com.chaosinmotion.securechat.messages.SCMessageQueue.java

/**
 * Start polling. Reason is for debugging only
 *//* w w  w.jav  a 2 s.  c  om*/

private void startPolling(String reason) {
    Log.d("SecureChat", "Polling because " + reason);

    if (timer == null) {
        timer = new Timer();
    }
    timerTask = new TimerTask() {
        @Override
        public void run() {
            pollForMessages();
        }
    };

    timer.schedule(timerTask, 0, POLLRATE);
}

From source file:kilim.Task.java

/**
 * @param millis/*from w w w.j ava 2s .  c o  m*/
 * to sleep. Like thread.sleep, except it doesn't throw an interrupt, and it
 * doesn't hog the java thread.
 */
public static void sleep(final long millis) throws Pausable {
    // create a temp mailbox, and wait on it.
    final Mailbox<Integer> sleepmb = new Mailbox<Integer>(1); // TODO: will need a better mechanism for monitoring later on.
    timer.schedule(new TimerTask() {
        public void run() {
            sleepmb.putnb(0);
        }
    }, millis);
    sleepmb.get(); // block until a message posted
}

From source file:coria2015.server.JsonRPCMethods.java

/**
     * Shutdown the server/*from  w  ww .j a  va 2s.com*/
     */
    @RPCMethod(help = "Shutdown Experimaestro server")
    public boolean shutdown() {
        // Shutdown jetty (after 1s to allow this thread to finish)
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                boolean stopped = false;
                try {
                    server.stop();
                    stopped = true;
                } catch (Exception e) {
                    LOGGER.warning("Could not stop properly jetty");
                }
                if (!stopped)
                    synchronized (this) {
                        try {
                            wait(10000);
                        } catch (InterruptedException e) {
                            LOGGER.severe(e.toString());
                        }
                        System.exit(1);

                    }
            }
        }, 2000);

        // Everything's OK
        return true;
    }

From source file:com.huofu.RestaurantOS.ui.splash.activate.java

/**
 * ?//  ww  w.  ja  v  a2 s. c  o  m
 */
public void init() {

    MainApplication.setmActivity(this);
    rl_activate = (RelativeLayout) findViewById(R.id.rl_activate);
    rl_activate_input = (RelativeLayout) findViewById(R.id.rl_activate_code_input);
    rl_activate_qrscan_ready = (RelativeLayout) findViewById(R.id.rl_activate_qrcode_scan_ready);

    ctxt = getApplicationContext();

    buttonActivate = (Button) findViewById(R.id.buttonActivate);
    buttonSwitchInputCode = (Button) findViewById(R.id.button_switch_acitvate_keyboard_way);
    buttonSwitchQrScan = (Button) findViewById(R.id.button_activate_switch_to_qrscan);

    textviewScanStauts = (TextView) findViewById(R.id.textview_activate_status);

    etActivteCode = (EditText) findViewById(R.id.editTextActivateCode);

    titanic = new Titanic();
    ttv = new TitanicTextView(getApplicationContext());

    bitmapUtils = new BitmapUtils(getApplicationContext(), pathAcitvateCache, 150 * 1024 * 1024,
            150 * 1024 * 1024);
    bigPicDisplayConfig = new BitmapDisplayConfig();
    bigPicDisplayConfig.setShowOriginal(true); // ,?, ???, OOM
    callback = new DefaultBitmapLoadCallBack<ImageView>() {
        public void onLoadCompleted(ImageView container, String uri, android.graphics.Bitmap bitmap,
                BitmapDisplayConfig config, com.lidroid.xutils.bitmap.callback.BitmapLoadFrom from) {

            CommonUtils.sendMsg("", HIDE_LOADING, mUiHandler);

            imageViewQrcode.setVisibility(View.VISIBLE);
            imageViewQrcode.setBackgroundDrawable(new BitmapDrawable(bitmap));
            stopQrScanTimer();

            timerQrcode = new Timer();
            timerTaskQrcode = new TimerTask() {

                @Override
                public void run() {

                    if (!flagActivate) {
                        timerTaskQrcode.cancel();
                        timerQrcode.cancel();
                        return;
                    }

                    long qrcodeLastTime = System.currentTimeMillis() / 1000 - qrcodeCreateTime;
                    CommonUtils.LogWuwei(tag, "qrcodeLastTime is " + qrcodeLastTime);
                    if (qrcodeLastTime > 300) {
                        timerTaskQrcode.cancel();
                        timerQrcode.cancel();
                        sendUIMessage(SHOW_QRCODE_REFRSH_AGAIN, "");
                        return;
                    }

                    // TODO Auto-generated method stub
                    if (active) {
                        ApisManager.ScanAuthQrcode(tokenQrcode, new ApiCallback() {
                            @Override
                            public void success(Object object) {
                                sendUIMessage(HIDE_LOADING, "");
                                JSONObject oj = (JSONObject) object;

                                if (Integer.parseInt(oj.getString("status")) != 1) {
                                    return;
                                }
                                String status = oj.getString("related_status");

                                if (status.equals("5") || status.equals("3") && activate.active)//?
                                {
                                    if (activate.flagAuthSuccess) {
                                        return;
                                    }

                                    activate.flagAuthSuccess = true;

                                    if (activate.active) {
                                        CommonUtils.sendMsg(null, activate.STOP_SCAN_QRCODE_TIMER, mUiHandler);
                                        String master_key = oj.getString("master_key");
                                        LocalDataDeal.writeToLocalMasterKey(master_key, ctxt);

                                        String client_id = oj.getString("client_id");
                                        LocalDataDeal.writeToLocalClientId(client_id, ctxt);
                                        CommonUtils.sendMsg("", SCAN_QRCODE_SUCCESS, mUiHandler);
                                    }

                                } else if (status.equals("1")) {
                                    CommonUtils.sendMsg("?",
                                            UPDATE_QRCODE_SCAN_STATUS, mUiHandler);
                                } else if (status.equals("2")) {
                                    CommonUtils.sendMsg("",
                                            UPDATE_QRCODE_SCAN_STATUS, mUiHandler);
                                } else if (status.equals("4")) {
                                    activate.flagWaitingCmd = true;
                                    CommonUtils.sendMsg("",
                                            UPDATE_QRCODE_SCAN_STATUS, mUiHandler);
                                } else if (status.equals("6"))//?????
                                {
                                    activate.flagWaitingCmd = false;
                                    activate.stopQrScanTimer();
                                    CommonUtils.sendMsg("???", AUTH_FAILED, mUiHandler);
                                } else if (status.equals("7")) {
                                    activate.flagWaitingCmd = false;
                                    activate.stopQrScanTimer();
                                    CommonUtils.sendMsg("??", AUTH_FAILED,
                                            mUiHandler);
                                } else if (status.equals("0")) {
                                    activate.flagWaitingCmd = false;
                                    activate.stopQrScanTimer();
                                    CommonUtils.sendMsg("???", AUTH_FAILED, mUiHandler);
                                }
                            }

                            @Override
                            public void error(BaseApi.ApiResponse response) {
                                sendUIMessage(HIDE_LOADING, "");
                            }
                        });
                    }

                }
            };
            timerQrcode.schedule(timerTaskQrcode, 0, 1000);
        }
    };
    imageViewQrcode = (ImageView) findViewById(R.id.imageview_activate_qrcode_scan);

    PackageManager manager;
    PackageInfo info = null;
    manager = this.getPackageManager();
    String versionName = null;
    try {
        info = manager.getPackageInfo(this.getPackageName(), 0);
        versionName = info.versionName;
        String version = CommonUtils.getSringAfterChar(versionName, 'V');
        LocalDataDeal.writeToLocalVersionName(ctxt, version);
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }
}

From source file:edu.cens.loci.sensors.AccelerometerHandler.java

private void startChkTimer() {
    mFlag = false;//from ww w . j  a  va  2  s.co m
    mChkTimer = new Timer(TIMER_CHECK_ACC);
    mChkTimer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            if (isOn() && !mFlag) {
                MyLog.e(LociConfig.D.SYS, TAG,
                        "[ACC] (check timer) Movement Detector is not receiving Accel data. restart handler.");

                if (isOn())
                    stop();

                Timer restartTimer = new Timer(TIMER_RESTART_ACC);
                restartTimer.schedule(new TimerTask() {
                    public void run() {
                        MyLog.e(LociConfig.D.SYS, TAG, "[ACC] (check timer) Restart Accelerometer.");
                        start();
                    }
                }, 500);

            } else {
                MyLog.e(LociConfig.D.SYS, TAG, "[ACC] (check timer) Movement Detector OK.");
            }
            mFlag = false;
        }
    }, LociConfig.pAccWatch, LociConfig.pAccWatch);
}

From source file:com.willwinder.ugs.nbp.setupwizard.panels.WizardPanelConnection.java

private void startConnectTimer() {
    if (!finishedConnecting && finishedConnectingTimer == null) {
        finishedConnectingTimer = new Timer();
        finishedConnectingTimer.schedule(new TimerTask() {
            @Override//from   w w w . j  a  v  a  2s.  c  o m
            public void run() {
                finishedConnecting = true;
                finishedConnectingTimer = null;
                refreshComponents();
            }
        }, CONNECT_TIME);
    }
}

From source file:com.leacox.pusherclient.PusherClient.java

private void resetActivityTimer() {
    if (activityTimer != null) {
        activityTimer.cancel();//ww  w. j ava  2s  .c o  m
    }

    activityTimer = new Timer();
    activityTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            logger.debug("Sending PING");
            send("pusher:ping", new JSONObject());
            activityTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    try {
                        logger.debug("Did not receive PONG: Closing connection");
                        webSocket.close();
                    } catch (WebSocketException e) {
                        logger.error("Error closing web socket connection", e);
                    }
                }
            }, 30000);
        }
    }, 120000);
}