如何在 Android 中暂停/恢复线程? [英] How to pause/resume thread in Android?

查看:68
本文介绍了如何在 Android 中暂停/恢复线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个线程运行到一个活动中.我不希望线程在用户单击主页按钮时继续运行,或者,例如,用户接到电话.所以我想暂停线程并在用户重新打开应用程序时恢复它.我试过这个:

I have a thread that running into an activity. I don't want that the thread continuos running when the user click the home button or, for example, the user receive a call phone. So I want pause the thread and resume it when the user re-opens the application. I've tried with this:

protected void onPause() {
  synchronized (thread) {
    try {
      thread.wait();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
  super.onPause();
}
protected void onResume() {
  thread.notify();
  super.onResume();
}

它停止了线程但不恢复它,线程似乎被冻结了.

It stops the thread but don't resume it, the thread seems freezed.

我也尝试过使用已弃用的方法 Thread.suspend()Thread.resume(),但在本例中使用了 Activity.onPause() 线程不会停止.

I've also tried with the deprecated method Thread.suspend() and Thread.resume(), but in this case into Activity.onPause() the thread doesn't stop.

有人知道解决办法吗?

推荐答案

正确使用 wait()notifyAll() 使用锁.

Use wait() and notifyAll() properly using a lock.

示例代码:

class YourRunnable implements Runnable {
    private Object mPauseLock;
    private boolean mPaused;
    private boolean mFinished;

    public YourRunnable() {
        mPauseLock = new Object();
        mPaused = false;
        mFinished = false;
    }

    public void run() {
        while (!mFinished) {
            // Do stuff.

            synchronized (mPauseLock) {
                while (mPaused) {
                    try {
                        mPauseLock.wait();
                    } catch (InterruptedException e) {
                    }
                }
            }
        }
    }

    /**
     * Call this on pause.
     */
    public void onPause() {
        synchronized (mPauseLock) {
            mPaused = true;
        }
    }

    /**
     * Call this on resume.
     */
    public void onResume() {
        synchronized (mPauseLock) {
            mPaused = false;
            mPauseLock.notifyAll();
        }
    }

}

这篇关于如何在 Android 中暂停/恢复线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆