Time since button released - android

I am trying to calculate the length of time that has elapsed since a button was released. I understand how to calculate this by waiting for the user to interact with the application again but i would like to be able to wait a fixed period - say 2 seconds - before a method is called or another event is triggered.
I am not sure how i can achieve this - is there a way of doing this without waiting for the user to press the button again?

Hey perfect_comment for this kind of timed task there is a few things you could do one of which is using ScheduledExecutorService this will allow you to set up a runnable to do some task at a fixed interval. In your onCreate method you would declare the shceduler like this
scheduler = Executors.newSingleThreadScheduledExecutor();
ScheduledFuture<?> future;
then tell your your scheduler to run some future task like this
`future = scheduler.scheduleWithFixedDelay(mRunnable, 1, DISCOVERY_INTERVAL, TimeUnit.SECONDS);
where runnable is a Runnable you have defined
mRunnable = new Runnable() {
#Override
public void run() { //printer has been found execute runnable
//your task code
}
};

Related

Call ExectuorService with time interval - android

i used a custom thread to fetch data in the background every 1 second by making a thread goes to sleep, but my App crashes and throws exception OutOfMemoryError. Now i read a documentation in android developer and i understand that using custom thread is bad practice as it is difficult to manage the memory consistency. but finally i found ExecutorService very interesting when we need to do some tasks on background So, i decided to use it.
As You know the ExecutorService is like below:
public void executeTask()
{
ExecutorService executroService = new Executor.newSingleThreadExecutor();
executroService.execute(new Runnable()
{
#Override
publi void run()
{
// now execute the server request
}
});
}
Now how can i achive calling to executorService every 1 second untill the user goes to onpause() state or untill the user shifts from the current activity to another activity? if i use a custom thread to call that service, the App goes to crash. so how can i achive that ?
What you need is a ScheduledExecutorService
It can schedule commands to run after a given delay,
or to execute periodically.
Here is a code that implements this
import static java.util.concurrent.TimeUnit.*;
class BeeperControl {
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public void beepForAnHour() {
Runnable beeper = () -> System.out.println("beep");
ScheduledFuture<?> beeperHandle =
scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
Runnable canceller = () -> beeperHandle.cancel(false);
scheduler.schedule(canceller, 1, HOURS);
}
}

Schedule code execution in the future

I wonder what the best way is to implement this behavior:
I have an event X with an id that happens from time to time.
If the event with a certain id happened, I want to execute some code after 25 seconds, except if X with the same id happens again, in that case I want it to be postponed again with 25 seconds.
What is the best way to implement this?
Here is how you can use a simple handler to delay running something for 25 seconds. It's up to you to figure out how to filter on some ID.
Handler handler = new Handler();
public void myEvent() {
// Remove any callback that may be registered, this will reset it if called before
handler.removeCallbacks(runMe);
// Execute the runnable in 25 seconds
handler.postDelayed(runMe, 25000);
}
Runnable runMe = new Runnable() {
#Override
public void run() {
// This will run after the postDelayed expires in 25 seconds
Log.d("TAG", "Run me at some time");
}
};

Automatically start execution upon activity launch

I'm working on an app that synchronizes some graphic UI events with an audio track. Right now you need to press a button to set everything in motion, after onCreate exits. I'm trying to add functionality to make the audio/graphical interaction start 10 seconds after everything is laid out.
My first thought is, at the end of onCreate, to make the UI thread sleep for 10000 miliseconds using the solution here and then to call button.onClick(). That seems like really bad practice to me, though, and nothing came of trying it anyway. Is there a good way to implement this autostart feature?
Never ever put sleep/delay on UI-thread. Instead, use Handler and its postDelayed method to get it done inside onCreate, onStart or onResume of your Activity. For example:
#Override
protected void onResume() {
super.onResume();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//do whatever you want here
}
}, 10000L); //the runnable is executed on UI-thread after 10 seconds of delay
}
Handler handler=new Handler();
Runnable notification = new Runnable()
{
#Override
public void run()
{
//post your code............
}
};
handler.postDelayed(notification,10000);
Yes, putting the UI thread to sleep isnt a good idea.
Try this
private final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
worker.schedule(task, 10, TimeUnit.SECONDS);

How to hide the layout when the screen remains untouched by the user?

I has use OnTouchListener to visible layout1 while screen was touch.
Now I want invisible layout1 while the screen didn't be touch three seconds.
But I don't know which event listener can I use?
Now the problem has be resolved.
But another one was appear.
I use:
class unTouchTask extends TimerTask {
public void run() {
if(untouch == true) {
RelativeLayout rl = (
RelativeLayout)findViewById(R.id.relativeLayout2);
rl.setVisibility(View.INVISIBLE);
timer.cancel();
untouch = false;}
}
}
Below error on linerl.setVisibility(View.INVISIBLE);:
android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
Option1 : You need to run a timer to track the user intraction inactive time, and on every user touch you will need to reset the timer.
Code your timer as below:
class UpdateTimeTask extends TimerTask {
public void run() {
//hide your layout
}
}
And in the event listener to start this update, the following Timer() instance is used:
if(startTime == 0L) {
startTime = evt.getWhen();
timer = new Timer();
timer.schedule(new UpdateTimeTask(), 300, 200);
}
NOTE :In particular, note the 300, 200 parameters. The first parameter means wait 300 ms before running the clock update task the first time. The second means repeat every 200ms after that, until stopped.
Option 2: Fortunately, the role of Timer can be replaced by the android.os.Handler class, with a few tweaks
You can get more detailed example at http://www.vogella.de/articles/AndroidPerformance/article.html
Regards.
You can use the Timer and TimerTask to schedule something to happen in a time interval.
If the user ever touches the screen, cancel the timer and reset it. You will need to UI related stuff in the UI thread. This article will give you an idea.
You are getting this Error because You can use threads but all the views, and all the views related APIs, must be invoked from the main thread (also called UI thread.) So the solution to this is to use the Handler. A Handler is an object that will post messages back to the UI thread for you. http://developer.android.com/reference/android/os/Handler.html will guide you to code handlers.
The second option is to use runOnUiThread. Following is what I do in my thread :
runOnUiThread(new Runnable() {
public void run() {
titleProgress.setVisibility(View.VISIBLE);
}
});
//long operation here
runOnUiThread(new Runnable() {
public void run() {
titleProgress.setVisibility(View.INVISIBLE);
}
});

Android - Controlling a task with Timer and TimerTask?

I am currently trying to set up a WiFi Scan in my Android application that scans for WiFi access points every 30 seconds.
I have used Timer and TimerTask to get the scan running correctly at the intervals which I require.
However I want to be able to stop and start the scanning when the user presses a button and I am currently having trouble stopping and then restarting the Timer and TimerTask.
Here is my code
TimerTask scanTask;
final Handler handler = new Handler();
Timer t = new Timer();
public void doWifiScan(){
scanTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
wifiManager.scan(context);
Log.d("TIMER", "Timer set off");
}
});
}};
t.schedule(scanTask, 300, 30000);
}
public void stopScan(){
if(scanTask!=null){
Log.d("TIMER", "timer canceled");
scanTask.cancel();
}
}
So the Timer and Task start fine and the scan happens every 30 seconds however I cant get it to stop, I can stop the Timer but the task still occurs and scanTask.cancel() doesn't seem to work either.
Is there a better way to do this? Or am I missing something in the Timer/TimerTask classes?
You might consider:
Examining the boolean result from calling cancel() on your task, as it should indicate if your request succeeds or fails
Try purge() or cancel() on the Timer instead of the TimerTask
If you do not necessarily need Timer and TimerTask, you can always use postDelayed() (available on Handler and on any View). This will schedule a Runnable to be executed on the UI thread after a delay. To have it recur, simply have it schedule itself again after doing your periodic bit of work. You can then monitor a boolean flag to indicate when this process should end. For example:
private Runnable onEverySecond=new Runnable() {
public void run() {
// do real work here
if (!isPaused) {
someLikelyWidget.postDelayed(onEverySecond, 1000);
}
}
};
using your code, instead of
scanTask.cancel();
the correct way is to cancel your timer (not timerTask):
t.cancel();
The Android documentation says that cancel() Cancels the Timer and all scheduled tasks. If there is a currently running task it is not affected. No more tasks may be scheduled on this Timer. Subsequent calls do nothing. Which explains the issue.

Categories

Resources