I am trying to update a user location to our REST WebService every minute. I have tried using a Timer and a Runnable with Handler. Both of these are having problems.
Both work fine on my Emulator, although on our test devices the timer and Runnable are not running every minute, they update sporadically, sometimes within 1 second of each other, sometimes 5 minutes later, and anywhere in between..
Does anyone know why this might happen?
Context context;
Handler handler = new Handler();
#Override
public void onCreate() {
super.onCreate();
context = this;
handler.postDelayed(runnable, 0);
}
private Runnable runnable = new Runnable() {
#Override
public void run() {
updateLocation(context);
handler.postDelayed(this, 60000);
}
};
Related
I made a button that starts a Chronometer and I want to make the Chronometer restart after 15 minutes (to be looping). I am new to coding and I don't know how to manage that .
The code:
btPlay.setOnClickListener(v -> {
chronometer.setBase(SystemClock.elapsedRealtime());
chronometer.start();
});
btPlay.setOnClickListener(v -> {
startCounting=true;
});
myHandle = new Handler();
myHandle.post(new Runnable() {
#Override
public void run() {
myHandle.postDelayed(this, 1000);
if(startCounting){
//put your counting code here.
}
}
});
the void run function will get called every 1 second. you can add you code inside the run method.
Are you working on Android?.
If so, then you can try using the handler class to run repeated tasks.
I have a mic, which I want to activate for 5 seconds and then get that data. While the activity thread is still running.
Method 1: Is the activation of mic.
Method 2: Is for collecting the .amr/.mp3 output from the file.
And this will only happen one time.
I want that my activity should call method 1 at the start and after time X(or 5 seconds), it should call the other method. I am able to do this manually by using 2 buttons, one for record and other for save the file. But I am unable to do this automatically.
Thanks in advance.
Maybe something like:
firstMethodCall();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
secondMethodCall();
}
}, 5000);
Or better:
firstMethodCall();
new Timer().schedule(new TimerTask() {
#Override
public void run() {
secondMethodCall();
}
}, 5000);
Create a Thread.
Call first method, Thread.sleep() for some time
and Then Call Second Method.
Example:
Thread thread=new Thread(){
public void run(){
firstMethod();
Thread.sleep(time);
secondMethod();
}
};
//on button click
thread.start();
I need a thread repeating after 30 seconds that load data from web service.
i want to stop and start thread onResume and onPause so that it runs when screen is active and disable it when activity paused. Restart on resume.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
dataIfInternet(refreshTop);
}
}, 30000);
How to stop it when activity paused.
U can't pause the handler, so u need to cancel it in your onPause and post in again in your onResume
so u probably want something like this:
private Handler myHandler = new Handler();
in your onResume()
Runnable myRunnable = new Runnable()
{
#Override
public void run()
{
dataIfInternet(refreshTop);
}
};
myHandler.postDelayed(myRunnable, 30000);
and in your onPause()
// Cancel the runnable
myHandler.removeCallbacks(myRunnable);
I hope this solves your problem
My issue is that upon opening a certain activity in my project, I initialize a ScheduledExecutorService that sends an Intent to an IntentService class every 20 seconds.
Now when I first open the activity that contains the ScheduledExecutorService, the Intent fires once every 20 seconds as planned.
The issue arises when I exit the activity (staying in the app) and then reenter the activity. This results in the Intent being sent twice in a 20 second window, and I figure it has to do with my creating a new ScheduledExecutorService in the onResume of my activity.
How do I ensure that there is only one instance of ScheduledExecutorService at any given time?
Relevant code is below:
#Override
public void onResume() {
super.onResume();
ScheduledExecutorService scheduleIntentSender = Executors.newScheduledThreadPool(1);
scheduleIntentSender.scheduleAtFixedRate(new Runnable() {
public void run() {
sendIntent();
}
}, 0, 20,TimeUnit.SECONDS);
mDownloadStateReceiver =
new DownloadStateReceiver();
// Registers the DownloadStateReceiver and its intent filters
LocalBroadcastManager.getInstance(this).registerReceiver(
mDownloadStateReceiver,
testIntentFilter);
}
I suggest not doing that in your Activity because it's intended to display a UI. Do that in a Service instead. You can launch a Service in onStart and track the state of the executor in your Service, whether it's launched or not. Service is good because it's a background component which is not tied to UI at all. It will not be affected during screen rotations etc.
You should cancel the previous ScheduledExecutorService after closing activity:
ScheduledExecutorService scheduleIntentSender = Executors.newScheduledThreadPool(1);
final ScheduledFuture schedulHandler = scheduleIntentSender.scheduleAtFixedRate(new Runnable() {
public void run() {
sendIntent();
}
}, 0, 20,TimeUnit.SECONDS);
//Call schedulHandler.cancel(true) to cancel scheduleIntentSender in onDestroy()
I am following this tutorial to have a loading screen in my program. The tutorial says my activity should Sleep() using the Sleep() command, however it does not recognize Sleep() as a function and provides me with an error, asking if I would like to create a method called Sleep().
Here is the code sample:
public class LoadingScreenActivity extends Activity {
//Introduce an delay
private final int WAIT_TIME = 2500;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
System.out.println("LoadingScreenActivity screen started");
setContentView(R.layout.loading_screen);
findViewById(R.id.mainSpinner1).setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
//Simulating a long running task
this.Sleep(1000);
System.out.println("Going to Profile Data");
/* Create an Intent that will start the ProfileData-Activity. */
Intent mainIntent = new Intent(LoadingScreenActivity.this,ProfileData.class);
LoadingScreenActivity.this.startActivity(mainIntent);
LoadingScreenActivity.this.finish();
}
}, WAIT_TIME);
}
}
You can use one of the folllowing methods:
Thread.sleep(timeInMills);
or
SystemClock.sleep(timeInMills);
SystemClock.sleep(milliseconds) is a utility function very similar to Thread.sleep(milliseconds), but it ignores InterruptedException. Use this function for delays if you do not use Thread.interrupt(), as it will preserve the interrupted state of the thread.
The function is Thread.sleep(long).
Note, however, that you should not perform a sleep on the UI thread.
The code you posted is horrible. Please don't use that on an actual device. You will get an "Application Not Responding" error if you run something similar to this.
If you're using Handlers, keep in mind that a Handler is created on the thread where it runs. So calling new Handler().post(... on the UI thread will execute the runnable on the UI thread, including this "long running operation". The advantage is that you can create a Handler to the UI Thread which you can use later, as shown below.
To put the long running operation into a background thread, you need to create a Thread around the runnable, as shown below. Now if you want to update the UI once the long running operation is complete, you need to post that to the UI Thread, using a Handler.
Note that this functionality is a perfect fit for an AsyncTask which will make this look a lot cleaner than the pattern below. However, I included this to show how Handlers, Threads and Runnables relate.
public class LoadingScreenActivity extends Activity {
//Introduce a delay
private final int WAIT_TIME = 2500;
private Handler uiHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHandler = new Handler(); // anything posted to this handler will run on the UI Thread
System.out.println("LoadingScreenActivity screen started");
setContentView(R.layout.loading_screen);
findViewById(R.id.mainSpinner1).setVisibility(View.VISIBLE);
Runnable onUi = new Runnable() {
#Override
public void run() {
// this will run on the main UI thread
Intent mainIntent = new Intent(LoadingScreenActivity.this,ProfileData.class);
LoadingScreenActivity.this.startActivity(mainIntent);
LoadingScreenActivity.this.finish();
}
};
Runnable background = new Runnable() {
#Override
public void run() {
// This is the delay
Thread.Sleep( WAIT_TIME );
// This will run on a background thread
//Simulating a long running task
Thread.Sleep(1000);
System.out.println("Going to Profile Data");
uiHandler.post( onUi );
}
};
new Thread( background ).start();
}
use Thread.sleep(1000);
1000 is the number of milliseconds that the program will pause.
try
{
Thread.sleep(1000);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
Keep in mind: Using this code is not recommended, because it is a delay of time but without control and may need more or less time.