How to call AsyncTask recursively in android? - android

i tried both the links : Starting AsyncTask recursively after a gap of 5 minutes and Need advice new AsyncTask recursive calling
but they didnt solve my problem.
i want to use asynctask recursively after every 10sec of gap.
iam creating an app in which a dialog box shows with some content whenever some condition full fill and i need to change that content for that i am trying to call asynctask with a combination of thread and handler.
Thanks in advance!!!!

This repeats every 1000ms:
handler must be final as it is accessed within inner class
final Handler handler = new Handler();
Thread threadObj = new Thread() {
public void run() {
// Asynctask
// delay
handler.postDelayed(this, 1000);
}
};
//to start thread
threadObj.start();
//to stop thread
handler.removeCallbacks(threadObj);

Create a runnable where you start the asynctask again and again and the start the task for the first time by calling handler.postDelayed(repeatingTask , 1000);
private Runnable repeatingTask = new Runnable() {
public void run() {
new MyAsyncTask().execute("my String");
handler.postDelayed(this, 1000);
}
};
This way the runnable will be repeated again and again.Hope this helps you.

public void recur()
{
private Runnable repeat = new Runnable() {
public void run() {
new AsycnCaller().execute();
handler.postDelayed(this, 10000);
}
};
}
call this function where you want Start
and also call this in postexecution of asyntask

Related

Setting Interval For Activiry and Perform Task

Is there any function in Android that can use to make the activity wait for an interval and continue working?
I mean , for example, I use setContentView() to set a layout , and after 3 seconds it will load another layout, and continue to do another job, I don't need to repeat doing same thing after an interval, just continue do another thing.
Thanks in advanced.
You can Use Following Method to Set Interval
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// This method will be executed once the timer is over
// Do your code here
}
}, 3000);
Here, 1000 = 1 Second
But Before running this code make sure that you are not in BACKGROUND PROCESS THREAD...otherwise this may cause an error..
Do it at Android Style:
Handler mHandler = new Handler();
mHandler.postDelayed(runnableHandler, 3000);
private Runnable runnableHandler = new Runnable() {
#Override
public void run() {
doSomething()
}
};
private void doSomething() {
// Before do something remove all callbacks from Handler
mHandler.removeCallbacks(runnableHandler);
andFinallyDoWhatYouNeed();
}

What code do i implement to have a time limit in my game

I'm createing a quiz that has a time limit and i dont know what to implement to have a timelimit in my level 1 class. what should i implement? can you show me a complete code?
am i correct?
private Runnable task = new Runnable() {
public void run() {
Intent intent = new Intent(getApplicationContext(),MainMenu.class);
startActivity(intent);
}
};
private void onCreate() {
Handler handler = new Handler();
handler.postDelayed(task, 60000);
There are different ways to do it. One way is to use a Runnable and a Handler.
First, define the Runnable:
private Runnable task = new Runnable() {
public void run() {
Log.i(TAG, "Time limit reached!");
// Execute code here
}
};
Then you call it (say at the start of the level, onCreate) with this Handler and postDelayed
Handler handler = new Handler();
handler.postDelayed(task, 60000);
The code within the run() method of the Runnable will execute 60 seconds after you call postDelayed
If you need regular notifications you can also use a CountDownTimer

Updating UI on button click after a certain time

I have a TextView. I want to update its text (append a "1") after 1 second of a button click.
public class HaikuDisplay extends Activity {
Method m;
Timer t;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t = new Timer();
m = HaikuDisplay.class.getMethod("change");
}
//Event handler of the button
public void onRefresh(View view)
{
//To have the reference of this inside the TimerTask
final HaikuDisplay hd = this;
TimerTask task1 = new TimerTask(){
public void run(){
/*
* I tried to update the text here but since this is not the UI thread, it does not allow to do so.
*/
//Calls change() method
m.invoke(hd, (Object[])null);
}
};
t.schedule(task1, 1000);
}
public void change()
{
//Appends a "1" to the TextView
TextView t = (TextView)findViewById(R.id.textView1);
t.setText(t.getText() + "1");
}
//Event handler of another button which updates the text directly by appending "2".
//This works fine unless I click the first button.
public void onRefresh1(View view)
{
TextView t = (TextView)findViewById(R.id.textView1);
t.setText(t.getText() + "2");
}
}
Consider all Exceptions be handled.
On first click, m.invoke gives InvocationTargetException. But it calls the method change() on successive invokes without any Exceptions(verified by logging). But it does not update the text. Where am I wrong?
Also, I see in the debugger that it creates a new Thread every time I click the button. That is fine. But why isn't it removing the previous Threads though their execution has been completed?
Do something like this
public void onRefresh1(View v) {
// You can have this in a field not to find it every time
final EditText t = (EditText) findViewById(R.id.textView1);
t.postDelayed(new Runnable() {
#Override
public void run() {
t.append("1");
}
}, 1000);
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// Update UI
}
}, 1000);
implement this on button click
UPDATE:
There are some other answers. dtmilano suggested another solution which is almost same to mine except he is calling the postDelayed method of View class and In my answer I used postDelayed method of handler class.
from the api reference of android the postDelayed method of Handler says
The runnable will be run on the thread to which this handler is
attached.
and the postDelayed method of View says
The runnable will be run on the user interface thread.
This is the only difference between these two solution. in my answer instead of creating new Handler every time you can use any other handler instance. Then the runnable will be run on that thread where that specific handler is declared. And if the postDelayed of EditText is used the the runnable method will be run on the user Interface Thread.
Now the performance issue, both has the same performance (If anybody can prove me wrong with reference I will be happy)
That's looking awful convoluted - have you considered using CountDownTimer instead?
new CountDownTimer(1000, 1000) {
public void onTick(long millisUntilFinished) {
// no-op
}
public void onFinish() {
change();
}
}.start();
This should call change (and hence change the text) on the UI thread, avoiding reflection and threading errors.
Hi Use the following code for that. Hope this will help you .
new java.util.Timer().schedule(
new java.util.TimerTask() {
#Override
public void run() {
// your code here
}
},
1000
);
Have a look of this question also.
display data after every 10 seconds in Android
You can try with this also.
private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
public void run() {
doStuff();
/*
* Now register it for running next time
*/
handler.postDelayed(this, 1000);
}
};
**EDIT 3**
Try with this once you are need to enable once (i mean if you put your code in yourmethod()== this will get automatically call 1 seconds once.
private Timer timer;
TimerTask refresher;
// Initialization code in onCreate or similar:
timer = new Timer();
refresher = new TimerTask() {
public void run() {
yourmethod();
};
};
// first event immediately, following after 1 seconds each
timer.scheduleAtFixedRate(refresher, 0,100);

Refresh parsing code android

I am using the JSON parser to parse some pages but I would like to recall the parsing function every 30 seconds. How can i do that ?
One of the method to call a method every 30 seconds is by using postDelay of Handler see below code.
Handler handler;
handler=new Handler();
handler.removeCallbacks(run);
handler.post(run);
Runnable run=new Runnable()
{
public void run()
{
parsing();
handler.postDelayed(run,30000);
}
};
Another approach is by using "AlarmManager"
That is a weird need, only parsing when necessary would probably be a lot better.
Anyway, you should have a look at Timers and background services but be sure of what you are doing : if you create a background service that make a network call twice every minute, if that call is costly, you could cost a lot of data and/or battery to your users which is not a good idea.
You can do it using a timer.
Timer myTimer = new Timer();
After that you can call use the schedule method to call your json parser method.
myTimer.schedule(new TimerTask()
{
public void run() {
timerMethod();
}
}, 0, 1000);
private void timerMethod()
{
this.runOnUiThread(doSomething);
}
private Runnable doSomething = new Runnable() {
public void run() {
// Your code for doing something
}

Android Async, Handler or Timer?

Every 5 seconds, I want to call my webservice and get text (not images), then display it in my ImageAdapter. What would be the best way to accomplish this?
final Handler handler = new Handler();
final Runnable r = new Runnable()
{
public void run()
{
callWebservice();
}
};
handler.postDelayed(r, 5000);
It depends if you want to use a different thread or not. Do you want the user to be able to interact with the application on the UI Thread while the images are downloading? If so, then I would definitely use an AsyncTask with a small ProgressBar (style="#android:style/Widget.ProgressBar.Small")
If you don't care about threading then what #inazaruk said.
Edit: the truth is most modern apps that retrieve data from a web service will use an AsyncTask with a discreet little loader in the corner just to let the user know it's updating.
Edit 2: here's an example of using a TimerTask to run something every 5 seconds. The key is the runOnUiThread(). There may be better ways to tie all the elements together but this accurately portrays all the pieces.
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
CallWebService();
}
}, 0, 1000);
}
private void CallWebService()
{
this.runOnUiThread(fetchData);
}
private Runnable fetchData = new Runnable() {
public void run() {
asyncTask.execute();
}
};
You should call asynctask inside the application main thread. Asynctask can't be called in a background thread.

Categories

Resources