如何暂停/恢复线程的Andr​​oid?线程、Andr、oid

2023-09-11 20:17:34 作者:逗嘴小行家°

我有运行到一个活动的线程。 我不想,线程连续的运行,当用户单击主页按钮或例如,用户接听电话的手机。 所以我想暂停线程,并恢复它当用户重新打开应用程序。 我试着这样的:

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.

我也试图与德precated方法 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.

任何人都知道该如何解决?

Anyone know the solution?

推荐答案

使用等待() notifyAll的()正确使用锁。

样品code:

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

}