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:org.linphone.LinphoneService.java

@Override
public void onCreate() {
    super.onCreate();
    theLinphone = this;

    // Dump some debugging information to the logs
    Hacks.dumpDeviceInformation();//from w w w .  ja  v a 2s . co m
    addCallListner();
    //      tryTogetLastReceive();
    //      tryTogetLastRequest();
    tryKeepOnline();
    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotification = new Notification(R.drawable.status_level, "", System.currentTimeMillis());
    mNotification.iconLevel = IC_LEVEL_ORANGE;
    mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
    Intent notificationIntent = new Intent(this, MainViewActivity.class);
    mNofificationContentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    mNotification.setLatestEventInfo(this, NOTIFICATION_TITLE, "", mNofificationContentIntent);
    mNotificationManager.notify(NOTIFICATION_ID, mNotification);
    mPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    mAudioManager = ((AudioManager) getSystemService(Context.AUDIO_SERVICE));
    mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    try {
        copyAssetsFromPackage();

        mLinphoneCore = LinphoneCoreFactory.instance().createLinphoneCore(this, LINPHONE_RC,
                LINPHONE_FACTORY_RC, null);

        mLinphoneCore.setPlaybackGain(3);
        mLinphoneCore.setRing(null);

        try {
            initFromConf();
        } catch (LinphoneException e) {
            Log.w(TAG, "no config ready yet");
        }
        TimerTask lTask = new TimerTask() {
            @Override
            public void run() {
                mLinphoneCore.iterate();
            }

        };

        mTimer.scheduleAtFixedRate(lTask, 0, 100);
        IntentFilter lFilter = new IntentFilter(Intent.ACTION_SCREEN_ON);
        lFilter.addAction(Intent.ACTION_SCREEN_OFF);
        registerReceiver(mKeepAliveMgrReceiver, lFilter);

    } catch (Exception e) {
        Log.e(TAG, "Cannot start linphone", e);
    }

}

From source file:de.yaacc.upnp.server.YaaccUpnpServerService.java

/**
 * start sending periodical upnp alive notifications.
 *//*from ww  w  .j  a v  a  2  s  .c  om*/
private void startUpnpAliveNotifications() {
    int upnpNotificationFrequency = getUpnpNotificationFrequency();
    if (upnpNotificationFrequency != -1
            && preferences.getBoolean(getString(R.string.settings_local_server_chkbx), false)) {
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                Log.d(YaaccUpnpServerService.this.getClass().getName(), "Sending upnp alive notivication");
                SendingNotificationAlive sendingNotificationAlive = null;
                if (localServer != null) {
                    sendingNotificationAlive = new SendingNotificationAlive(
                            getUpnpClient().getRegistry().getUpnpService(), localServer);
                    sendingNotificationAlive.run();
                }
                if (localRenderer != null) {
                    sendingNotificationAlive = new SendingNotificationAlive(
                            getUpnpClient().getRegistry().getUpnpService(), localRenderer);
                    sendingNotificationAlive.run();
                }
                startUpnpAliveNotifications();
            }
        }, upnpNotificationFrequency);

    }
}

From source file:com.corporatetaxi.TaxiOntheWay_Activity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_taxiontheway);
    taxiOntheWay_activity_instance = this;
    AppPreferences.setApprequestTaxiScreen(TaxiOntheWay_Activity.this, true);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitleTextColor(Color.BLACK);
    setSupportActionBar(toolbar);//from  w w  w .j av a2 s . c  o m
    // getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    String title = getString(R.string.title_activity_taxidetail);
    getSupportActionBar().setTitle(title);

    fab_menu = (FloatingActionsMenu) findViewById(R.id.fab_menu);
    fab_msg = (FloatingActionButton) findViewById(R.id.fab_message);
    fab_call = (FloatingActionButton) findViewById(R.id.fab_call);
    fab_cancel = (FloatingActionButton) findViewById(R.id.fab_cancel);

    textheader = (TextView) findViewById(R.id.textheader);
    textname = (TextView) findViewById(R.id.name_text);
    textmobilenumber = (TextView) findViewById(R.id.mobile_text);
    textcompanyname = (TextView) findViewById(R.id.companyname);
    texttaxinumber = (TextView) findViewById(R.id.taxinumber);
    taxiname = (TextView) findViewById(R.id.taxinametext);
    mtextnamehead = (TextView) findViewById(R.id.namehead);
    mtextcompanyhead = (TextView) findViewById(R.id.companyhead);
    mtextmobilehead = (TextView) findViewById(R.id.mobilehead);
    mtexttexinumhead = (TextView) findViewById(R.id.taxiplatthead);
    taxinamehead = (TextView) findViewById(R.id.taxinamehead);
    mdriverimage = (ImageView) findViewById(R.id.driver_image);
    mdriverlicense = (TextView) findViewById(R.id.driverlicense);
    medriverinsurance = (TextView) findViewById(R.id.driverinsurance);

    map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
    map.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    getLocation();

    Typeface tf = Typeface.createFromAsset(this.getAssets(), "Montserrat-Regular.ttf");

    textheader.setTypeface(tf);
    mtextnamehead.setTypeface(tf);
    mtextcompanyhead.setTypeface(tf);
    mtextmobilehead.setTypeface(tf);
    mtexttexinumhead.setTypeface(tf);
    textname.setTypeface(tf);
    textmobilenumber.setTypeface(tf);
    textcompanyname.setTypeface(tf);
    texttaxinumber.setTypeface(tf);
    taxinamehead.setTypeface(tf);
    taxiname.setTypeface(tf);
    mdriverlicense.setTypeface(tf);
    medriverinsurance.setTypeface(tf);

    ////////current date time//////////////////
    currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
    Log.d("currentdatetime", currentDateTimeString);

    /////back arrow ////////////
    //        final Drawable upArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
    //        upArrow.setColorFilter(getResources().getColor(R.color.colorbutton), PorterDuff.Mode.SRC_ATOP);
    //        getSupportActionBar().setHomeAsUpIndicator(upArrow);

    /////////////notification data///////////////
    Intent intent = getIntent();
    String data = intent.getStringExtra("data");
    Log.d("data value", data + "");
    // caceldialog();
    JSONObject jsonObject = null;
    try {
        jsonObject = new JSONObject(data);
        AppPreferences.setAcceptdriverId(TaxiOntheWay_Activity.this, jsonObject.getString("driverId"));
        Log.d("driverid---", AppPreferences.getAcceptdriverId(TaxiOntheWay_Activity.this));
        drivermobile = jsonObject.getString("mobile");
        drivername = jsonObject.getString("username");
        drivercompanyname = jsonObject.getString("taxicompany");
        drivertaxiname = jsonObject.getString("vehicalname");
        drivertexinumber = jsonObject.getString("vehicle_number");
        // driverlatitude = jsonObject.getDouble("latitude");
        // driverlongitude = jsonObject.getDouble("longitude");
        driverimage = jsonObject.getString("driverImage");
        SourceAddress = jsonObject.getString("source_address");
        sourcelatitude = jsonObject.getDouble("source_latitude");
        sourcelongitude = jsonObject.getDouble("source_longitude");
        driverlicense = jsonObject.getString("driverlicense");
        driverinsurance = jsonObject.getString("driverinsurance");

        Log.d("driveriamge", driverimage);

        final LatLng loc = new LatLng(new Double(sourcelatitude), new Double(sourcelongitude));
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 15));
        MarkerOptions marker = new MarkerOptions().position(loc).title(SourceAddress);
        marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_three));
        map.addMarker(marker);

        textname.setText(drivername);
        textmobilenumber.setText(drivermobile);
        textcompanyname.setText(drivercompanyname);
        texttaxinumber.setText(drivertexinumber);
        taxiname.setText(drivertaxiname);
        mdriverlicense.setText(driverlicense);
        medriverinsurance.setText(driverinsurance);

        if (mdriverlicense.length() == 0) {
            mdriverlicense.setVisibility(View.GONE);
        }
        if (medriverinsurance.length() == 0) {
            medriverinsurance.setVisibility(View.GONE);
        }

        Intent intent1 = new Intent(TaxiOntheWay_Activity.this, DriverService.class);
        intent1.putExtra("driverId", jsonObject.getString("driverId"));
        startService(intent1);

        //            loc2 = new LatLng(driverlatitude, driverlongitude);
        //            MarkerOptions marker2 = new MarkerOptions().position(loc2);
        //            marker2.icon(BitmapDescriptorFactory.fromResource(R.drawable.drivertaxi));
        //            map.addMarker(marker2);
        Timer timer;
        TimerTask task;
        int delay = 10000;
        int period = 10000;

        timer = new Timer();

        timer.scheduleAtFixedRate(task = new TimerTask() {
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        /*loc2 = new LatLng(new Double(AppPreferences.getCurrentlat(TaxiOntheWay_Activity.this)),
                            new Double(AppPreferences.getCurrentlong(TaxiOntheWay_Activity.this)));
                        MarkerOptions marker2 = new MarkerOptions().position(loc2);
                        map.clear();
                        marker2.icon(BitmapDescriptorFactory.fromResource(R.drawable.drivertaxi));
                        map.addMarker(marker2.title(drivername));*/
                        loc2 = new LatLng(new Double(AppPreferences.getCurrentlat(TaxiOntheWay_Activity.this)),
                                new Double(AppPreferences.getCurrentlong(TaxiOntheWay_Activity.this)));

                        if (marker1 == null) {
                            marker1 = map.addMarker(new MarkerOptions().position(loc2).title(drivername)
                                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.drivertaxi)));

                        }
                        animateMarker(marker1, loc2, false);

                    }
                });

            }
        }, delay, period);

    } catch (JSONException e) {
        e.printStackTrace();
    }
    /////////////notification dataend///////////////
    fab_cancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            initiatePopupWindowcanceltaxi();
        }
    });

    fab_msg.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            initiatePopupWindowsendmesage();
        }
    });
    fab_call.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent callIntent = new Intent(Intent.ACTION_CALL);
            callIntent.setData(Uri.parse("tel:" + drivermobile));
            startActivity(callIntent);
        }
    });

    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    if (driverimage.equalsIgnoreCase("")) {
        mdriverimage.setImageResource(R.drawable.ic_action_user);

    } else {
        Picasso.with(getApplicationContext()).load(driverimage).error(R.drawable.ic_action_user)
                .resize(200, 200).into(mdriverimage);
    }
}

From source file:esg.node.connection.ESGConnectionManager.java

private void periodicallyRegisterToPeers() {
    log.trace("Launching connection manager's registration push timer...");
    long delay = Long.parseLong(props.getProperty("conn.mgr.initialDelay", "10"));

    final long period = Long.parseLong(props.getProperty("conn.mgr.period", "30"));
    final long slop_bounds = 15000; //represents 15000ms or 15 seconds of slop.... slop/period is the ratio of period misses
    final Random random = new Random(System.currentTimeMillis());

    log.trace("connection registration delay:  " + delay + " sec");
    log.trace("connection registration period: " + period + " sec");

    Timer timer = new Timer("Reg-Repush-Timer");

    //This will transition from active map to inactive map
    timer.schedule(new TimerTask() {
        public final void run() {
            log.debug("(Timer) Re-Pushing My Last Registry State (Event)");
            long elapsedTime = (System.currentTimeMillis()
                    - ESGConnectionManager.this.lastDispatchTime.longValue());
            long window = ((period * 1000) + (Math.abs(random.nextLong()) % slop_bounds)); //milliseconds

            log.trace("Re-push: elapsedTime=" + elapsedTime + "ms >? window=" + window + "ms");

            if (elapsedTime > window) {
                ESGConnectionManager.this.getESGEventQueue().enqueueEvent(new ESGCallableFutureEvent<Boolean>(
                        ESGConnectionManager.this, Boolean.valueOf(false), "Registration Re-push Event") {
                    public boolean call(DataNodeComponent contextComponent) {
                        log.trace("Registration Re-push \"Call\"'ed...");
                        boolean handled = false;
                        try {
                            //Note: since "Boolean" generic, setData needs to take a value of that type
                            //"handled" plays *two* roles. 1) It is the Data that is being retrieved and stored
                            //by whatever process is coded (in this case calling sendOutRegistryState()).
                            //2) It is also setting the return value for this "call" method being implemented
                            //that indicates if this call was successfully handled.  The former has its type
                            //dictated by the generic.  The latter is always a boolean.
                            setData(handled = ((ESGConnectionManager) contextComponent).sendOutRegistryState());
                        } finally {
                            log.info("Registration Re-push completed [" + handled + "]");
                        }// w w  w  .java2  s  .c  o  m
                        return handled;
                    }
                });
            } else {
                log.debug("NOT performing re-push - last message sent approx " + (elapsedTime / 1000)
                        + "secs ago < " + (window / 1000) + "secs");
            }
        }
    }, delay * 1000, period * 1000);
}

From source file:com.predic8.membrane.core.Router.java

private void startAutoReinitializator() {
    if (getInactiveRules().isEmpty())
        return;//www.j  av a  2  s .  c  om

    reinitializator = new Timer("auto reinitializator", true);
    reinitializator.schedule(new TimerTask() {
        @Override
        public void run() {
            tryReinitialization();
        }
    }, retryInitInterval, retryInitInterval);
}

From source file:com.mibr.android.intelligentreminder.INeedToo.java

private void startMyTransmittingTimer() {
    getMyTransmittingTimer().schedule(new TimerTask() {
        public void run() {
            Intent intent = new Intent(INeedToo.this, INeedWebService.class).setAction("Outbound");
            startService(intent);/* www.ja  v a  2 s  .c  om*/
        }
    }, 1000 * 60 * 2, 1000 * 60 * 15);
}

From source file:com.zavakid.mushroom.impl.MetricsSystemImpl.java

private synchronized void startTimer() {
    if (timer != null) {
        LOG.warn(prefix + " metrics system timer already started!");
        return;/*from  ww  w.java2s .com*/
    }
    logicalTime = 0;
    long millis = period * 1000;
    timer = new Timer("Timer for '" + prefix + "' metrics system", true);
    timer.scheduleAtFixedRate(new TimerTask() {

        public void run() {
            try {
                onTimerEvent();
            } catch (Exception e) {
                LOG.warn(e);
            }
        }
    }, millis, millis);
    LOG.info("Scheduled snapshot period at " + period + " second(s).");
}

From source file:com.towson.wavyleaf.Sighting.java

protected void refresh() {
    // Check for GPS
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    playAPKEnabled = doesDeviceHaveGooglePlayServices();

    currentEditableLocation = locationData.getLocation();

    if (!isAccurateLocation(currentEditableLocation)) { // If location isn't accurate

        if (!gpsEnabled) { // If GPS is disabled
            buildAlertMessageNoGps();/*from   w w  w  .j  av a2 s . c  o  m*/
        } else if (gpsEnabled) {
            if (playAPKEnabled) {
                setUpMapIfNeeded();
                wheresWaldo();
            }
        }

        updateLocationTimer = new Timer();
        TimerTask updateLocationTask = new TimerTask() {
            @Override
            public void run() {
                checkLocation();
            }
        };
        updateLocationTimer.scheduleAtFixedRate(updateLocationTask, 0, FIVE_SECONDS);

    } else
        setUpMapIfNeeded();
}

From source file:emperior.Main.java

public static void removeTabbedPaneIcon() {
    final Timer timer = new Timer();
    TimerTask task = new TimerTask() {
        @Override/*w ww  .  ja v  a 2s.  c  o m*/
        public void run() {
            int index = MainFrame.jTabbedPane.getSelectedIndex();
            if (MainFrame.jTabbedPane.getIconAt(index) != null) {
                MainFrame.jTabbedPane.setIconAt(index, null);
                timer.cancel();
            }
        }
    };
    timer.schedule(task, 100, 60000);

}

From source file:com.norteksoft.cas.web.VerificationCodeValidator.java

private void timeoutTimer() {
    Timer timer = new Timer("login-info-timer", true);
    TimerTask task = new TimerTask() {
        public void run() {
            try {
                timeoutLoginInfo();/*from ww w .j ava 2s  .  c  o m*/
            } catch (Exception e) {
                log.debug("validate login info time out error. ", e);
            }
        }
    };
    timer.schedule(task, 30 * 1000l, 30 * 1000l);
}