对于这种情况,选择像 Retrofit 这样的网络库会很好。否则,您必须创建一个 HTTP url 连接,将图像下载为位图,然后将其保存到文件中。所有工作都需要在主线程之外完成。所以需要大量的线程池。所以让我们通过改造来解决问题
首先将改造作为依赖项添加到您的应用级 gradle 文件中
compile 'com.squareup.retrofit:retrofit:2.0.0'
compile 'com.squareup.retrofit:converter-gson:2.0.0'
然后创建一个包含图像视图的演示布局文件,在这个图像视图中我们将显示下载的图像
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/imageViewId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:maxWidth="1420px"
android:maxHeight="700px"
android:scaleType="fitCenter" />
</RelativeLayout>
之后让我们创建一个这样的网络 API 接口
public interface RetrofitImageAPI {
@GET("retrofit/images/uploads/android.jpg")
Call<ResponseBody> getImageDetails();
}
这是使用改造作为 sigleton 模式的好习惯 (see this)
但出于演示目的,我将在一个活动中展示所有内容
public class MainActivity extends AppCompatActivity {
String url = "http://www.delaroystudios.com/";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Button ButtonArray= (Button) findViewById(R.id.RetrofitImage);
ButtonArray.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
View VisibleImage = findViewById(R.id.RetrofitImage);
VisibleImage.setVisibility(View.GONE);
getRetrofitImage();
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
void getRetrofitImage() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitImageAPI service = retrofit.create(RetrofitImageAPI.class);
Call<ResponseBody> call = service.getImageDetails();
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Response<ResponseBody> response, Retrofit retrofit) {
try {
Log.d("onResponse", "Response came from server");
boolean FileDownloaded = DownloadImage(response.body());
Log.d("onResponse", "Image is downloaded and saved ? " + FileDownloaded);
} catch (Exception e) {
Log.d("onResponse", "There is an error");
e.printStackTrace();
}
}
@Override
public void onFailure(Throwable t) {
Log.d("onFailure", t.toString());
}
});
}
private boolean DownloadImage(ResponseBody body) {
try {
Log.d("DownloadImage", "Reading and writing file");
InputStream in = null;
FileOutputStream out = null;
try {
in = body.byteStream();
out = new FileOutputStream(getExternalFilesDir(null) + File.separator + "Android.jpg");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}
catch (IOException e) {
Log.d("DownloadImage",e.toString());
return false;
}
finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
int width, height;
ImageView image = (ImageView) findViewById(R.id.imageViewId);
Bitmap bMap = BitmapFactory.decodeFile(getExternalFilesDir(null) + File.separator + "Android.jpg");
width = 2*bMap.getWidth();
height = 3*bMap.getHeight();
Bitmap bMap2 = Bitmap.createScaledBitmap(bMap, width, height, false);
image.setImageBitmap(bMap2);
return true;
} catch (IOException e) {
Log.d("DownloadImage",e.toString());
return false;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item)
}
}
如果有帮助请不要忘记点赞并点击接受按钮。这对回答的人来说意义重大。
祝你有美好的一天