英文:
How to do tasks like HttpURLConnection in the background of a app using Java in Android Studio?
问题
我基本上在遵循一个用于学习Android Studio的教程,该教程使用AsyncTask类来执行后台任务,例如HttpURLConnection。但问题是它产生了许多错误,后来我发现该类已被弃用。那么有什么替代方案吗?
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
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 {
public class DownloadingTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String result = "";
HttpURLConnection urlConnection = null;
URL url;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result = result + current;
data = reader.read();
}
return result;
} catch (IOException e) {
e.printStackTrace();
return "Failed";
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadingTask task = new DownloadingTask();
String s = null;
try {
s = task.execute("http://www.android.com/").get();
} catch (Exception e) {
e.printStackTrace();
}
Log.i("Msg", s);
}
}
注意:上述代码中已经做了一些修改以替代AsyncTask的使用,特别是在网络连接关闭方面。这个修改将确保在下载完成后正确关闭连接,以避免资源泄漏。
英文:
I am basically following a tutorial for learing Android Studio that uses AsyncTask class for doing background tasks like HttpURLConnection. But the thing is that it created a lot of error and later I found out that class was deprecated. So what is the alternative?
(Please provide an example code if you can)
CODE:
public class MainActivity extends AppCompatActivity {
public class DownloadingTask extends AsyncTask<String, Void, String>
{
@Override
protected String doInBackground(String... urls)
{
String result="";
HttpURLConnection urlConnection=null;
URL url;
try{
url=new URL(urls[0]);
urlConnection=(HttpURLConnection)url.openConnection();
InputStream in;
in = urlConnection.getInputStream();
InputStreamReader reader=new InputStreamReader(in);
int data=reader.read();
while (data!=-1)
{
char current=(char) data;
result = result + current;
data=reader.read();
}
return result;
}
catch (Exception e)
{
e.printStackTrace();
return "Failed";
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadingTask task= new DownloadingTask();
String s=null;
try {
s = task.execute("http://www.android.com/").get();
}
catch (Exception e)
{
e.printStackTrace();
}
Log.i("Msg",s);
}
}
答案1
得分: 0
以下是翻译好的部分:
这是一个示例,展示了如何使用AsynkTask下载图像。
private class DownLoadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView imageView;
DownLoadImageTask(ImageView imageView) {
this.imageView = imageView;
}
protected Bitmap doInBackground(String... urls) {
String urlOfImage = urls[0];
Bitmap logo = null;
try {
InputStream is = new URL(urlOfImage).openStream();
logo = BitmapFactory.decodeStream(is);
} catch (Exception e) { // 捕获下载异常
Log.v("download", e.getMessage());
}
return logo;
}
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
}
这是如何运行它的方法:
new DownLoadImageTask(img).execute(imageUrl);
任何更新都在onPostExecute
方法中进行,因为它在UI线程上运行。
是的,您说得对。AsynkTask已被弃用。您可以使用LoaderManager和Java Executor,或者Volley、Retrofit库。
对于下载图像,您可以使用Picasso和Glide库。
英文:
This is an example that shows how to download an image using AsynkTask.
private class DownLoadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView imageView;
DownLoadImageTask(ImageView imageView) {
this.imageView = imageView;
}
protected Bitmap doInBackground(String... urls) {
String urlOfImage = urls[0];
Bitmap logo = null;
try {
InputStream is = new URL(urlOfImage).openStream();
logo = BitmapFactory.decodeStream(is);
} catch (Exception e) { // Catch the download exception
Log.v("download", e.getMessage());
}
return logo;
}
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
}
This is how to run it
new DownLoadImageTask(img).execute(imageUrl);
Any update is done in this method onPostExecute as it runs on the UI Thread.
Yes, You are right. AsynkTask is deprecated. You can use LoderManager and Java Executor
Or Volley, Retrofit libraries
For downloading images, You can use Picasso and Gilde Libraries.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论