I need to make a network request every 5 seconds to update a list with data. I'm thinking of the best way to do it in Android/Kotlin.
I was advised to use CountDownTimer with onTick() and onFinish methods. But I'm not sure if it's going to work well in my case because the timer will be started once in onCreate() method in activity but I need the job to start/finish every 5 seconds.
Could you advise, please?
You can use an CountDownTimer, but you should take care that the networktraffic is on a background thread.
Or you can use Alarmmanager https://developer.android.com/reference/android/app/AlarmManager, maybe if you want to start a service even if your app is in background?
val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(this, MyBroadcastReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0)
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(),
5 * 1000, // 5 seconds
pendingIntent)
Or an Handler would work like this:
https://developer.android.com/reference/android/os/Handler
val handler = Handler()
val runnable = object : Runnable {
override fun run() {
// Perform network request
// Update UI if necessary
handler.postDelayed(this, 5 * 1000) // 5 seconds
}
}
handler.post(runnable)
Related
I have made an android app which starts a service.
I want it to run every 30 seconds. Please don't worry about battery, it is not a public use app and it will run only ONCE for 3-4 hours in the entire week when the game is being played.
Now the problem I am facing is that initially when the app starts and service starts it runs every 30 seconds as expected but once the phone is locked or the app goes to the background then android operating system does not let it run for less than every minute. It is triggered after every 60 seconds.
I know it is android's restriction.
My questions is that is there someway to by pass it or some trick that can make it run every 30 seconds.
public static void startBTService()
{
Utilities.showDebugInfo("Start BT Service called...");
if ( Utilities.getCurrentBTService() != null )
{
Utilities.showDebugInfo("BT Service already running...");
Utilities.sendDataAckUI("BT Service already running...", false);
Utilities.runJavascript("showBTServiceButtons(true);");
return;
}
AlarmManager alarmManager = (AlarmManager)((Activity)Utilities.context).getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(Utilities.context, OnAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(Utilities.context, 1111, intent, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 30000, pendingIntent);
Utilities.runJavascript("showBTServiceButtons(true);");
Utilities.sendDataAckUI("BT Service started...", false);
}
Please help.
Thanks
I had a similar problem using the AlarmManager. The solution I used was a Timer queued up inside an IntentService.
int delay = 1000 * 15; // delay for 15 sec.
int period = 1000 * transmitInterval; // interval to send data
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
transmitData();
}
}, delay, period);
I have done an application that fire an alarm in certain time, and i am stuck on implementing remind me after half an hour functionality
what can i do to implement receiver, or service or anything that runs after half an hour of clicking the button of reming me after half an hour
any suggestions ?
Edited the code from Android execute a function after 1 hour to half an hour.
// the scheduler
protected FunctionEveryHalfHour scheduler;
// method to schedule your actions
private void scheduleEveryHalfHour(){
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
new Intent(WAKE_UP_AFTER_HALF_HOUR),
PendingIntent.FLAG_UPDATE_CURRENT);
// wake up time every 1 hour
Calendar wakeUpTime = Calendar.getInstance();
wakeUpTime.add(Calendar.SECOND, 30 * 60);
AlarmManager aMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
aMgr.set(AlarmManager.RTC_WAKEUP,
wakeUpTime.getTimeInMillis(),
pendingIntent);
}
//put this in the creation of service or if service is running long operations put this in onStartCommand
scheduler = new FunctionEveryHalfHour();
registerReceiver(scheduler , new IntentFilter(WAKE_UP_AFTER_HALF_HOUR));
// broadcastreceiver to handle your work
class FunctionEveryHalfHour extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
// if phone is lock use PowerManager to acquire lock
// your code to handle operations every half hour...
// after that call again your method to schedule again
// if you have boolean if the user doesnt want to continue
// create a Preference or store it and retrieve it here like
boolean mContinue = getUserPreference(USER_CONTINUE_OR_NOT);//
if(mContinue){
scheduleEveryHalfHour();
}
}
}
You can write a simple service with a timer and whenever the time is up.it can do your thing.all you need to do is start a service with a timer inside of it
I am developing an android app and want to know how can I receive an incoming call.
I have created a broadcast receiver and in its on receive method I have given a 15 second delay using countdown timer on call state ringing.Now, I want to receive an incoming call in countdown timer's finish method. I am not getting any way to implement it. can anyone suggest ?
thanks!!
instead of using a countdown timer, set a one-time Alarm instead which then fires your method to receive the call. You can do something like this:
AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
Intent cHandler = new Intent (this, CallHandlers.class);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, cHandler, PendingIntent.FLAG_CANCEL_CURRENT);
//Set an alarm that will trigger in 15 seconds
alarm.set(AlarmManager.RTC_WAKEUP,System.currentTimeMillis() + (15 * 1000), pi);
hi you can use a coundowntimer visit http://developer.android.com/reference/android/os/CountDownTimer.html
new CountDownTimer(15000, 1000) {
public void onTick(long millisUntilFinished) {
//here you can have your logic for call
}
public void onFinish() {
mTextField.setText("done!");
}
}
.start();
for working code example of countdowntimer visit http://www.filefactory.com/file/cbbbc38/n/SimpleCountDownTimerExample.zip
I recently just learned and developed a widget. I understand that the widget have an auto update at every 30 - 60 minutes minimum. Now I have been asked to reduced that auto update to 5 minutes.
So I have thought up for creating another Service Thread that is constantly running a countdown timer every 5 minutes and refreshes the app to check for any possible errors. These errors are actually ping tests results. If a server is down, I will execute a Toast Message to inform the user that this server is down.
So, how should I go about doing this? Or is there a better suggestion. Please enlighten me.
May this helps you:
Buddy use TimerTask to call after specific time interval
Timer timer = new Timer();
timer.schedule(new UpdateTimeTask(),1, TimeInterval);
and
class UpdateTimeTask extends TimerTask {
public void run()
{
// code here
}
}
Or You can Use AlaramManager also:
Set AlarmManager like this:
private static final int REPEAT_TIME_IN_SECONDS = 60; //repeat every 60 seconds
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis(),
REPEAT_TIME_IN_SECONDS * 1000, pendingIntent);
Change AlarmManager.RTC to AlarmManager.RTC_WAKEUP if u want to wake up phone when it goes off. More about AlarmManager Click Here
Those two parameters also means that your alarm time will be System.currentTimeMilis() which is time in UTC.
I think better use runnable with postDelayed, like this:
private Handler handler = new Handler();
private Runnable runnable = new CustomRunnable();
private class CustomRunnable implements Runnable {
public void run() {
// your logic
handler.postDelayed(runnable, REFRESH_TIME);
}
}
REFRESH_TIME — your constant to refresh in millis. Just run once handler.postDelayed(runnable, REFRESH_TIME); where you want.
I am creating the following thread in my onCreate but realized that this call needs to execute every 20 minutes or so:
Thread t = new Thread() {
public void run(){
setTopUsers();
}
};
t.start();
private void setTopUsers() {
...
for(Map.Entry<Double,String> entry : myMap.entrySet()) {
key = entry.getKey();
value = entry.getValue();
if(...)
view.setText(...)
}
}
The method that's being called simply processes information from a TreeMap and displays the results to the UI. I'm trying to figure out what is the best way to handle this: 1) Create a Timer that runs on a separate thread (but I've read that's not a good idea), 2) Create a service Intent that processes every 20 minutes (seems like overkill).
Any suggestions?
http://developer.android.com/reference/android/app/AlarmManager.html#setRepeating%28int,%20long,%20long,%20android.app.PendingIntent%29
Something like this should work:
Intent intent = new Intent(this, ProcessService.class);
PendingIntent pIntent = PendingIntent.getService(this, 0, intent, 0);
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.cancel(pIntent);
am.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), INTERVAL, pIntent);
Let the user decide. Implement both, there's nothing worse than a repeating process the user can't control.