my app is working fine but i cant figure out why my void run(); still runs in the background when i click the "home" button.
I want my thread to pause the Thread onPause and start the thread again when onResume() i called!
Cant figure out what im doing wrong!
My code:
public class MainActivity extends ActionBarActivity {
Thread thread;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
thread = new Thread(new MyThread());
thread.start();
}
@Override
protected void onPause() {
super.onPause();
this.thread.interrupt();
Log.d("Method:","OnPause();");
}
@Override
protected void onResume(){
super.onResume();
this.thread.run();
Log.d("Method:","onResume();");
}
@Override
protected void onDestroy(){
super.onDestroy();
this.thread.interrupt();
finish();
Log.d("Method:","onDestroy();");
}
}
Inner class:
public class MyThread implements Runnable{
@Override
public void run() {
while(!Thread.currentThread().isInterrupted()){
if(Thread.currentThread().isInterrupted()){
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d("Method","void run()");
//Creates a file with SharedPreferences and make editable
SharedPreferences preferences = getSharedPreferences("MyPrime", Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = preferences.edit();
Random random = new Random();
BigInteger bigInteger = new BigInteger(10,random);
//Loads and gets the last int value store in the file
SharedPreferences preferences1 = getSharedPreferences("MyPrime",Context.MODE_PRIVATE);
final int numberInFile = preferences1.getInt("MyPrime",0);
if(bigInteger.isProbablePrime(random.nextInt(500))){
if(numberInFile < bigInteger.intValue()){
editor.putInt("MyPrime",bigInteger.intValue());
editor.commit();
}
}
}
}
}
It's because you're catching and ignoring the InterruptedException
that gets thrown when you interrupt the thread. Don't ignore exceptions!
If you take a look at the relevant docs, you can see that if you interrupt a thread while it's waiting in a sleep
call, that exception will be thrown and the interrupted status will be cleared (i.e. isInterrupted()
will return false). And your thread probably spends most of its time in that sleep call so it's likely it gets interrupted there.