call network periodically for any updates only in foreground - android

I would like to periodically check for updates doing network call every 30 sec and update listview accordingly, only if my screen is in foreground (thus not from service). What I am doing for that is -
private void refreshPeriodically()
{
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
new callToMyAsyncTask().execute(context);
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 30*1000); //execute in every 30 sec
}
but, that hangs my list while scrolling.
What should I do for that?

You shouldn't use handler. When you call handler.post() it will run on UI thread so your list will freeze. Start a new callToMyAsyncTask in run method in TimerTask without using handler and you can call timer.cancel() when your activity is not in foreground.
Also I think you should use scheduleAtFixedRate instead of schedule.
However I think you may have some problems without service. When you cancel timer it will not cancel current callToMyAsyncTask and when it call onPostExecute activity is no longer available. But I don't know it will crash or not.

Related

Stop Handler in service Android

I have been using handler inside service class, the handler is responsible for sending location every 5 seconds via socket. When logging out, the service gets stopped but the handler still running.
I tried every possible way, By using any boolean variable is not feasible in my case because i have to start again that handler.
public Runnable mn_Runnable12 = new Runnable() {
public void run() {
gps = new GPSTracker(LocationService.this);
if (gps.canGetLocation()) {
latString = Double.toString(gps.getLatitude()); // Live
logString = Double.toString(gps.getLongitude());
connection= MyApplication.getInstance().getConnection();
if (connection!=null&&connection.isConnected()) {
sendLocation();
}
}
}
};
this is inside onCreate() of service.
T.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
mHandler12.postDelayed(mn_Runnable12, 5000);
}
},
5000,
5000);
I try to stop the handler in onDestroy method of service, service gets topped but the handler still running.
#Override
public void onDestroy() {
System.out.println("Location Service Detaroy-----");
if (connection.isConnected()) {
unSubscribe();
}
mHandler12.removeCallbacksAndMessages(null);
mHandler10.removeCallbacksAndMessages(null);
}
You Also have to cancel Timer Since its running repeatedly with an interval.
First cancel timer and then remove handlers callback.
T.cancel();
T.purge();
// remove handler here

Android: Task every 10 seconds (exactly)

We have an app who should process a task every 10 seconds. This should be more or less exact, which means that a difference of 1 or 2 seconds is OK, but not gaps of 20 seconds or more.
This should work regardless if the app is open, in foreground or in background.
We implement this via AlarmManager, but it is not working properly. If the smartphone is not plugged in and it is running in background, there are gaps in the execution.
With Android 4.3., we have gaps (about 30 seconds) from time to time, with Android 5.x we have fewer gaps, but gaps about 5 or 10 minutes long!
I think there must be a way to implement this, an alarm clock is also possible and is exact.
More about the app: It works in a service and a broadcast receiver is implemented. This means the service is restarted if I wipe away the app or restart the handy. This works correctly. The only problem is the 10 second task.
Any hints? How is an alarm clock implemented? Which calls, API?
I tried different ways until now without success.
Thanks
Hans
public void callAsynchronousTask() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
PerformBackgroundTask performBackgroundTask = new PerformBackgroundTask();
// PerformBackgroundTask this class is the class that extends AsynchTask
performBackgroundTask.execute();
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 10000); //execute in every 10000 ms
}
You can do it with handler and runnable, which I think is preferred by Android..
public class ActivityMain extends Activity
{
private Handler mainHandler = new Handler();
private Runnable backgroundTask = new Runnable() {
#Override
public void run() {
//do your background task
mainHandler.postDelayed(this, 10000);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainHandler.postDelayed(backgroundTask, 10000);
}
}
Use of "AlarmManager" with "broadcast Receiver" and "service". These 3 component will make your requirement fulfill.
Using Alarm Manager to generate a Broadcast Receiver, and from BroadcastReceiver start a Service where you can put your desired code of logic to get your task done in every 10 Seconds.

Scheduling Repeating Tasks in a Service

I need to repeat a task every 1 hour in the background (I am sending some info to my server).
I tried to use a service with a post delay handler calling it self.
handler = new Handler();
runable = new Runnable() {
#Override
public void run() {
try{
//sending info to server....
}
catch (Exception e) {
// TODO: handle exception
}
finally{
//also call the same runnable
handler.postDelayed(this, 1000*60*60);
}
}
};
handler.postDelayed(runable, 1000*60*60);
This did not work, in small time interval of 1 minutes it worked fine, when i changed it to 5 minutes it worked for about 5 repetitions and then the timing got wrong and after an hour the service shut down.
i want to try to use a AlarmManager but in the documentation
it says "As of Android 4.4 (API Level 19), all repeating alarms are inexact"
does anybody know how inexact it is? is it seconds? ,minutes?
can i rely on this to work on time?
does anybody have any other suggestions for repeating tasks in a service?
Thanks
You can use this This Code is for repeated calling on oncreate method or anyother thing
public void callAsynchronousTask() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
onCreate();
} catch (Exception e) {
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 1000); //execute in every 1000 ms
}

schedule an asynctask after a variable time duration every time in android?

I am using a timeschedular in android to schedule an AsyncTask in my app.I was able to work it out well,now i want every time the duration after which the task runs to be changed i am using this code
ip=3000;
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
play_duration=durat.get(vn);
ip=Integer.valueOf(play_duration);
ip=ShowImages.ip*1000;
Showtime s1 = new Showtime();
s1.execute(what,f12,transi,play_duration);
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0,ip);
i am trying to change the value of ip variable every time in the thread but it do not change and i do not know why my thread always run after the initial value of ip that is 3000 miliseconds, can someone suggest a way to do it..thanks
to change component on the UI use the runOnUiThread,
see here, here and here to do that thing on the background you can use something like -
while(true)
{
runOnUiThread() {
do some stuf here;
}
Thread.Sleep(300); //<--- that should be nothing for the user and enough for the cpu
}
if you need more accurate answer post your code and ill guide you through

How to set timer to call a function every n minutes?

I want to set up a timer in an Android application that will call a function after every 15/30/45 and n minutes when user login. But also it will stop timer when user log off. and timer begin from start if user login again. I want that option(15/30/45/n miutes) to be saved in database so that I can update list after sync.
Is Timer a good approach or I need to use alarm services? Or is there any system services required?
Is it possible to change previous doc/file in local phone database storage to new doc that is receiving through web server? is there any system services required to do so?
Use following code to call your function every 15/30/45
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
#SuppressWarnings("unchecked")
public void run() {
try {
"Your function call "
}
catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, "Timer value");

Categories

Resources