android asynctask例子,寻找在Android中使用AsyncTask的get()的好例子

看起来好像

AsyncTask.get()阻塞了来电线程,

AsyncTask.execute()没有.

您可能希望使用AsyncTask.get()测试您想要测试特定Web Service调用的测试用例,但不需要它们是异步的,并且您想要控制完成所需的时间.或者任何时候您想在测试套件中测试您的Web服务.

语法与execute相同:

private class DownloadFilesTask extends AsyncTask {

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

}

return totalSize;

}

protected void onProgressUpdate(Integer... progress) {

setProgressPercent(progress[0]);

}

protected void onPostExecute(Long result) {

showDialog("Downloaded " + result + " bytes");

}

}

new DownloadFilesTask().get(5000, TimeUnit.MILLISECONDS);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面给出一个使用 HttpURLConnection 实现 HTTP 请求的完整例子。 1. 在 AndroidManifest.xml 文件添加网络权限: ``` <uses-permission android:name="android.permission.INTERNET" /> ``` 2. 在 MainActivity.java 文件编写网络请求代码: ``` import android.os.AsyncTask; import android.os.Bundle; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class MainActivity extends AppCompatActivity { private TextView mTextView; private static final String API_URL = "https://jsonplaceholder.typicode.com/todos/1"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTextView = findViewById(R.id.text_view); new HttpGetRequest().execute(API_URL); } private class HttpGetRequest extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { String urlString = params[0]; // 获取请求 URL try { URL url = new URL(urlString); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setConnectTimeout(5000); // 设置连接超时时间 urlConnection.setReadTimeout(5000); // 设置读取超时时间 urlConnection.connect(); int responseCode = urlConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream inputStream = urlConnection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); return response.toString(); } else { return "Error: " + responseCode; } } catch (IOException e) { e.printStackTrace(); return "Error: " + e.getMessage(); } } @Override protected void onPostExecute(String result) { mTextView.setText(result); } } } ``` 3. 在 activity_main.xml 文件添加一个 TextView 控件: ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/text_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:textSize="20sp" /> </RelativeLayout> ``` 4. 运行应用,可以看到 TextView 控件显示了从 API 获取到的数据。 注意:上面的例子使用AsyncTask 来在子线程执行 HTTP 请求。但是,AsyncTask 有一些局限性,例如不能取消已经执行的任务,同时也不方便在多个 Activity 或 Fragment 复用。因此,建议使用第三方网络库如 OkHttp 或 Retrofit。这些库已经封装了网络请求,使用起来更加方便,同时也具有更好的性能和可扩展性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值