java.util.Timer Java Examples

The following examples show how to use java.util.Timer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ForgetPswActivity.java    From Gizwits-SmartSocket_Android with MIT License 6 votes vote down vote up
/**
 * 发送验证码
 * 
 * @param phone
 *            the phone
 */
private void sendVerifyCode(final String phone) {
	String CaptchaCode = etInputCaptchaCode_farget.getText().toString();
	dialog.show();
	btnReGetCode.setEnabled(false);
	btnReGetCode.setBackgroundResource(R.drawable.button_gray_short);
	secondleft = 60;
	timer = new Timer();
	timer.schedule(new TimerTask() {

		@Override
		public void run() {
			// 倒计时通知
			handler.sendEmptyMessage(handler_key.TICK_TIME.ordinal());
		}
	}, 1000, 1000);
	// 发送请求验证码指令
	// mCenter.cRequestSendVerifyCode(phone);
	// 发送请求验证码指令
	Log.i("AppTest", tokenString + ", " + captchaidString + ", " + CaptchaCode + ", " + phone);
	mCenter.cRequestSendVerifyCode(tokenString, captchaidString, CaptchaCode, phone);
}
 
Example #2
Source File: DelayOverflow.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
void scheduleNow(Timer timer, TimerTask task, int how) {
    switch (how) {
        case 0 :
            timer.schedule(task, new Date(), Long.MAX_VALUE);
            break;
        case 1:
            timer.schedule(task, 0L, Long.MAX_VALUE);
            break;
        case 2:
            timer.scheduleAtFixedRate(task, new Date(), Long.MAX_VALUE);
            break;
        case 3:
            timer.scheduleAtFixedRate(task, 0L, Long.MAX_VALUE);
            break;
        default:
            fail(String.valueOf(how));
    }
}
 
Example #3
Source File: Metrics.java    From SubServers-2 with Apache License 2.0 6 votes vote down vote up
private void startSubmitting() {
    // We use a timer cause want to be independent from the server tps
    final Timer timer = new Timer(true);
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            // Plugin was disabled, e.g. because of a reload (is this even possible in Sponge?)
            if (!Sponge.getPluginManager().isLoaded(plugin.plugin.getId())) {
                timer.cancel();
                return;
            }
            // The data collection (e.g. for custom graphs) is done sync
            // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
            Scheduler scheduler = Sponge.getScheduler();
            Task.Builder taskBuilder = scheduler.createTaskBuilder();
            taskBuilder.execute(() -> submitData()).submit(plugin);
        }
    }, 1000*60*5, 1000*60*30);
    // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
    // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted!
    // WARNING: Just don't do it!
}
 
Example #4
Source File: DasServlet.java    From XPagesExtensionLibrary with Apache License 2.0 6 votes vote down vote up
public void doInit() throws ServletException {
    synchronized(s_initialized) {
        if ( !s_initialized ) {
            super.doInit();
            
            // Initialize the core service
            initCoreService();
            
            // Initialize the data service
            initDataService();
            
            // Initialize resources from other plugins
            initDynamicResources();
            
            // Schedule the timer task to run every 30 seconds
            IStatisticsProvider provider = ProviderFactory.getStatisticsProvider();
            if ( provider != null ) {
                s_statsTimer = new Timer(true);
                s_statsTimer.schedule(s_statsTimerTask, STATS_TIMER_INTERVAL, STATS_TIMER_INTERVAL);
            }
            
            s_initialized = true;
            DAS_LOGGER.getLogger().fine("DasServlet initialized."); // $NON-NLS-1$
        }
    }
}
 
Example #5
Source File: JobTestHelper.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
public static void executeJobExecutorForTime(ProcessEngineConfiguration processEngineConfiguration, long maxMillisToWait, long intervalMillis) {
  AsyncExecutor asyncExecutor = processEngineConfiguration.getAsyncExecutor();
  asyncExecutor.start();

  try {
    Timer timer = new Timer();
    InteruptTask task = new InteruptTask(Thread.currentThread());
    timer.schedule(task, maxMillisToWait);
    try {
      while (!task.isTimeLimitExceeded()) {
        Thread.sleep(intervalMillis);
      }
    } catch (InterruptedException e) {
      // ignore
    } finally {
      timer.cancel();
    }

  } finally {
    asyncExecutor.shutdown();
  }
}
 
Example #6
Source File: CrashXCheckJni.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String []s)
{
    final Dialog fd = new Dialog(new Frame(), true);
    Timer t = new Timer();
    t.schedule(new TimerTask() {

        public void run() {
            System.out.println("RUNNING TASK");
            fd.setVisible(false);
            fd.dispose();
            System.out.println("FINISHING TASK");
        }
    }, 3000L);

    fd.setVisible(true);
    t.cancel();
    Util.waitForIdle(null);

    AbstractTest.pass();
}
 
Example #7
Source File: AsyncServlet.java    From training with MIT License 6 votes vote down vote up
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

	final AsyncContext asyncContext = req.startAsync();

	// DON'T TRY THIS AT HOME: Working with threads in a Container !!
	new Timer().schedule(new TimerTask() {
		@Override
		public void run() {
			try {
				asyncContext.getResponse().getWriter().println(new Date() + ": Asynchronous Response");
				System.out.println("Release pending HTTP connection");
				asyncContext.complete();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}, 10 * 1000);
	resp.getWriter().println(new Date() + ": Async Servlet returns leaving the connection open");
}
 
Example #8
Source File: HomeFragment.java    From FireFiles with Apache License 2.0 6 votes vote down vote up
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    storageTimer = new Timer();
    secondatyStorageTimer = new Timer();
    usbStorageTimer = new Timer();
    processTimer = new Timer();
    storageStats = (HomeItem) view.findViewById(R.id.storage_stats);
    secondayStorageStats = (HomeItem) view.findViewById(R.id.seconday_storage_stats);
    usbStorageStats = (HomeItem) view.findViewById(R.id.usb_storage_stats);
    memoryStats = (HomeItem) view.findViewById(R.id.memory_stats);
    recents = (TextView)view.findViewById(R.id.recents);
    recents_container = view.findViewById(R.id.recents_container);

    mShortcutsRecycler = (RecyclerView) view.findViewById(R.id.shortcuts_recycler);
    mRecentsRecycler = (RecyclerView) view.findViewById(R.id.recents_recycler);

    roots = DocumentsApplication.getRootsCache(getActivity());
    mHomeRoot = roots.getHomeRoot();
    showRecents();
    showData();
}
 
Example #9
Source File: CrashXCheckJni.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String []s)
{
    final Dialog fd = new Dialog(new Frame(), true);
    Timer t = new Timer();
    t.schedule(new TimerTask() {

        public void run() {
            System.out.println("RUNNING TASK");
            fd.setVisible(false);
            fd.dispose();
            System.out.println("FINISHING TASK");
        }
    }, 3000L);

    fd.setVisible(true);
    t.cancel();
    Util.waitForIdle(null);

    AbstractTest.pass();
}
 
Example #10
Source File: MEMTest.java    From GTTools with MIT License 6 votes vote down vote up
@Test
public void testMem() throws InterruptedException
{
	Timer timer = new Timer();
	
	MEMTimerTask task = new MEMTimerTask(
		new DataRefreshListener<Long[]>(){

			@Override
			public void onRefresh(long time, Long[] data) {
				System.out.println(data[0] + "/" + data[1] + "/" + data[2]+ "/" + data[3]);
			}});

	timer.schedule(task, 0, 1000);
	Thread.sleep(10000);
}
 
Example #11
Source File: NaviSetLinePresenter.java    From AssistantBySDK with Apache License 2.0 6 votes vote down vote up
@Override
public void startCountDown() {
    countDownTimer = new Timer();
    countDownTimer.schedule(new TimerTask() {
        private int i = 0;

        @Override
        public void run() {
            if (++i > 10) {
                stopCountDown();
                mHandler.sendEmptyMessage(NaviSetLineActivity.MSG_START_NAV);
            } else {
                Message msg = new Message();
                msg.what = NaviSetLineActivity.MSG_UPDATE_COUNTDOWN;
                msg.arg1 = 10 - i;
                mHandler.sendMessage(msg);
            }
        }
    }, 1000, 1000);
}
 
Example #12
Source File: BlePeripheral.java    From Bluefruit_LE_Connect_Android_V2 with MIT License 6 votes vote down vote up
CaptureReadHandler(String identifier, CaptureReadCompletionHandler result, int timeout, @Nullable CaptureReadCompletionHandler.TimeoutAction timeoutAction, boolean isNotifyOmitted) {
    mIdentifier = identifier;
    mResult = result;
    mIsNotifyOmitted = isNotifyOmitted;

    // Setup timeout if not zero
    if (timeout > 0 && timeoutAction != null) {
        mTimeoutAction = timeoutAction;

        mTimeoutTimer = new Timer();
        if (kProfileTimeouts) {
            mTimeoutStartingMillis = System.currentTimeMillis();
            Log.d(TAG, "Start timeout:  " + identifier + ". millis:" + mTimeoutStartingMillis);
        }
        mTimeoutTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (kProfileTimeouts) {
                    Log.d(TAG, "Fire timeout:   " + identifier + ". elapsed millis:" + (System.currentTimeMillis() - mTimeoutStartingMillis));
                }
                mResult.read(kPeripheralReadTimeoutError, null);
                mTimeoutAction.execute(identifier);
            }
        }, timeout);
    }
}
 
Example #13
Source File: CrashXCheckJni.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String []s)
{
    final Dialog fd = new Dialog(new Frame(), true);
    Timer t = new Timer();
    t.schedule(new TimerTask() {

        public void run() {
            System.out.println("RUNNING TASK");
            fd.setVisible(false);
            fd.dispose();
            System.out.println("FINISHING TASK");
        }
    }, 3000L);

    fd.setVisible(true);
    t.cancel();
    Util.waitForIdle(null);

    AbstractTest.pass();
}
 
Example #14
Source File: CrashXCheckJni.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String []s)
{
    final Dialog fd = new Dialog(new Frame(), true);
    Timer t = new Timer();
    t.schedule(new TimerTask() {

        public void run() {
            System.out.println("RUNNING TASK");
            fd.setVisible(false);
            fd.dispose();
            System.out.println("FINISHING TASK");
        }
    }, 3000L);

    fd.setVisible(true);
    t.cancel();
    Util.waitForIdle(null);

    AbstractTest.pass();
}
 
Example #15
Source File: BaseController.java    From MyBox with Apache License 2.0 6 votes vote down vote up
public void toFront() {
    try {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Platform.runLater(() -> {
                    getMyStage().toFront();
                    if (topCheck != null) {
                        topCheck.setSelected(AppVariables.getUserConfigBoolean(baseName + "Top", true));
                        if (topCheck.isVisible()) {
                            getMyStage().setAlwaysOnTop(topCheck.isSelected());
                        }
                    }
                    timer = null;
                });
            }
        }, 1000);
    } catch (Exception e) {
        logger.error(e.toString());
    }
}
 
Example #16
Source File: CrashXCheckJni.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String []s)
{
    final Dialog fd = new Dialog(new Frame(), true);
    Timer t = new Timer();
    t.schedule(new TimerTask() {

        public void run() {
            System.out.println("RUNNING TASK");
            fd.setVisible(false);
            fd.dispose();
            System.out.println("FINISHING TASK");
        }
    }, 3000L);

    fd.setVisible(true);
    t.cancel();
    Util.waitForIdle(null);

    AbstractTest.pass();
}
 
Example #17
Source File: DelayOverflow.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
void scheduleNow(Timer timer, TimerTask task, int how) {
    switch (how) {
        case 0 :
            timer.schedule(task, new Date(), Long.MAX_VALUE);
            break;
        case 1:
            timer.schedule(task, 0L, Long.MAX_VALUE);
            break;
        case 2:
            timer.scheduleAtFixedRate(task, new Date(), Long.MAX_VALUE);
            break;
        case 3:
            timer.scheduleAtFixedRate(task, 0L, Long.MAX_VALUE);
            break;
        default:
            fail(String.valueOf(how));
    }
}
 
Example #18
Source File: DelayOverflow.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
void test(String[] args) throws Throwable {
    for (int how=0; how<4; how++) {
        final CountDownLatch done = new CountDownLatch(1);
        final AtomicInteger count = new AtomicInteger(0);
        final Timer timer = new Timer();
        final TimerTask task = new TimerTask() {
            @Override
            public void run() {
                checkScheduledExecutionTime(this);
                count.incrementAndGet();
                done.countDown();
            }};

        scheduleNow(timer, task, how);
        done.await();
        equal(count.get(), 1);
        checkScheduledExecutionTime(task);
        if (new java.util.Random().nextBoolean())
            sleep(10);
        check(task.cancel());
        timer.cancel();
        checkScheduledExecutionTime(task);
    }
}
 
Example #19
Source File: PeerConnectionClient.java    From janus-gateway-android with MIT License 6 votes vote down vote up
public void createPeerConnectionFactory(final Context context,
    final PeerConnectionParameters peerConnectionParameters, final PeerConnectionEvents events) {
  this.peerConnectionParameters = peerConnectionParameters;
  this.events = events;
  // Reset variables to initial states.
  this.context = null;
  factory = null;
  videoCapturerStopped = false;
  isError = false;
  mediaStream = null;
  videoCapturer = null;
  renderVideo = true;
  localVideoTrack = null;
  remoteVideoTrack = null;
  localVideoSender = null;
  enableAudio = true;
  localAudioTrack = null;
  statsTimer = new Timer();

  executor.execute(new Runnable() {
    @Override
    public void run() {
      createPeerConnectionFactoryInternal(context);
    }
  });
}
 
Example #20
Source File: DataSimFragment.java    From AndroidSDK with MIT License 6 votes vote down vote up
private void sendContinuous(final String deviceId, final String datastream, final float minValue, final float maxValue, int period) {
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    sendOnce(deviceId, datastream, minValue, maxValue);
                }
            });
        }
    };
    mSendDataTimer = new Timer(true);
    mSendDataTimer.schedule(task, 0, period * 1000);
    mSendContinuousButton.setText(R.string.stop_sending);
    mDeviceIdLayout.setEnabled(false);
    mDataStreamLayout.setEnabled(false);
    mMinValueLayout.setEnabled(false);
    mMaxValueLayout.setEnabled(false);
    mPeriodLayout.setEnabled(false);
    mSendOneceButton.setEnabled(false);
    mSending = true;
}
 
Example #21
Source File: BucketQueueManager.java    From sdmq with Apache License 2.0 6 votes vote down vote up
@Override
public void start() {
    int bucketSize = checkBucketNum(properties.getBucketSize());
    if (isRuning.compareAndSet(false, true)) {
        for (int i = 1; i <= bucketSize; i++) {
            String     bName = NamedUtil.buildBucketName(properties.getPrefix(), properties.getName(), i);
            BucketTask task  = new BucketTask(bName);
            task.setJobOperationService(jobOperationService);
            task.setPoolName(NamedUtil.buildPoolName(properties.getPrefix(), properties.getName(), properties
                    .getOriginPool()));
            task.setReadyName(NamedUtil.buildPoolName(properties.getPrefix(), properties.getName(), properties
                    .getReadyName()));
            task.setProperties(properties);
            task.setLock(lock);
            String threadName = String.format(THREAD_NAME, i);
            Timer  timer      = new Timer(threadName, daemon);
            timer.schedule(task, 500, properties.getBuckRoundRobinTime());
            HOLD_TIMES.put(threadName, timer);
            LOGGER.info(String.format("Starting Bucket Thead %s ....", threadName));
        }

    }
}
 
Example #22
Source File: PeerConnectionClient.java    From sample-videoRTC with Apache License 2.0 5 votes vote down vote up
public void createPeerConnectionFactory(final Context context,
    final PeerConnectionParameters peerConnectionParameters, final PeerConnectionEvents events) {
  this.peerConnectionParameters = peerConnectionParameters;
  this.events = events;
  videoCallEnabled = peerConnectionParameters.videoCallEnabled;
  dataChannelEnabled = peerConnectionParameters.dataChannelParameters != null;
  // Reset variables to initial states.
  factory = null;
  peerConnection = null;
  preferIsac = false;
  videoCapturerStopped = false;
  isError = false;
  queuedRemoteCandidates = null;
  localSdp = null; // either offer or answer SDP
  mediaStream = null;
  videoCapturer = null;
  renderVideo = true;
  localVideoTrack = null;
  remoteVideoTrack = null;
  localVideoSender = null;
  enableAudio = true;
  localAudioTrack = null;
  statsTimer = new Timer();

  executor.execute(new Runnable() {
    @Override
    public void run() {
      createPeerConnectionFactoryInternal(context);
    }
  });
}
 
Example #23
Source File: XPlottingViewer.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void actionPerformed(ActionEvent evt) {
    plotterCache.remove(key);
    Timer t = timerCache.remove(key);
    t.cancel();
    ((XMBeanAttributes) table).collapse(attributeName, this);
}
 
Example #24
Source File: DesktopSearchController.java    From FXDesktopSearch with Apache License 2.0 5 votes vote down vote up
public void configure(final DesktopSearchMain aApplication, final Backend aBackend, final String aSearchURL, final Window aWindow) {
    gateway = new DesktopGateway(aApplication, DesktopSearchController.this);
    window = aWindow;
    application = aApplication;
    backend = aBackend;
    backend.setProgressListener(new FXProgressListener());
    watcherThread = new ProgressWatcherThread();
    webView.getEngine().setJavaScriptEnabled(true);
    webView.getEngine().getLoadWorker().stateProperty().addListener((ov, t, t1) -> {
        if (t1 == State.SUCCEEDED) {
            final var windowGlobalJSNamespace = (JSObject) webView.getEngine().executeScript("window");
            windowGlobalJSNamespace.setMember("desktop", gateway);
        }
    });
    webView.setContextMenuEnabled(false);
    webView.getEngine().load(aSearchURL);
    webView.getEngine().setJavaScriptEnabled(true);

    if (aApplication.getConfigurationManager().getConfiguration().isCrawlOnStartup()) {
        // Scedule a crawl run 5 seconds after startup...
        final var theTimer = new Timer();
        theTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                Platform.runLater(() -> recrawl());
            }
        }, 5000);
    }
}
 
Example #25
Source File: LongTouchHandler.java    From ProgressView with Apache License 2.0 5 votes vote down vote up
@Override
public boolean onTouch(View v, MotionEvent event) {
    if (v.isClickable()) {
        /* handle press states */
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            v.setPressed(true);
            timer = new Timer();
            // Initial delay = length of a long press
            timer.schedule(new IncrementTask(0, ViewConfiguration.getLongPressTimeout()), ViewConfiguration.getLongPressTimeout());
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
            timer.cancel();
            v.setPressed(false);
        }

        long lengthOfPress = event.getEventTime() - event.getDownTime();
        // If the button has been "tapped" then handle normally
        if (lengthOfPress < ViewConfiguration.getLongPressTimeout()
            && event.getAction() == MotionEvent.ACTION_UP) {
                incrementListener.increment();
        }

        return true;
    } else {
        /* If the view isn't clickable, let the touch be handled by others. */
        return false;
    }
}
 
Example #26
Source File: HomeFragment.java    From FireFiles with Apache License 2.0 5 votes vote down vote up
private void animateProgress(final HomeItem item, final Timer timer, RootInfo root){
    try {
        final double percent = (((root.totalBytes - root.availableBytes) / (double) root.totalBytes) * 100);
        item.setProgress(0);
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if(Utils.isActivityAlive(getActivity())){
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (item.getProgress() >= (int) percent) {
                                timer.cancel();
                            } else {
                                item.setProgress(item.getProgress() + 1);
                            }
                        }
                    });
                }
            }
        }, 50, 20);
    }
    catch (Exception e){
        item.setVisibility(View.GONE);
        Crashlytics.logException(e);
    }
}
 
Example #27
Source File: LogTopComponent.java    From NBANDROID-V2 with Apache License 2.0 5 votes vote down vote up
private void startReading() {
    if (starting) {
        return;
    }
    starting = true;
    if (reader == null || !reader.isReading()) {

        if (reader == null) {
            reader = new LogReader();
            for (LogTableManager manager : tabManagers) {
                reader.addLogListener(manager);
            }

            reader.addPropertyChangeListener(WeakListeners.propertyChange(myPropertyChangeListener, reader));

            cmbLogDevicesSupport = new LogDevicesComboBoxSupport(reader);
            cmbLogDevicesSupport.attach(cmbLogDevices);
        }

        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                reader.startReading();
                starting = false;
            }
        }, 1000);
    } else {
        starting = false;
    }
}
 
Example #28
Source File: SplashActivity.java    From Ecommerce-Retronight-Android with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
	// TODO Auto-generated method stub
	super.onCreate(savedInstanceState);
	requestWindowFeature(Window.FEATURE_NO_TITLE); 
	this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
	setContentView(R.layout.activity_splash);
	
	Timer timer = new Timer();
	timer.schedule(new TimerTask() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			
			Intent intent = new Intent(SplashActivity.this, MainActivity.class);
			startActivity(intent);
			finish();
			
		}
	}, MainActivity.SPLASH_DURATION);

	tvZonCon = (TextView)findViewById(R.id.tv_zoncon);
	tvZonCon.setShadowLayer(2, 1, 1, getResources().getColor(R.color.black));
	tvZonCon.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
	tvZonCon.setVisibility(RelativeLayout.GONE);
	
}
 
Example #29
Source File: GPSCollector.java    From sensordatacollector with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onRegistered()
{
    if(mGoogleApiClient != null) {
        mGoogleApiClient.connect();
    } else {
        searchLocationWithoutGoogleService();
    }

    this.timer = new Timer();
    this.timer.scheduleAtFixedRate(new TimerTask()
    {
        @Override
        public void run()
        {
            Log.d("GPSCollector", "New Data Available?");

            Location location = null;
            if(mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
                if(!(Build.VERSION.SDK_INT >= 23 &&
                        !(ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                        ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED))) {

                    location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                }
            }

            if(location == null || (lastKnownLocation != null && location.getTime() <= lastKnownLocation.getTime())) {
                location = getBestLocation();
            }

            if(location != null && (lastKnownLocation == null || location.getTime() > lastKnownLocation.getTime())) {
                lastKnownLocation = location;
                doLocationUpdate(lastKnownLocation);
            }
        }
    }, 0, getSensorRate());
}
 
Example #30
Source File: RepeatFiringBehavior.java    From nebula with Eclipse Public License 2.0 5 votes vote down vote up
public void pressed() {
	runTask.run();
	
	timer = new Timer();
	TimerTask runAction = new Task();

	timer.scheduleAtFixedRate(runAction, INITIAL_DELAY, STEP_DELAY);
}