Runnable,Pause和Resume线程

时间:2015-05-13 19:01:45

标签: java android runnable onresume onpause

我的应用程序工作正常,但我无法弄清楚为什么我的void run();当我点击" home"按钮。

我希望我的线程暂停Thread onPause并在onResume()调用时再次启动线程!

无法弄清楚我做错了什么!

我的代码:

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();");

}

}

内班:

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();

                }
            }
        }

    }

}

2 个答案:

答案 0 :(得分:2)

这是因为你正在捕捉并忽略在你打断线程时被抛出的InterruptedException。不要忽视例外!

如果您查看the relevant docs,可以看到如果您在sleep调用中等待线程时中断线程,则会抛出该异常并且中断状态将为已清除(即isInterrupted()将返回false)。并且你的线程可能大部分时间都花在那个睡眠调用上,所以它可能会在那里被中断。

答案 1 :(得分:0)

从onCreate中删除代码并使你的onResume像这样工作。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
protected void onResume(){
    super.onResume();
    thread = new Thread(new MyThread());
    thread.start();
    Log.d("Method:","onResume();");
}