I've got an activity with the following code:
Handler dataLoaderHandler = new Handler();
int mInterval = 3000;
public MyActivity myself;
Thread dataLoader = new Thread( new Runnable() {
#Override
public void run() {
Log.e("MyActivity","ReloadData");
new DataLoader(new JSONData(myself)).execute(Configuration.dataURL);
dataLoaderHandler.postDelayed(dataLoader, mInterval);
}
});
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myself = this;
... some other stuff...
dataLoader.start();
}
... other code ...
#Override
protected void onDestroy() {
super.onDestroy();
Log.e("MyActivity","onDestroy ending thread");
try { dataLoader.join(); } catch(Exception e) { e.printStackTrace(); }
Log.e("MyActivity","onDestroy called");
}
When I hit the back button my activity gets destroyed but the thread still continues to run every 3 seconds. Why is the thread not stopped or better said deleted?
Because you haven't stopped it. Since calling stop() on a thread is already deprecated, you should stop the thread within the thread itself. This can be easily done by calling return on it.
However, don't expect your Thread to finish immediately you hit your back button. The Thread will probably run up until Android OS determines it has to (basically, it may take a while to stop even you call it).
You may want to check that question I made a time ago, it's well answered.
try:
boolean finished=false;
Handler dataLoaderHandler = new Handler();
int mInterval = 3000;
public MyActivity myself;
Thread dataLoader = new Thread( new Runnable() {
#Override
public void run() {
if(!finished){
Log.e("MyActivity","ReloadData");
new DataLoader(new JSONData(myself)).execute(Configuration.dataURL);
dataLoaderHandler.postDelayed(dataLoader, mInterval);}
}
});
#Override
protected void onStop() {
super.onStop();
finished=true;
}
Related
I have been trying to stop a handler in my onPause(). Despite of calling removeCallbacks(timeRunnable) or removeCallbacksAndMessages(timeRunnable), the handler is not stopped. I have seen many answers here. But nothing worked. I might be missing something here.
Code:
public Runnable timeRunnable = new Runnable() {
#Override
public void run() {
Log.d("Here is my task");
timeHandler.postDelayed(timeRunnable, 5000);
}
};
public void startTimeHandler() {
timeHandler.post(timeRunnable);
}
public void stopTimeHandler() {
timeHandler.removeCallbacks(timeRunnable);
}
#Override
protected void onPause() {
super.onPause();
stopTimeHandler();
}
I am using below code snippet to run a thread every 10 seconds and update UI based on the values received from Server, stop thread on onPause.
Declare below variables in your class:
public class ActivityPortfolio extends AppCompatActivity {
Handler handler = new Handler();
Runnable runnable;
int delay = 10*1000;
//---------
In your onResume:
#Override
protected void onResume() {
handler.postDelayed(new Runnable(){
public void run(){
doSomething();
handler.postDelayed(this, delay);
}
}, delay);
super.onResume();
}
onPause():
#Override
protected void onPause() {
super.onPause();
handler.removeCallbacks(runnable); // this alone didnt work as we are calling postDelayed() in background as well.
handler.removeCallbacksAndMessages(null);//after adding this it stops thread
}
I just wanted to test Log.i() and look at the console in android studio. In the code below onResume should start the thread and run() should write an endless stream of "dings" with the tag "run" in the monitor. But the run method apparently only gets called once. Why?
public class MainActivity extends Activity implements Runnable {
Thread gameThread = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("onCreate","getting started");
}
public void run() {
Log.i("run","ding");
}
#Override
public void onResume() {
super.onResume();
gameThread = new Thread(this);
gameThread.start();
}
}
You're missing the notion of what threading really does. It allows you to run a unit of work asynchronously. So, all the same normal rules apply. The reason it only runs once, is because the thread exits after run() returns. So just like any other method, you should put something like
while(true)
{
Log.i("run","ding");
}
inside of run(). Ideally you would actually check some condition so that you can exit the thread as needed.
Finally, it is probably a bad idea to have your MainActivity implement Runnable. Typically it is good style to have a thread implemented by its own class, for example DingThread implements Runnable.
You're missing while loop that why its run only once. Use below code. This is the better approach to use thread concept.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("onCreate","getting started");
}
#Override
public void onResume() {
super.onResume();
startThread();// create thread obj and start
}
private GameThread mGameThread = null;
private void startThread() {
stopThread();// if thread already running stop it then create new thread and start (for avoiding multi-threading).
mGameThread = new GameThread();
mGameThread.start();//start the thread.
}
//To stop the thread simply call this method.
private void stopThread() {
if(mGameThread != null) {
mGameThread.setStop();
mGameThread = null;
}
}
private class GameThread extends Thread {
private boolean mIsStop;// mIsStop is default false
#Override
public void run() {
while (!mIsStop) { // if mIsStop is false then only come inside loop.
Log.i("run","ding"); //log will print
}
}
public void setStop() {
mIsStop = true;// set mIStop variable to true.
}
}
}
I can't stop this thread when I exit my activity or application.
public class MyThread extends Thread {
public Handler handler;
#Override
public void try{
Looper.prepare();
handler = new Handler();
Looper.loop();
}
}
...
myThread = new MyThread();
myThread.start();
final Runnable runnable = new Runnable() {
#Override
public void run(){
doSomething();
myThread.handler.postDelayed(this,30*1000);
}
};
myThread.handler.post(runnable);
#Override
public void onStop(){
myThread.handler.removeCallbacksAndMessages(null);
myThread.handler.getLooper().quit();
myThread = null;
}
I can confirm that all the onStop() code is run, but the logcat still shows the thread running after I exit the application.
I think even if I remove the battery and smash the device with a sledgehammer it will still keep running, I've tried everything. :~) I must be missing something about handlers, loopers, and threads. Please help.
add a boolean flag in the Activity, say "shouldThreadRun", set to true in onResume(), set to false in onPause()
In run() of the Thread, check whether the Activity is still running
if(shouldThreadRun){
doSomething();
myThread.handler.postDelayed(this,30*1000);
}
EDIT: I've found that what I'm describing below only occurs on my emulated device (Nexus 5, target api 19, 4.4.2 with Intel Atom (x86) cpu), but NOT on my physical device (HTC One)....
EDIT2: Edit1 was due to an IllegalStateException that I didnt catch. Added some code to check if the thread was already running before trying to start it. This combined with the accepted answer resolved my issue.
I have implemented an activty that starts a new thread in the activity's onCreate method, like this:
...
private boolean running;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
running = true;
new Thread(null, work, "myThread").start();
}
Runnable work = new Runnable() {
#Override
public void run() {
while (running) {
//Doing work
}
}
};
I'm "pausing" my thread with my activity's onPause method, like this:
#Override
protected void onPause() {
running = false;
super.onPause();
}
So I thought that resuming it would be just as easy...ยจ
#Override
protected void onResume(){
running = true;
super.onResume();
}
but my thread isn't resuming. Any ideas why? Thankful for any help.
Marcus
All of the answers i think have some issues about your running variable because you can not write and read a variable from two different Threads without synchronized block so i post my own answer:
package com.example.threadandtoast;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
public class MonitorObject{
public boolean running = true;
public String message = "";
public boolean mustBePost = true;
}
Thread t;
int threadNameCounter = 0; // i use this variable to make sure that old thread is deleted
// when i pause, you can see it and track it in DDMS
Runnable work = new Runnable() {
boolean myRunning;
#Override
public void run() {
synchronized(mSync) {
myRunning = mSync.running;
}
while (myRunning) {
runOnUiThread(new Runnable() { // in order to update the UI (create Toast)
#Override // we must switch to main thread
public void run() {
// i want to read the message so i must use synchronized block
synchronized(mSync) {
// i use this variable to post a message just for one time because i am in an infinite loop
// if i do not set a limit on the toast i create it infinite times
if(mSync.mustBePost){
Toast.makeText(MainActivity.this, mSync.message, Toast.LENGTH_SHORT).show();
// the message post so i must set it to false
mSync.mustBePost = false;
// if i am going to pause set mSync.running to false so at the end of infinite loop
//of thread he reads it and leaves the loop
if(mSync.message.equals("Main Activity is going to pause")){
mSync.running=false;
}
}
}
}
});
synchronized(mSync) {
myRunning = mSync.running;
}
}
}
};
final MonitorObject mSync = new MonitorObject();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onPause() {
super.onPause();
synchronized(mSync) {
// mSync.running = false; you can not set it here because
// it is possible for the thread to read it and exit the loop before he posts your message
mSync.mustBePost=true;
mSync.message = "Main Activity is going to pause";
}
}
#Override
protected void onResume(){
super.onResume();
threadNameCounter++;
synchronized(mSync) {
mSync.running = true;
mSync.mustBePost=true;
mSync.message = "Main Activity is going to resume";
}
t = new Thread(work,"My Name is " + String.valueOf(threadNameCounter));
t.start();
}
}
Or you can use this code:
public class MainActivity extends ActionBarActivity {
Thread t;
int threadNameCounter = 0; // i use this variable to make sure that old thread is deleted
// when i pause, you can see it in DDMS
String message = "";
boolean isPost = false;
Runnable work = new Runnable() {
#Override
public void run() {
while (true) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if(!isPost){
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
isPost = true;
if( message.equals("Main Activity is going to pause")){
t.interrupt();
}
}
}
});
if(Thread.currentThread().isInterrupted()){
break;
}
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onPause() {
super.onPause();
message = "Main Activity is going to pause";
isPost = false;
}
#Override
protected void onResume(){
super.onResume();
message = "Main Activity is going to resume";
isPost = false;
threadNameCounter++;
t = new Thread(work,"My Name is " + String.valueOf(threadNameCounter));
t.start();
}
}
you can also use semaphore or wait-notify approach.
i put public String message = ""; and public boolean mustBePost = true; in to mSync object but it is
not necessary because only main thread have an access to them.
if you have any problem please ask.
The statement running = false; will stop execution of the Thread, instead of pausing it. Use two variables: One for stopping current Thread, and another for pausing and resuming the Thread, as follow:
boolean isThreadPause=false;
Runnable work = new Runnable() {
#Override
public void run() {
while (running) {
if (!isThreadPause) {
// Doing work
}
}
}
};
In the onPause event of the Activity, set isThreadPause to true, and in the onResume event, set isThreadPause to false.
This is because your Runnable object stops when the while loop stops. You could try this:
Runnable work = new Runnable() {
#Override
public void run() {
while () {
if(running){
//Doing work
}
}
}
};
I found the code pasted below in a post on this forum back in 2011. I was using a timer to trigger the execution of doSomeWork but doSomeWork spawns an asynctask and (as I found out) asynctasks can only be spawned from the UI thread. So, I converted to using this postDelayed function of a Handler.
Now this code does indeed call doSomeWork every ten seconds and my asynctask no longer has problems. But when I call stopRepeatingTask() it does NOT stop the execution of doSomeWork - it keeps getting called every ten seconds.
This code is in a service and stopSelf() has been called but the code keeps running. The Android system doesn't even show the service as running but it's still calling doSomeWork.
What's wrong? How can I stop it?
Thanks, Gary
private int m_interval = 5000; // 5 seconds by default, can be changed later
private Handler m_handler;
#Override
protected void onCreate(Bundle bundle) {
// ...
m_handler = new Handler();
}
Runnable m_statusChecker = new Runnable() {
#Override
public void run() {
doSomeWork(); //this function can change value of m_interval.
m_handler.postDelayed(m_statusChecker, m_interval);
}
};
void startRepeatingTask() {
m_statusChecker.run();
}
void stopRepeatingTask() {
m_handler.removeCallbacks(m_statusChecker); // <--this does not appear to work
}
Add a status to your code to stop respawning new tasks:
private int mInterval = 5000; // 5 seconds by default, can be changed later
private Handler mHandler;
private boolean mIsRunning;
protected void onCreate(Bundle bundle) {
// ...
mHandler = new Handler();
}
Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
if (!mIsRunning) {
return; // stop when told to stop
}
doSomeWork(); // this function can change value of mInterval.
mHandler.postDelayed(mStatusChecker, mInterval);
}
};
void startRepeatingTask() {
mIsRunning = true;
mStatusChecker.run();
}
void stopRepeatingTask() {
mIsRunning = false;
mHandler.removeCallbacks(mStatusChecker);
}