Trying to figure out how to do this, basically my App requires a button to be hit and hit multiple times, it counts how many times you hit it and if you don't hit one within a certain space of time it will display a message.
I just can't figure out how to get the 'If button isn't pressed within 'x' seconds then...' part, I've tried if(imagebutton1.isPressed()) statement but it checks it instantly when the actvity starts, I just want it to check 'X' amount of seconds after the button was last pressed.
ANy help is appreciated thanks.
In your case you would need to record the last time the button was pressed
Then add a updated while statement
In c++
Int presses;
Int timelimit; //the seconds between each press (you can use a chronometer but this is simpler but less accurate (and no decimals)
Int lastpressed; //need chronometer for more accuracy or decimals)
Int ammountpassed; //time since you pressed it
If(imagebutton1.isPressed())
{
Bool Started = Yes;
Presses++;
While(!imagebutton1.isPressed()&&ammountpassed<TimeLimit)
{
Ammountpassed++;
};
};
If (ammountpassed>=timelimit)
{
If (presses>=highscore)
{
DisplayMsg " Number of presses" presses; "! New highscore!";
};
Else(presses<highscore)
{
DisplayMsg "not fast enough! Number of presses" presses; "!" };
};
};
You will have to tweak it a bit to fit your needs ("displaymsg" I for think is the actual function so you might have to change that but there's the logic :)
I recommend hand typing this as I belive I may have made a few error but nothing adding a semi colon or 2 won't fix ;)
Hope it helps :) Good Luck :)
Every time the user hits the button you can post a message on the handler's queue with your text message to be displayed and the appropriate delay time (and remove previous messages). Therefore if the delayed time exceeds without any press the thread will execute the handler's message. Lets say you want to post to the main handler a message to be executed in delay number of milliseconds, then in your activity you would need to hold the reference to the handler and create a Runnable where the necessary text message will be displayed:
Handler mainHandler = new Handler(getMainLooper());
Runnable runnable = new Runnable(...);
In your OnClickListener of the button you would need to execute only:
#Override
public void onClick(View v) {
mainHandler.removeCallbacksAndMessages(null);
mainHandler.postDelayed(runnable, delay);
}
Related
For now my app have a chat that comunicate via bluetooth with an OBD port in the car.
Now i want upgrade my project for real time information, so i want create a method that repeat some Array with a list of commands and repeat the sendMessage(message) every sec or 500 millisec (something for real time data).
There is some bestway to do that?
I have my Activity with 4 EditText for showing data and a Button with "start scan" and if pressed it becomes a "stop scan" and interrupt the infinite loop of commands.
In the same time i need to take back data and show results in the EditText.
EDIT
Or just use an AlarmManager?
EDIT 2
With this code not work properly because send only the first message after 5 sec and the second it lost...
How can i send all the commands into ArrayList one at a time every t millisec?
public void repeatCommand(){
for (final String command : commandArray){
final Handler handlerTimed = new Handler();
handlerTimed.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 100ms
sendMessage(command);
}
}, 5000);
}
/*String message = "010C\r";
sendMessage(message);*/
}
Sorry I didn't write android code for so long but I had your case so long ago.
You have to define a Service and start it in foreground with RETURN_STICKY and then write a handler with timer which execute your code per second (or what you like!). Then you can broadcast your result or how you want to communicate with your activity and use it.
Then start service and stop it with your button.
PS:
1. As far as I know alarmManager is not a good idea in this case.
Somehow you have to be sure that your Service will not be killed by android.
Recently, I have developed an app on travelling domain. The aim of this app is to show the user; the path from source to destination. When the user comes in the range of 25 meters range of the destination, the user gets a notification/ an alert stating that the destination is nearby.
What I tried to achieve it:
In the onLocationChanged() I kept on for the destination's range & if the user is in the range, the notification/alert will pop-out. However, when the I tested the app, I found out that when I am in the range, the notifications flood the device horribly as the condition of showing the notification/alert is based on the onLocationChanged() ie as location changes, the loop executes the exact same number of times and the user get annoyed by the app.
Also, the app does not work when I search for a different location. It does not show the destination marker. For the first time, the destination marker is seen but later searches do not show the destination marker; I wonder why?!
This problem has bugged me since long time. Please help me on this one!!
you can keep a check on the number of time the notification is displayed, for example in loop
boolean notification_shown = false;
for(...)
{
if(!notification_shown)
{
//show notification
notification_shown = true;
}
else
{
//rest of your coding
}
}
this will show the notification only one time. If you want to display notification for few more times than you can use counter. like
int counter = 0;
//increment it till you want and than stop
Two possible solutions that are probably best combined: one, use a static dialog so that you only have one instance of the alert; two, unregister the onLocationChanged() listener as soon as you reach the destination (the first time it alerts the user).
When you are using loop in the onLocationChange() method, in side your loop take a variable say "count" and then check the condition for the distance. After the particular condition got true then increment the count. If counter get 1 then pop an alert and after that exit from the loop.
int count=0;
public void onLocationChanged(Location locFromGps) {
if(locFromGps<=30)
{
if(count==1)
{
exit(0);
}
count++;
Toast.makeText(getApplicationContext(),"Location is near", 0).show();
}
}
I have multiple Views that are clickable. I want to collect all the clicks in series if they're within 0.5 seconds of the previous click, then batch process the clicks only after 0.5 second of the very last click.
e.g.
Delay: 0.2 0.4 0.6
Click on A ---> B ---> C ---> D
Processing should be "ABC" (let's say passing them to the processing method as String "ABC" will do), then another process for "D". I'm having problem coming up with the "wait-and-see" part. What is a good approach to do this?
Thanks in advance.
Mike
Ended up doing it via Handler which is quite simple for this case. For those who are interested, I defined a handler in the activity that handles a designated message which is to process something immediately. Then on every click, I clear the message queue and then send a message with that 0.5sec delay.
Handler myHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 3001:
process();
break;
}
}
};
and whenever there's a View that I'm interested in, I add the following lines in its onClickListener()
myHandler.removeMessages(3001);
myHandler.sendEmptyMessageDelayed(3001, 500);
There may be a case of over-removing msg3001 but that's ok as it's being handled by the system gracefully.
I want to programm a game for Android.
Play principle: The user should have a short time to choose the correct answer.
My problem is the combination between the input (choosing the answer) and the time (countdown). I tried to run a thread, but the thread isn't stoppable. So the user gives the answer, the next activity will be shown and after a while (when the "timer" becomes 0) the activity will be shown again.
How could I implement this in a correct way?
Should I use Thread, Handler, CountDownTimer ?
You can keep a running timer using this on init:
Timer updateTimer = new Timer("update");
updateTimer.scheduleAtFixedRate(new TimerTask() {
public void run() {
updateGUI();
}
}, 0, 1000);
long startTime = System.currentTimeMillis();
Then in a Thread:
//Clock update
currentTime = System.currentTimeMillis() - startTime;
SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
clock.setText(sdf.format(currentTime));
clock.invalidate();
You could stop the Thread with a boolean inside or outside as you please?
Okay, I don't know the specific libraries to use, and I haven't done any thread programming myself, but I would think of the program as a state machine. I hope it helps :/
Set up a boolean userHasAnswered = false.
Set up a specialized listener (e.g. touch listener for some button) for answers.
If the listener gets an appropriate response from the user, set userHasAnswered = true.
When question loads up, start the thread which counts down.
If user fails to give ans when the time reaches zero, just call loadNextQuestion().
In your thread, do periodic checks every few units of time to see if userHasAnswered == true, and if it is true, then call updateScore() and loadNextQuestion().
You may want to have a look at alarm manager
I am developing an App where I show the countdown timer. To countdown the time I am using Handler class. Once the countdown timer reaches certain time the Alarm goes off. My problem is as below,
Initially I show the timer time as 04:00:00. Once it reaches 00:00:00 then the Alarm goes off. The Alarm code is working fine. But the timer display is not reliable. It works fine until I keep the App open. If I close the App (using Home or Back) or lock the device and open App again then the timer shown is not the correct one (delaying a lot, but still alarm works on-time). (But it works sometimes very fine under the same scenario). But whenever I ping the device to the system for checking the Log in eclipse that time all works fine!!!!!!!
1. I want to know whether I am using the Handler properly or not
2. (or) Is going out of the App or locking the device causing the problem
Below is my Handler code,
Handler digiHandler;
// Method to initialize the time and define the Handler
public void initialize(int hourstime,int mintime,int sectime){
hour = hourstime;
min = mintime;
sec = sectime;
digiHandler = new Handler();
handleRunnable = new Runnable(){
public void run(){
updateTimes();
}
};
}
public void startUpdateTheread(){
digiHandler.postDelayed(handleRunnable, UPDATEDELAY);
}
// Method to update the timer times
private void updateTimes(){
timerText = String.format(timerFormat,hour,min,sec );
-------------------------
-------------------------
-- code for incrementing the time ---
--------------------------
--------------------------
--------------------------
startUpdateTheread();
}
Please give the suggestions
Thanks
Edit:
When I observed the log it shows that to countdown 1 second of timer sometimes it is taking 1 minute time. The log is as below,
09-21 21:09:18.965: DEBUG/DigitalTimer(7656): timerText**:04:22:54
****long difference here****
09-21 21:10:19.308: DEBUG/DigitalTimer(7656): timerText**:04:22:53
..................................................................................
..................................................................................
..................................................................................
09-21 21:10:23.314: DEBUG/DigitalTimer(7656): timerText**: 04:22:49
**--long difference here ---**
09-21 21:11:22.604: DEBUG/DigitalTimer(7656): timerText**:04:22:48
It is happening always. So I can rule out that locking/coming out of an App is causing the problem. Seems I need to tweak the Handler part of the code.
The problem is that if the activity dies, then so does the thread it spawned, I recommend creating a service to handle this since such timers can be long i imagine (over 4 minutes) and in that time, you need the application to not die.
take a look at http://developer.android.com/reference/android/app/Service.html and let me know if that seems like a good enough solution.