gpt4 book ai didi

android - 在 Android 中停止线程已被弃用

转载 作者:行者123 更新时间:2023-11-30 01:38:54 25 4
gpt4 key购买 nike

我正在开发一个 Android 项目,我有一个线程正在发布到 PHP API 并检查响应。

在线程开始之前,我会显示一个可以取消的进度对话框。当按下取消键时,我调用了 thread.stop() 但这显示为已弃用。

我在 Google 上发现的所有内容都表明我有一个标志并在 while 循环中检查该标志并干净地退出线程,但是在我的情况下没有循环,那么我应该怎么做呢?

最佳答案

您面临的问题是已知问题,因为 threads are not supposed to be stopped by calling thread.stop(); 方法。

Android 也不鼓励在 Android 中使用 Java 线程,方便的是,Android 对线程之间的通信有一些额外的支持,Handler 类提供了一个整洁的队列消息机制,Looper 提供了一个方便的方法来处理相同的消息.

但是正如您提到的,您想要显示一个可以取消的进度对话框。当按下取消时,可以使用 AsyncTask 实现此类功能。

因为 AsyncTask 是在 Android 中实现并行性的最简单方法之一,而无需处理更复杂的方法,如 Threads。尽管它提供了与 UI 线程的基本级别的并行性,但它不应该用于更长的操作(例如,不超过 2 秒)。

Mainly AsyncTask should handle your problem, Since:

  1. It provides easy and standard recommended mechanism to publish background progress (see the Usage section here: http://developer.android.com/reference/android/os/AsyncTask.html)
  2. It provides method cancel(boolean); for cancelling a task(see the Cancelling a task section here: http://developer.android.com/reference/android/os/AsyncTask.html

AsyncTask 有四种方法来完成任务:

onPreExecute();
doInBackground();
onProgressUpdate();
onPostExecute();

cancel();方法来处理后台工作的取消。

doInBackground() 是最重要的地方,因为它是执行后台计算的地方。

代码:这是带有解释的骨架代码大纲:

public class AsyncTaskTestActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

// This starts the AsyncTask
// Doesn't need to be in onCreate()
new DownloadFilesTask().execute(url1);
}

// Here is the AsyncTask class:
//
// AsyncTask<Params, Progress, Result>.
// Params – the type (Object/primitive) you pass to the AsyncTask from .execute()
// Progress – the type that gets passed to onProgressUpdate()
// Result – the type returns from doInBackground()
// Any of them can be String, Integer, Void, etc.

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}

protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}

protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
}

有关更深入的知识,请访问以下链接:

https://blog.nikitaog.me/2014/10/11/android-looper-handler-handlerthread-i/ http://developer.android.com/reference/android/os/AsyncTask.html

关于android - 在 Android 中停止线程已被弃用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34777125/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com