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
}
Related
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 I want to do is just a basic implementation of handler example. I have a TextView on the mainActivity, and once the page loads the handler is supposed to run and show the user value coming from SystemClock.uptimeMillis. But ıt doesn't work more than once. How can I make this code run?
public class MainActivity extends Activity {
long uptoMS=0L;
TextView tv;
Handler handler=new Handler();
long swaptime=0L;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)findViewById(R.id.textView1);
uptoMS=SystemClock.uptimeMillis();
tv.setText(String.valueOf(uptoMS));
handler.post(runner);
}
private Runnable runner=new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
swaptime+=uptoMS;
tv.setTag(String.valueOf(swaptime));
handler.post(this);
}
};
}
See this below example
scheduler(){
TimerTask tasknew = new TimerSchedulePeriod();
Timer timer = new Timer();
// scheduling the task at interval
timer.schedule(tasknew,100, 100);
}
// this method performs the task
public void run() {
System.out.println("timer working");
}
timer = new Timer();
refreshTask = new TimerTask() {
#Override
public void run() {
swaptime+=uptoMS;
tv.setTag(String.valueOf(swaptime));
handler.post(this);
}
};
timer.schedule(refreshTask,
100, 100);
Well, there some problems with your code.
Firstly, you use setTag() instead of setText(), so the value will never update.
tv.setTag(String.valueOf(swaptime));
Secondly, you get uptoMS once in onCreate(), and then you use it in every "handler loop". I don't know what you try to achive but it's unlike that you want this.
Thirdly, you instantly repost your Runnable, so the main thread's message queue will be busy. You should give some break instead of instant reposting. For example you can wait 100 ms between the updates, so the TextView will be updated 10 times in every second.
handler.postDelayed(this, 100);
And finally, however others suggest you using Timer, just ignore them. Handler is the Android way to achieve tasks like this.
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
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();
}
};
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.