I need to create an alarm every time new data is inserted on the Database(the database has the values of date and time of every alarm that is going to be created), without any interaction with the user, the app has to do it automatically.
How do I know when new data is inserted? checking every x minutes using a timer?
How to create an alarm automatically when that happens?
Typically for something like this, you would want to use something more like Firebase that will live update your data.
But to do a timer, first extend TimerTask:
public class Progress extends TimerTask {
#Override
public void run(){
//this item runs on a separate thread
runOnUiThread(new Runnable() {
#Override
public void run() {
seconds += 0.1;
//this item runs on the main thread
}
});
}
}
And then to run this task:
Timer timer;
Progress progress;
timer.schedule(progress, 100, 100);
This will run the timer every .1 seconds.
I am trying to write an app that shows the user a string on textview, and replace the text due to user input. This should happen on time intervals of 60 seconds.
I tried to use a countdown timer, which sets a boolean var to false on it's onFinish method. While this boolean is true, I am trying to change the strings in the textview (further work will be to change the text due to the user actions, but I'm still trying to get this work for simple actions).
For now, the app seems to be stucked and nothing happens, but if I am removing the while loop, there is a single text on the screen (as it should be).
Is there a problem using a while loop for that purpose? Is there a different way to work along with the timer?
(p.s I know there are some problems in the code, but this is just for isolating the problem. Thanks!)
EDIT:
I will try to clarify my intentions:
I want to give the user tasks, which he should perform in a given time. I want to display the time remaining on the screen, along with the task to perform. When the user finishes the task, if there is still time on the clock, he will press a button and another task will appear. The goal is to finish as many tasks as possible in the given time.
My code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start_game);
Bundle b = getIntent().getExtras();
game = b.getParcelable("game_record");
figuresList = new ArrayList<String>(game.getFiguresList());
clockView = (TextView) findViewById(R.id.clockView);
figureText = (TextView) findViewById(R.id.figureText);
timer = new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
clockView.setText(Long.toString(millisUntilFinished / 1000));
}
public void onFinish() {
clockView.setText("done!");
isTurn = false;
}
};
playRound();
}
private void playRound() {
figuresIterator = figuresListUsage.iterator();
isTurn = true;
String nextFigure = figuresIterator.next();
timer.start();
while (isTurn == true) {
figureText.setText(nextFigure);
nextFigure = figuresIterator.next();
}
}
It's a little difficult to understand your games logic but the main problem i see with your code is that you are entering the loop in a lifecycle event handler. Take a look at this lifecycle description. You are stopping it in onCreate and there is still work to be done before the activity will finish its lifecycle handling.
I suggest you try making play round event bound or use a diffrent thread for it. there are alot of threading APIs for android and as i dont know the nature of your game rounds i cant recommend any.
In my UI I have a button and a label.
On the button click I want to start a new thread which would update the label text to display the timer information (like 00:00 seconds).
This should be updated every second.
Could someone give a simple solution to this problem please?
Assuming that the information is in the form of a textView (called tv), you would use a countdowntimer:
new CountDownTimer(30000, 1) {
public void onTick(long millisUntilFinished) {
mTextField.setText(/* Whatever you want for each millisecond */);
}
public void onFinish() {
mTextField.setText("00:00");
}
}.start();
the second parameter in the CountDownTimer constructor is the intervals for which onTick, so for this timer, onTick will be called every millisecond.
Any questions?
I have a button on which I want to set the timer for 5 seconds for the first time and it should perform some task after completing 5 seconds. Also if user click button 2 times it should start timer for 10 seconds and after 10 seconds it should perform specific task. and if user click 3rd time it should stop all running timers. so I have do not know How to implement timer for one time
what I have search is this. But in this link it is continuously repeating after specific period of time, whereas I want to run once.
Now what I want
To start timer with first click (of 5 seconds)and if meanwhile user click 2nd time it should set timer with with new time period and if user click third time it cancels out all timers.
I do not want to use Thread timer using sleep method.
I want same behavior as there is in camera app in android 5.0 v.
So please tell me how to do this any code and source code would be appreciated.
In the link you provided you will find the answer if you try little harder.
For a repeating task:
new Timer().scheduleAtFixedRate(task, after, interval);
For a single run of a task:
new Timer().schedule(task, after);
So what you need to do is to maintain temporary variable to keep track of number of clicks and you can use second method like
For a repeating task:
new Timer().scheduleAtFixedRate(task, after, interval);
For a single run of a task:
new Timer().schedule(task, after * numberOfTimeBtnClked);
You have to pass the TimerTask method instead of task in that method.
**For updating your textview use below code and forget about whatever I have written above **
public void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
//run in an interval of 1000ms
timer.schedule(timerTask, 0, 1000); //
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
timerSince++; //global integer variable with default value 0
if(timerSince == 5 * numberOfBtnClick){
//call your method
timer.cancel;
timerSince = 0;
}else{
//textView.setText(((5 * numberOfBtnClick)-timerSince)+" second left");
}
});
}
};
}
}
On event start button click call:
startTimer();
I'm working on a presentation app, which displays different images. There I wanted to to let the presentation slide through my List of images, video and pdf files, after a short amount of time.
I start my different views through intents, startActivityForResult(intent, RESULT_OK);
Starting videos and closing videos was not an issue. I used onPreparedListener and setOnCompletionListener and everything worked like a charm.
With pictures however, this was completely diffrent.
I created a new Thread in my ImageView and did put that thread to sleep(), after that I called the setresult() method and finish(). But instead of waiting, the picture wasn't shown at all and the presentation was stuck there, without setting the result and finishing the activity.
So I started searching for some explanation of time in android and found this explanation:
Explanation
I read through it and tried to get a good grasp on whats explained there. But the more I thought about it, the more I got insecure, which is the best way to implement the waiting behavior for my intended purpose.
So instead of some code, I am much more interested in, what you would advise me to use and why with a, if possible, detailed explanation.
elapsedRealtime()?
uptimeMillis()?
System.currentTimeMillis()?
From android docs:
• System.currentTimeMillis() is the standard "wall" clock (time and date) expressing milliseconds since the epoch. The wall clock can be set by the user or the phone network (see setCurrentTimeMillis(long)), so the time may jump backwards or forwards unpredictably. This clock should only be used when correspondence with real-world dates and times is important, such as in a calendar or alarm clock application. Interval or elapsed time measurements should use a different clock. If you are using System.currentTimeMillis(), consider listening to the ACTION_TIME_TICK, ACTION_TIME_CHANGED and ACTION_TIMEZONE_CHANGED Intent broadcasts to find out when the time changes.
• uptimeMillis() is counted in milliseconds since the system was booted. This clock stops when the system enters deep sleep (CPU off, display dark, device waiting for external input), but is not affected by clock scaling, idle, or other power saving mechanisms. This is the basis for most interval timing such as Thread.sleep(millls), Object.wait(millis), and System.nanoTime(). This clock is guaranteed to be monotonic, and is suitable for interval timing when the interval does not span device sleep. Most methods that accept a timestamp value currently expect the uptimeMillis() clock.
• elapsedRealtime() and elapsedRealtimeNanos() return the time since the system was booted, and include deep sleep. This clock is guaranteed to be monotonic, and continues to tick even when the CPU is in power saving modes, so is the recommend basis for general purpose interval timing.
If the time interval, you're going to measure, is relatively short, you can use pretty much any method which gives you correct time. I prefer currentTimeMillis(). In case the time interval is really long, the recommended method is to use elapsedRealtime().
Also, if you only want to do something with a delay, simply use: http://developer.android.com/reference/android/os/Handler.html#postDelayed(java.lang.Runnable, long) . It's simple and works great.
Simplest way to achieve that is CountDownTimer
private final class CountDownTimerImpl extends CountDownTimer {
//5 sec.
private static final long TIME_INTERVAL = 5000;
private final ImageView imageView;
private final List<Drawable> images;
public CountDownTimerImpl(ImageView imageView, List<Drawable> images) {
super(TIME_INTERVAL, TIME_INTERVAL);
this.imageView = imageView;
this.images = images;
//set first image from images array to imageView
imageView.setImageDrawable(images.get(0));
}
//this method is executed after TIME_INTERVAL (5 sec.)
public void onFinish() {
//remove drawable from imageView
imageView.setImageDrawable(null);
//remove this drawable from array
images.remove(0);
//if array is not empty start another count down
if (!images.isEmpty()) {
new CountDownTimerImpl(imageView, images).start();
}
}
public void onTick(long millisUntilFinished) {
//nothing to do here
}
}
You should start this CountDownTimer by:
new CountDownTimerImpl(imageView, images).start();
where images is of course an drawables array of your presentation images.
I have no time to test this solution but it should work - if not please leave a comment and I will update it later.
You can use TimerTask
int counter=0;
final Handler handler = new Handler();
Timer ourtimer = new Timer();
TimerTask timerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
counter++;
//you can do stuffs here say like if (counter==15) { do something}
}
});
}};
ourtimer.schedule(timerTask, 0, 1000);
You can do this in a different way writing a callback module
Create a activity call it BaseActivity and let all you activities to extend it
Now declare a method call is void callback(){} keep the body empty
now in onCreate create a timer as above and call the callback function your code will look like
onCreate(){
final Handler handler = new Handler();
Timer callTimer = new Timer();
TimerTask timerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
callback();
}
});
}};
callTimer.schedule(timerTask, 0, 1000);
}
Now in you activity override the callback method which will be called after the time you specified in timer,
Ex
Class a extends BaseActivity(){
#Override
onCreate(){
// playVideo
}
#Override
void onCallBack(){
//navigate to another activity
}
}