我正在开发一个扩展 Activity 并实现 Runnable 的 Android 应用程序。
问题是 run() 函数没有启动,我不确定实现 Runnable 是否会使其作为 AsyncTask 自动启动?
这是我的代码
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener, Runnable {
...
@Override
public void run() {
// mediaPlayer is myMediaPlayer
// progress is my SeekBar
Log.w("Tunesto", "testabababab");
int currentPosition = 0;
int total = mediaPlayer.getDuration();
progress.setMax(total);
while (mediaPlayer != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = mediaPlayer.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
progress.setProgress(currentPosition);
Log.w("MyApp", String.valueOf(currentPosition));
}
}
}
很明显,如果我来回启动 Run,UI Thread 会因为 sleep 方法而卡住屏幕,那么我应该如何让 Run 方法运行呢?
谢谢!
最佳答案
您必须在 Android 中使用 AsyncTask
。
执行步骤:
- 创建一个扩展
AsyncTask
的嵌套类 - 实现
doInBackground
方法,您的逻辑应位于此位置 - 在您需要调用
run()
的嵌套类实例上调用execute
方法
The fact is i'm not sure if it's possible to stop an asyntask?
您可以使用 AsyncTask
上的 cancel()
方法取消异步任务。有关这方面的更多详细信息,请参阅 Android 文档。
编辑
要将 run()
函数中的代码移动到 AsyncTask
中,您需要放置任何“设置”UI
的东西在 onPreExecute()
中,例如创建一个 ProgressBar
。然后把你的工作,比如调用sleep()
和其他不能在UI Thread
上完成的事情放在doInBackground()
里面。如果您需要更新搜索栏,您可以在 onProgressUpdate()
中通过在 doInBackground()
中调用 publishProgress()
来完成。最后,如果您需要关闭 ProgressBar
或做一些结束 UI
的事情,您将在 onPostExecute()
中完成。
之所以这样解释,是因为 AsyncTask
的所有方法都在 UI Thread
上运行,doInBackground()
除外。
关于java - Android - Runnable run() 函数不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20915832/