In my application I have a activity that displays contents from internet..... I just want to know how can I auto refresh the activity.....
Please suggest and provide
This code for If you want first create the view and after that refreshing page at specified time span then use following code.(here mention refreshing rate is 20 seconds) It Works Fine and Automatic refresh in every 20 seconds.
public class MainActivity extends Activity {
Handler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.mHandler = new Handler();
m_Runnable.run();
}
private final Runnable m_Runnable = new Runnable()
{
public void run()
{
Toast.makeText(MainActivity.this,"in runnable",Toast.LENGTH_SHORT).show();
MainActivity.this.mHandler.postDelayed(m_Runnable,20000);
}
};
}
Consider purchasing "The Busy Coder's Guide to Advanced Android Development", to read in particular Chapter 13, "Advanced Service Patterns". The source code for this chapter is available on Github, with this handy introduction:
CWAC Wakeful: Staying Awake At Work
The recommended pattern for Android's equivalent to cron jobs and Windows scheduled tasks is to use AlarmManager. This works well when coupled with an IntentService, as the service will do its work on a background thread and shut down when there is no more work to do.
It goes over coupling AlarmManager
with an IntentSerivce
. This is far more complex than using a Handler, but packaging data services in a Service
is a good practice and actually compulsory if you want to share data between different applications.
If you don't know how to use services, consider purchasing The Busy Coder's Guide to Android Development. It "comes with" the book I mentioned earlier. I bought all of them yesterday and they're a veritable goldmine.
try this one, it works well :)
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.mHandler = new Handler();
this.mHandler.postDelayed(m_Runnable,5000);
}//onCreate
private final Runnable m_Runnable = new Runnable()
{
public void run()
{
Toast.makeText(refresh.this,"in runnable",Toast.LENGTH_SHORT).show();
refresh.this.mHandler.postDelayed(m_Runnable, 5000);
}
};//runnable
@Override
protected void onPause() {
super.onPause();
mHandler.removeCallbacks(m_Runnable);
finish();
}
/*Above method needs to be there otherwise activity will be updating itself again and again even if the activity is paused i.e. back button or home button is pressed*/
You can use handler to do a loop process, like this:
Handler handler = new Handler();
Runnable refresh;
In the first call time:
refresh = new Runnable() {
public void run() {
// Do something
handler.postDelayed(refresh, 5000);
}
};
handler.post(refresh);
Since you cannot call a non-final variable inside an annonymous class, you will have to declare refresh
in the containing class.