Call method every 30 second is not working - android

I want to update user location in every 30 second for which i am using volley request with Service.
The code in bellow:
public class CarLocationUpdateService extends Service {
Context context;
long delay = 1000; // delay for 1 sec.
long period = 10000; // repeat every 10 sec.
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
context = this;
Handler ha=new Handler();
ha.postDelayed(new Runnable() {
#Override
public void run() {
//call function
CarLocationUpdateVolleyClass carLocationUpdateVolleyClass=new CarLocationUpdateVolleyClass(context);
carLocationUpdateVolleyClass.carLocationRequest();
}
}, delay);
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
}

use JobScheduler with firbaseJobDispatcher
https://developer.android.com/topic/performance/scheduling.html

You can use fused location service to get location updates.I have created a service to get location updates.This code will give you the location in onLocationChanged method.
Check out my answer here here

try this :
mHandler = new Handler();
Runnable r = new Runnable() {
#override
public void run() {
f();
mHandler.postDelayed(this, 30000);
}
};
mHandler.postDelayed(r, 30000);

you have to call the handler.postDelayed() method again inside the runnable because it´s executed only once, that´s a normal behaviour. Seperate the runnable from the handler like this:
Handler ha = new Handler();
private Runnable yourRunnable = new Runnable() {
#Override
public void run() {
CarLocationUpdateVolleyClass carLocationUpdateVolleyClass=new CarLocationUpdateVolleyClass(context);
carLocationUpdateVolleyClass.carLocationRequest();
ha.postDelayed(yourRunnable, 30000);
}
};
ha.post(yourRunnable);
by the way, your question tells us something about 30 seconds, but you just call it every 10 seconds.

Try this it works
public void doWork(){
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// This method will be executed once the timer is over
// insert your data to db here
// close this activity
doWork();
Toast.makeText(MainActivity.this, "LOL", Toast.LENGTH_SHORT).show();
}
}, TIME_OUT);
}
And then simple call this method in onStartCommand()
doWork();

final Handler ha=new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
// ...
ha.postDelayed(this,30000);
}
};
ha.post(runnable);

Related

Remove callback not working in Handler

I have Handler.I call my function every 10 second.Code working perfect,but i can't stop handler.This is my source code
handler=new Handler();
handler.post(runnable);
public Runnable runnable = new Runnable() {
#Override
public void run() {
myFunction(position);
handler.postDelayed(runnable,10000);
}
};
public void myFunction(int position)
{
if(position>10)
handler.removeCallbacks(runnable);
}
I can call myfunction every 10 second,but i can't stop handler.Ho i can solve my problem?
The problem is that myFunction removes the callback, then you still call handler.postDelayed to schedule a new one. There are plenty of ways to refactor this. For example:
handler=new Handler();
handler.post(runnable);
public Runnable runnable = new Runnable() {
#Override
public void run() {
boolean reschedule = myFunction(position);
if(reschedule) {
handler.postDelayed(runnable,10000);
}
}
};
public boolean myFunction(int position)
{
if(position>10) {
return false;
}
return true;
}
You don't have to remove callbacks on the handler because a new one will not be scheduled in the first place.
You remove callback in myFunction but you postDelayed again when myFunction returns, just invert lines inside run()
#Override
public void run() {
handler.postDelayed(runnable,10000);
myFunction(position);
}

android implements runnable not working?

this is a simple code to understand the runnable .I tried but not working . can you guys help me pls this is my code
public class Autostart extends activity implements Runnable {
#override
public void run (){
System.out.println ("message");
}
}
}
this not printing any statements
If you are using an Activity, you need to write your code inside Activity lifecycle methods. onCreate() is called when the Activity is created. So starting your Runnable here would be the correct way to do it.
#Override
public void onCreate(Bundle savedInstanceState) {
Handler handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
System.out.println ("message");
}
};
handler.postDelayed(r, 1000);
}
You have to create a Thread object and call start() using that object.
Thread t = new Thread(this);
t.start();
Or Just use Handler
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Do Something here
}
}, 5000);
You can use below code to print a value after regular interval of time
public void callAsynchronousTask() {
final Handler handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
Log.e("on print timee", your value);
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 1000); // will execute after 1 sec
}
Hope this will help you
I found a similar solution to Swayam (android implements runnable not working?), however another handler.postDelayed reference within run() was required;
public void onCreate(
...
final Handler handler = new Handler();
final Runnable r = new Runnable()
{
public void run()
{
Log.i(TAG, "message");
handler.postDelayed(this, 1000);
...
}
};
handler.postDelayed(r, 1000);
Try following code
Handler mainThreadhandler = new Handler(getMainLooper());
mainThreadhandler.post(new Runnable(){
public void run(){
// UI work
}
});
public class Autostart extends activity implements Runnable {
Thread = thread;
#override
public void onCreate() {
thread = new Thread(this);
thread.start();
}
#override
public void run (){
System.out.println ("message");
}
}

service crashes while in loop - Android Studio

i'm basicaly tying to open up a service, that every 10 seconds, will show up a toast to say "10 seconds passed"
this is what i'm trying to do,
and after many research ive found out that to loop a service i'm
going to need to use while (true) - sleep... method...
but the service or my app crashes every time i start the service
(or to be exact every time the timer runs out)
what is my problem ?
my guess is that maybe the contaxt i'm passing to the toast is wrong ?
maybe there is another way to show toast every 10 seconds in loop (inside a serivice) ?
here is my service code >
package com.greenroad.candidate.mywallpaperchanger;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
/**
* Created by pitsponet on 31/08/2015.
*/
public class myService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(getApplicationContext(), "service created",
Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//try to run loop for showing up a toast
new Thread(new Runnable(){
public void run() {
// TODO Auto-generated method stub
while(true)
{
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//REST OF CODE HERE//
Toast.makeText(getApplicationContext(), "service started",
Toast.LENGTH_LONG).show();
}
}
}).start();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(getApplicationContext(), "service stoped",
Toast.LENGTH_LONG).show();
}
}
The reason for the crash, as explained by Brad, is because you are trying to perform UI operation from a non-UI Thread.
To achieve what you're trying to do, use the code below in your service. First of all remove your Thread in onStartCommand()
public class MyService extends Service {
private Handler mHandler;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mHandler = new Handler();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mHandler.postDelayed(ToastTask, 10000); // Starts the loop here
super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
// Stop the loop
mHandler.removeCallbacks(ToastTask);
super.onDestroy();
}
private Runnable ToastTask = new Runnable() {
#Override
public void run() {
Toast.makeText(MyService.this, "10 Seconds have passed", Toast.LENGTH_SHORT).show();
// Schedule this Runnable to run again after 10 sec
mHandler.postDelayed(this, 10000);
}
}
}
The reason that the service is crashing is because you're trying to run UI tasks (Toasts) outside of the main thread. Since you are creating a secondary thread for the infinite while loop, you'll need to post your Toast calls to the main looper as follows:
final Handler mainHandler = new Handler(getApplicationContext().getMainLooper());
mainHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Text to display", Toast.LENGTH_LONG).show();
}
});
That being said, I highly discourage using Thread.sleep() in any code that will run on a device, as this could lead to some serious issues. You should be able to accomplish the same thing (and also get rid of the infinite while-loop) using a Timer instead.
To use a Timer, you should be able to do something like the following:
// Schedules a TimerTask to execute every 10 seconds after a 10 second delay.
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
// Your Toast code here.
}
}, 10000, 10000);
Here's a complete example:
public class MyService extends Service {
private Handler mainHandler;
private Timer timer;
public void onStartCommand(final Intent intent, final int flags, final int startId) {
mainHandler = new Handler(getApplicationContext().getMainLooper());
timer = new Timer();
timer.schedule(new MyTimerTask(), 10000, 10000);
}
public void onDestroy() {
timer.cancel();
}
private class MyTimerTask extends TimerTask {
#Override
public void run() {
mainHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Text to display", Toast.LENGTH_LONG).show();
}
});
}
}
}

Repeat a Method for specific times in android

Here is a code which I want to repeat 50 times after every 3 seconds. if I am calling this function with 'for' loop or 'while' loop it is not working properly Please give me suggestion.
for (int i = 0; i < 50; i++) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
Generate_Ballon();
}
}, delay);
}
You can use CountDownTimer
See Example,
new CountDownTimer(150000, 3000)
{
public void onTick(long millisUntilFinished)
{
// You can do your for loop work here
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
Here onTick() method will get executed on every 3 seconds.
You should use Handler's postDelayed function for this purpose. It will run your code with specified delay on the main UI thread, so you will be able to update UI controls.
private int mInterval = 5000; // 5 seconds by default, can be changed later
private Handler mHandler;
#Override
protected void onCreate(Bundle bundle) {
...
mHandler = new Handler();
}
Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
updateStatus(); //this function can change value of mInterval.
mHandler.postDelayed(mStatusChecker, mInterval);
}
};
void startRepeatingTask() {
mStatusChecker.run();
}
void stopRepeatingTask() {
mHandler.removeCallbacks(mStatusChecker);
}
private int count = 50;
private Handler handler = new Handler();
private Runnable r = new Runnable() {
public void run() {
Generate_Ballon();
if (--count > 0) {
handler.postDelayed(r, delay);
}
}
};
handler.postDelayed(r, delay);

Android: execute code in regular intervals

I need to perform some code in regular intervals (connect to a server and pull data from MySQL database every minute). For this purpose I have a Sync class:
public class Sync {
static private Handler handler = new Handler();
Runnable task;
public Sync(Runnable task, long time) {
this.task = task;
handler.removeCallbacks(task);
handler.postDelayed(task, time);
}
}
and in my Activity I have:
public void onCreate(Bundle savedInstanceState) {
...
Sync sync = new Sync(call,60*1000);
...
}
final private Runnable call = new Runnable() {
public void run() {
//This is where my sync code will be, but for testing purposes I only have a Log statement
Log.v("test","this will run every minute");
}
};
I have tried this with a shorter time period for testing, but It only runs once. When it Logs the message for the first time, its also the last. Does anyone see what Im doing erong here? Thanks!
You can do that using the below code,
Hope it helps!
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
try{
//do your code here
}
catch (Exception e) {
// TODO: handle exception
}
finally{
//also call the same runnable to call it at regular interval
handler.postDelayed(this, 1000);
}
}
};
//runnable must be execute once
handler.post(runnable);
First you have to declare handler globally
Second you have to use post Delay method again in runnable to trigger it again.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Sync sync = new Sync(call,60*1000);
}
final private Runnable call = new Runnable() {
public void run() {
//This is where my sync code will be, but for testing purposes I only have a Log statement
Log.v("test","this will run every minute");
handler.postDelayed(call,60*1000);
}
};
public final Handler handler = new Handler();
public class Sync {
Runnable task;
public Sync(Runnable task, long time) {
this.task = task;
handler.removeCallbacks(task);
handler.postDelayed(task, time);
}
}
}
handler.postDelayed(task, time); will only execute once, if you want the code to trigger at regular intervals I would suggest a Timer and a TimerTask instead of a Handler and a Runnable.
TimerTasks can be set to run once, every x seconds, or with a fixed period e.g. x seconds - however long it took to run last time.
An alternative way, using ScheduledExecutorService's scheduleAtFixedRate:
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
public void beepEvery10Seconds() {
final Runnable beeper = new Runnable() {
public void run() { System.out.println("beep"); }
};
final ScheduledFuture<?> beeperHandle = scheduler.scheduleAtFixedRate(beeper, 0, 10, SECONDS);
}
private void doSomethingRepeatedly() {
timer.scheduleAtFixedRate( new TimerTask() {
public void run() {
try{
//Your code
}
catch (Exception e) {
// TODO: handle exception
}
}
}, 0, 10000);
}

Categories

Resources