I'm using a timertask in the main activity in order to update some data repeatedly every X seconds.
This data is of static form, so it's a public static method
is this a bad technique? I mean, using static methods like this
I know there's this thing called Service, but there aren't really many examples online on how to use it in order to update every X seconds a variable that should be then accessed by some activity
so my question is, what's the difference between using a timer task and a service? is a timertask just a time counter and nothing else? does it run in parallel if it's being used with a handler or not? and what happens if you have something like this:
handler = new Handler();
t = new Timer();
task = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
//do stuff;
}
});
}
};
t.schedule(task, 0, 10000);
how exactly does this code work? what does it do? does it run in parallel? why even if I leave the activity where this code is first being called, it still runs? what makes it run in this case?
thanks in advance
TimerTask is part of standard Java and can be use for delayed or repeated execution for some piece of (Runnable) code. It's use is discouraged on Android. You can use a Handler instead.
A Service can be used as a independent and UI-less part of your Android application. It can run and create it's own threads and can be started for UI or with Intents through a AlarmManager for example.
It think want you want is a Service which creates it's own thread and does some work. When the work is done, memory will be freed on Android when the garbage collector kicks in, something you do not control and that's a good thing.
Related
I'm new to Android, so apologies if I'm missing anything obvious.
I'm writing an app that does something every few hundred milliseconds. The frequency varies, but no more often than every 300 or so.
Currently I have a class DoEvery that implements Runnable that is scheduled every X milliseconds using scheduleAtFixedRate from the main thread. That is working, but I want to add an animation that is started every time DoEvery.run executes using Drawable.start() and from what I've read it doesn't seem like that is possible since Drawable.start() needs to be run on the main thread. Using scheduleAtFixedRate also seems to make it difficult to change the frequency later.
Is there a way to start the animation from the DoEvery class? Or is there a better way to run something on a regular basis like this?
You could try this.
new Thread(new Runnable() {
#Override public void run() {
//I'm in the thread.
//if you are not in the Activity, pass the activity instance to your class
// and use myActivity.runOnUiThread(...)
runOnUiThread(new Runnable() {
#Override public void run() {
//I'm in the main thread
}
});
}
}).start();
I am having a service in my application that puts a runnable (in another java file) in a thread and starts it.
That is working fine for once, but i want it to be repetitive due to a certain period.
I need a good way to handle that.
Reason why I didn't use the answers to other questions is that I don't want it to repeat infinity nor I know how many times it'll repeat the task. It'll simply stop due to a button click in the UI.
I was thinking of using a loop with a sleep and if statement. But I think that's really bad design for my application. Is there a standard way for doing such thing?
Thanks...
You can use a handler that somehow acts like a timer but I think it is better for your situation.
You initialize it like this:
Handler delayhandler = new Handler();
Set the time it fires like this (in ms):
delayhandler.postDelayed(mUpdateTimeTask, 500);
And it calls this:
private Runnable mUpdateTimeTask = new Runnable()
{ public void run()
{ // Todo
// This line is necessary for the next call
delayhandler.postDelayed(this, 100);
}
}
You can also remove the next call with:
delayhandler.removeCallbacks(mUpdateTimeTask);
Use a TimerTask and have it execute your thread/method.
http://android.okhelp.cz/timer-simple-timertask-java-android-example/
http://developer.android.com/reference/java/util/TimerTask.html - You can use the Cancel() method to stop the TimerTask from executing.
Use the Timer it will run the thread after a given time period and when you want to stop just stop timer or set it to infinite time period.
I am a new Android developer. I am using the Handler class to schedule some operations. So I am creating runnable objects that calls some of my instance methods.
But I have a problem. Sometimes my run() method in Runnable object is called twice.
What could be the problem??
and there is the code
//deneme is a Handler.
deneme.postDelayed(new Runnable() {
#Override
public void run()
{
randomOyna();
//the instance method that I call.
}
}, 1000);
If don't schedule your Handler to run on another Thread than the UI-thread, there might be a hidden delay in the execution because your Runnable will also run on the UI-thread and thus will only be allowed to run when there is "time" for it. With this hidden delay, it might seem like it is run twice but in reality it's just and over-delayed running before a regular delayed Runnable.
Can't see a mistake just by looking the hint you gave us... But you might try plain old java to run threads instead of handler... Good luck...
Look here for more details
In my app I have a background task (using AsyncTask) that downloads stuff from a web site.
This task can be called from two separate activities, and it is possible to call it twice. So in "activity1" the background task "update" is called, and runs for a while (it takes something like 5-10 seconds usually).
Then while it's running, user switches to "activity2" and runs "update" again.
This gives problems: either a crash when both try to clear the database (command: DELETE FROM table) at the same time, causing a "database locked" error. Or they try to put the same item in the database causing a duplicate.
I've tried to solve this by setting a static boolean flag to true when a task is active.
When the task is called, it will check for this flag, and if true (i.e. the same task running on another thread) it goes into a wait loop using a handler until this flag clears, and then returns. This to make sure that when the background task returns, the update has been done. I have to use a Looper for that: this sometimes fails with an error "can create only one looper per thread". And I really have it in a way that only one looper can be started, this is the offending code, which appears at the start of the background task:
if (active) {
Looper.prepare();
handler = new Handler();
handler.postDelayed(new Runnable() {
int count = 0;
#Override
public void run() {
if (active) {
count++;
if (count < 1000)
handler.postDelayed(this, 100);
}
}
}, 100);
Looper.loop();
active = false;
return "done";
}
And to make matters worse it often seems to hang in this loop, without returning.
How to solve such a situation?
Why don't use synchronization instead? It sounds like a concurrency issue. Why don't you make sure that if the first background task is running then the second background task is sleeping until the first one is finished.
Or ensure somehow, that if the user switches to Activity number 2, the background task from activity number 1 is cancelled.
Instead of the AsyncTask you can consider to use IntentService. Have a look at the Android Service concept. The IntentService class ensures that only one request will be processed at one time.
I found this answer very useful during implementing IntentService with Activity callback communication.
Database locking issues solved by wrapping it into a ContentProvider. Besides problems with a method being called again before the previous instance was finished, I had the issue of different methods running in different background threads clashing while trying to write to the database.
Officially designed to allow for sharing data between apps, it also works great for sharing data between threads in a single app. The ContentProvider will make sure that no locking issues occur.
Hi I have a countdown timer in my activity oncreate method as follows
start1 = new CountDownTimer(level1time, 1000)
//timer updated every second
{
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
//switch activities
}
}
.start();
}
I then call start1.cancel later in my code. This works when this particular activity is started once but when this activity is created again later the activities switch instantly due to the first timer finishing.
My understanding is that a new timer should be created each time the activity is created but that does not seem to be the case. Does anyone know how to fix this problem?
In any case it's better to use Handlers instead of Timers. I generally create a final Runnable object that has what I want run after a certain time, create a new Handler in onCreate(), and post the Runnable to it after a certain delay with postDelayed(Runnable, int). If the user leaves the activity or you ever want it to not execute, you can simply call Handler.removeCallbacks(Runnable) with your defined Runnable to stop the "timer" on it.
That's a high-level approach to your question. Get familiar with the Handler class and this becomes a very easy problem.