What is the best way to schedule an event?
I was thinking about the new Calendar API, but it requires an internet connection at least to create a new calendar.
Is there any API for creating a schedule which doesn't require internet connection?
Check out the FAQ You are more likely to keep getting help if you go back to your previous questions and accept answers that were helpful to you. Also see How does accepting an answer work? for more info.
AlarmManager will let you do that.
If you want to schedule your event for relatively soon though Handler is a better choice. You can use it to post a runnable like this:
Runnable r = new Runnable() {
public void run() {
doSomething();
}
}
Handler h = new Handler();
h.postDelayed(r, 1000);
This will execute the run method of your runnable in one second. You can change the second parameter of the postDelayed method to change the interval of time that passes. It is in milliseconds.
EDIT: Also note that the "best" way to do something is subjective, and generally depends on exactly what you are trying to do. If you can be more specific about what you are trying to schedule and how far in advance you'd like to schedule it then perhaps we can help narrow it down to the "best" choice. But without more info there is no way that we can tell you which is "best"
Related
Since I am new to android programming, I am not sure how to write code efficiently hence the reason for this question. I am creating an app. A basic app in which the app generates 10 random math questions and evaluates it from left to right (ignoring orders of operations). E.g. 3+5/2 should equal 4 instead of 5.5.
I am getting the error Launch timeout has expired. I have researched this and found out that its because the main thread is doing too much work. How do I overcome this? My app first does alot randomizing integers, could that be the case?
This is the code. It is pretty long.
P.S. in the display method, i hrdcoded it to display the first elements just to see if it will display.
public void initAnswers(String[] questionToBeLooped){
for(int i =0; i < questionToBeLooped.length; i++){
if(mathOperations.length == 2){
runningTotal = evaluateAnswerTwoOperations(mathOperations[0], mathNumbersInIntFormat.get(0), mathNumbersInIntFormat.get(1));
}else{
int operationsCounter =0;
int numbersCounter =1;
runningTotal = mathNumbersInIntFormat.get(0);
while(mathOperations[operationsCounter] != "="){
runningTotal = evaluateAnswerTwoOperations(mathOperations[0],runningTotal,mathNumbersInIntFormat.get(numbersCounter));
}
}
answers[i] = runningTotal;
}
}
Could someone tell me how to write this efficiently and also can you provide some tips to generate fluent and efficient apps.
Not sure what in your code is the cause, but you should offload the heavy work into an AsyncTask. AsyncTask will allow you to execute code in a background thread via doInBackground and callback to the UI thread via onPostExecute. The heavy work you are doing is probably something around the looping constructs you have.
Keep in mind that you cannot modify the UI from the background, so if you need to update UI, wait until the heavy work is finished and do it in onPostExecute.
See the docs here on AsyncTask.
Also worth noting that AsyncTask has a lot of flaws, but since you are new - it is where I would recommend to start.
I am working on an Android project that works well, and it uses Handler methods. But, I can't find this particular method in any tutorials or documentation.
The Handler method looks like this:
private Handler OnName = new Handler() {
#Override
public void handle() {
//do some stuff that needs it's own thread
finish();
}
};
It is overwriting the handle() method, I am not finding it in the documentation
Am I looking in the wrong place, or what is this for?
Can someone a short explanation or a good link of when handle()
triggers?
I am working on an android project where previous coders used Handlers
More importantly, the previous coders didn't use a distinct class name, causing confusion for others encountering the code base.
Please slap the previous coders with a trout for me.
Am I looking in the wrong place, or what is this for?
As you discovered, this isn't android.os.Handler, but something else. My guess is that it is a subclass of android.os.Handler, where (for whatever reason) they are ignoring the Message normally delivered to handleMessage().
I have an AppWidget that may receive two consecutive update request. To be shown it has to programmatically draw five 50x50 bitmaps, setting some PendingIntent and get some configuration (just to give you a little idea of the work load). It takes around 60 milliseconds between the two calls.
The option I have found so far to avoid the unnecessary update is to have a static field, something like:
public class myWidget extends AppWidgetProvider {
private static long lastUpdate;
#Override
public void onReceive(Context context, Intent intent) {
if((System.currentTimeMillis()-lastUpdate) > 200) {
doUpdates(context);
}
lastUpdate = System.currentTimeMillis();
}
}
With performance and "best practice" in mind...
Which do you think is the best solution in this case?
1) Use the static field (like in the example)
2) Just let the widget update twice
3) Other
In other words, is the use of the static field more harmful than just letting the widget update twice?
To be shown it has to programmatically draw five 50x50 bitmaps, setting some PendingIntent and get some configuration (just to give you a little idea of the work load). It takes around 60 milliseconds between the two calls.
Note that this will cause your UI to drop frames if you happen to have your UI in the foreground at the time the update request(s) come in.
Which do you think is the best solution in this case?
Both #1 and #2.
There is no guarantee that your process will still be around between the two subsequent update requests. Probably it will be around, given that you appear to be optimizing for two updates within 200ms. But it's not guaranteed. So, use the static data member for optimization purposes, but ensure that your code will survive the process being terminated in between.
I'd suggest using SystemClock.elapsedRealtime(), though, instead of System.currentTimeMillis(). System.currentTimeMillis() is based on the real-time clock, which can be adjusted on the fly (e.g., NITZ signals, SNTP updates, user manually changing the clock). SystemClock.elapsedRealtime() is guaranteed to be monotonically increasing, and so it is a better choice for this sort of scenario. Only use SystemClock.elapsedRealtime() when you need to tie something to "real world" time (e.g., as part of work with Calendar objects), not for interval timing.
Ive got an app with a class that implements Runnable. Where a thread is started and the run() methid overridden. This runs my graphics.
1.st question : how often is the run() called upon? i havent set a time for this so it must be a default value?
2.nd question : i want stuff to be done after a certain amount of time (2min,5min,10min) etc. What would be the best way to go about doing this, i was thinking about using an int as an counter and once it hits a specific value does what i want.
1.st question : how often is the run() called upon? i havent set a time for this so it must be a default value?
The run() method in your Thread is called when you call it eg. yourThread.start();
2.nd question : i want stuff to be done after a certain amount of time (2min,5min,10min) etc. What would be the best way to go about doing this, i was thinking about using an int as an counter and once it hits a specific value does what i want.
There are to options. Either you could call Thread.sleep() method (NB: Never do this in your UI thread).
Or you can do it the way you described above. So in your run() method you would have a while() loop and check on every iteration if the difference of the lastUpdate and the current time in milli seconds is bigger than the wanted period eg. 2 min, 5 min or 10 min.
I hope this helps.
Regarding question 2 - use ScheduledExecutor
1.st question : how often is the run() called upon?
You can find out for yourself, put this at the start of your Runnable:
Log.v("Running Runnable", System.currentTimeMillis() + "");
2.nd question : i want stuff to be done after a certain amount of time (2min,5min,10min) etc.
Extend a HandlerThread (it initializes the Looper for you!), add a Handler as a class variable, and use the Handler's postDelayed() or postAtTime() methods.
The exact amount of time in between calls to run() depends on the processor. The time between each call is the sort of thing that's really visible by the nanosecond. If you're trying to create a timer, I'd recommend using System.currentTimeMillis(), calling it in the run() method, and once the difference is greater than or equal to 1000 milliseconds, the actual timer decrements by one. This will keep track of seconds, and you can use it as a base for minutes and generating other events at specific times.
I collect some information inside a Spinner and this information can change
for example something may disappear or something new may come
I want the application to store this information every 100 seconds in a database
is it possible to do something like this?
I'm thinking of creating a database and within this database storing this information
but I'm not sure about this "every 100 seconds" part, how would I do this?
I'm thinking that maybe I will have to create a process that will be running in parallel, this process will have a time counter and when 100 seconds have passed, the function that will store the information in the database will be called
But I'm not sure if this is possible. I mean, creating such a counter that will run in parallel with the other application.
maybe there is something easier
thanks in advance
On Second Thought:
This is probably not the way to go(AlarmManager). A much better way would be to bind a listener to the spinner. That way you will only react and save data when there is new data to save.
Can you provide some details on the Spinner you are using and perhaps we can work out the event binding.
For the storage, use SQlite: http://developer.android.com/reference/android/database/sqlite/package-summary.html
For the 100 second interval, use the AlarmManager:
This class provides access to the system alarm services. These allow
you to schedule your application to be run at some point in the
future. When an alarm goes off, the Intent that had been registered
for it is broadcast by the system, automatically starting the target
application if it is not already running. Registered alarms are
retained while the device is asleep (and can optionally wake the
device up if they go off during that time), but will be cleared if it
is turned off and rebooted.
http://developer.android.com/reference/android/app/AlarmManager.html
Take a look at this answer for a code sample and further discussion: Android: How to use AlarmManager
I have some same requirement and done this in My application using CountDownTimer
and Created one Custom Class extending CountDownTimer and in that when Finish, I just did perform my data loading and initialized the same object agian to run after using Start
public class MyCounter extends CountDownTimer {
public MyCounter(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
MCObject.cancel();
MCObject = new MyCounter(_intMCCounter, 1000);
MCObject.start();
new tempAysnc().execute(paramList); // code to get data or store data write your code to insert data into database
}
#Override
public void onTick(long millisUntilFinished) {
}
}
In your Activity onCreate() write this code to initiate it first time.
_intMCCounter = 60000 * 5; //set interval to every 5 minutes
MCObject = new MyCounter(_intMCCounter, 1000);
MCObject.start();
and in onDestroy of your Activity write this code to cancel the Timer.
MCObject.cancel();
I think better way is to create a Listener which will check for the data change. If it founds any change of data then it make a function call which will store data in database.
You can use SQLite
I don't see any reason why this couldn't be done. (Only problem is maybe you run out of storage space after a while if you are planning to insert new data constantly)
Check ScheduledThreadPoolExecutor
http://developer.android.com/reference/java/util/concurrent/ScheduledThreadPoolExecutor.html
Android natively supports SQLite so you can use it as your database.