Create alarm automatically everytime Database gets new data - android

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.

Related

Countdown timer in recycle view for online order

Hi there
I have a problem in my food orders app I want to create countdouwn timer in my recyclew view depends on start order time and finish after 2 minutes and after finish cancel the order ...
The problem is
1 - how to every order has a different timer from start order to 2 minutes
2 - how order timer still working even app is close and if app not open automatically cancel the order ...
android main
I am trying everything to do that but iam filed...
Iam reading about how to run countdouwn in background and also reading about how to display countdouwn timer in recyclew
But cant found solutions to my cases...
Any help please...
Use a class for example, Dish. Now have a member of that class named as cancelTimer or whatever you want to call it. Using Handler, make the countdown for that particular instance. This way you can have different timers for each of your dishes.
Example:
Dish dish1 = new Dish();
dish1.setCancelTimer(10000);
Handler h = new Handler();
h.postDelayed(new Runnable(){
public void run(){
dish1.setCancelTimer(dish1.getCancelTimer()-1000);
h.postDelayed(this, 1000);
}
}, 0);
Repeat for all other dishes like:
Dish dish2 = new Dish();
dish2.setCancelTimer(50000);
Handler h2 = new Handler();
h2.postDelayed(new Runnable(){
public void run(){
dish1.setCancelTimer(dish1.getCancelTimer()-1000);
h.postDelayed(this, 1000);
}
}, 0);

Timer should run One time but with different Intervals

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();

Self Prepuating Timer That Modifies GUI in Android

I'm making an application and a certain part in my application I store a list of prices along with the time that the prices last for (they do not all last the same amount of time). So a price lasts a certain time then once that price's time is up it changes to another price (this part changes the UI or basically it updates a textview with the new price). So what I need is a timer that sets the timer again with the new time length and once it's done make the UI change. For instance say that each of the pairs represent the price amount and the time (in seconds): { {$2.53,1.4s}, {$4.57,4.45s}, {$1.23,3.6s}...}
So when the timer starts off the textview displays $2.53 and the timer lasts 1.4s and then it should grab the next price $4.57 and be set again but this time for 4.45s. This process continues on and on until the game is finished. I was thinking of using the CountDownTimer and resetting itself once the onFinish() method is called (I haven't verified if this idea works yet). Are there any other ideas?
You can use a countdown timer and onFinish method you call back the function and it starts another timer:
private void startWheatPrices(long gameTime)
{
//other stuff executed
StartWheatTimer(GameTimeDifference);//starts the timer for the first time
}
private void StartWheatTimer(long TimerAmount)
{
WheatTimer = new CountDownTimer(TimerAmount, 10) {
public void onTick(long millisUntilFinished)
{
}
public void onFinish()
{
//other stuff executed
WheatPricesTV.setText(Float.toString(PriceList.get(0).get(WheatPriceIndex).price));//price is changed
if(InGameplayMode)
StartWheatTimer(convertToMilliseconds(PriceList.get(0).get(WheatPriceIndex).timeLength));//call back the function to start the timer again
}
}.start();
}

Android, how to measure an elapsed amount of time

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
}
}

How to loop an AsyncTask infitinitely

I have the following type of application
Pull data prices down from feed
Process them and put them into my custom adapter
Display the prices in a ListView (so I call setAdapter).
Now the final stage is to repeat this infinitely perhaps at 5 second intervals.
So I have AsyncTask for handling the datadownload and on onPostExecute I update the adapter and it displays.
But how can I loop this whole activity with intervals of 5 seconds ?
Do I need to create a thread that calls this asynctask and in the thread use a loop with 5 second sleep ?
Thanks !!
You could use the TimerTask class and its scheduleAtFixedRate() method that download the data and after that update your interface using the post() method of a view so to avoid the AsyncTask at all. There are more way to do this, I should know because you want to download all every 5 seconds
The problem could be what to do when the datadownload fails or when it hangs for more than 5 seconds.
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
TimerMethod();
}
}, 0, 10000);
}
private void TimerMethod()
{
getActivity().runOnUiThread(Timer_Tick);
}
private Runnable Timer_Tick = new Runnable() {
public void run() {
new AsyncTask().execute();
}
};

Categories

Resources