gpt4 book ai didi

java - 在 doInBackground 中创建一个处理程序

转载 作者:行者123 更新时间:2023-11-29 07:42:05 30 4
gpt4 key购买 nike

我正在尝试创建一个计时器线程,它会定期查看下载缓冲区,并查看我创建的用于下载文件的线程中有多少字节。但是,我总是收到此消息:无法在未调用 Looper.prepare() 的线程内创建处理程序

我的代码:

private class DownloadPdfTask extends AsyncTask<String, Integer, String> {

private PowerManager.WakeLock mWakeLock;

@Override
protected String doInBackground(String... params) {

// ... code
try {
// Create the URL, needs java.net.URL
URL mUrl;
mUrl = new URL(params[0]);

// Variable to measure Latency (until first byte is received)
long beforeConnect = System.currentTimeMillis();


// Open connection to the URL
mConnection = (HttpURLConnection) mUrl.openConnection();
mConnection.connect();

long afterConnect = System.currentTimeMillis();

mLatency = afterConnect - beforeConnect;

// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (mConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + mConnection.getResponseCode()
+ " " + mConnection.getResponseMessage();
}

fileLength = mConnection.getContentLength();

// Download the file
is = mConnection.getInputStream();
final File osFile = new File("sdcard/filename.pdf");
if (!osFile.exists())
{
try
{
osFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
return e.toString();
}
}

os = new FileOutputStream(osFile);

final byte data[] = new byte[4096];
int count;

// Create timer thread to peek buffer and see how many bytes are there
final Handler mHandler = new Handler();
Runnable mHandlerTask = new Runnable() {
@Override
public void run() {
mThroughputEverySecond += " " + total;
// Run timer task every second
mHandler.postDelayed(this, 1000);
}
};

while ((count = is.read(data)) != -1) {
// Allow canceling with back button
if (isCancelled()) {
is.close();
return null;
}
total += count;
// Publishing the progress
if (fileLength > 0) { // Only if total length is known
publishProgress((int) (total * 100 / fileLength));
}
os.write(data, 0, count);
}

// Stop timer task after download is completed
mHandler.removeCallbacks(mHandlerTask);

} catch (Exception e) {
return e.toString();

最佳答案

尝试使用 new Handler(Looper.getMainLooper()) 实例化您的处理程序。

关于java - 在 doInBackground 中创建一个处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29041061/

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