Android development, download pictures at the specified address from the Internet

Android development, download pictures at the specified address from the Internet

There are two types of icons in the Android client interface.
One type is stored in the resource. This type of picture is fixed, such as the "message", "contacts", and "settings" icons in the title bar under the app. , It may change unless the version is updated.
The second type is that the client requests the server, and the server responds with the corresponding picture. To be precise, most of the picture background of the application is returned from the server.
In this demo, the type of Bitmap is involved. As for the related knowledge of Bitmap, Xiaobai doesn't know much about it. Interested friends can learn more about the following:
Summary of bitmap-----Xu Fuji 456 The
specific operation method is as follows:

  1. Add permissions in AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> 
  1. Create a new class with only one method for downloading pictures from the Internet and storing them in external storage, returning the Bitmap type:
    public static Bitmap loadPicture(String c_url){ } httpurlPicture.java The old rules for the content of the method are as follows:


//实例化url
URL url = new URL(c_url);
//建立http连接
HttpUrlConnection conn = (HttpUrlConnection)url.openConnection();
//设置读取超时限制,设置请求方式
conn.setReadTimeOut(5000);
conn.setRequestMethod("GET");
//获取字节流
InputStream stream = new InputStream();
//设置文件名
String filename = String.valueOf(System.currentTimeMillis);
//声明读入路径
file enterpath = null;
//声明从外界读入流,从本地读取是FileInputStream
FileOutputStream fileOutputStream = null;
//获得外存储器的状态,只有Medio_Mouted(挂载且可读可写)
if(Environment.getExternalStorState().equals(Environment.MEDIO_MOUTED)){
    
    
  //获取外部存储器的目录路径
  File stor_path = Environment.getExternalStorDirection();
  //建立读入路径,两个参数,分别为外部目录,文件名
  enterpath = new File(stor_path,filename);
  //绑定读入路径的读入流
  fileOutputStream = new FileOutputStream(enterpath);
}
//设置一次性读入量
int lens=0;
//建立2M大小的缓冲区
byte bytes = new byte[2*1024];
//读入流不为空时,开始进入读取
if(fileOutputStream!=null){
    
    
   while((lens=stream.read(bytes)!=-1){
    
    //读入量不为空时
       fileOutputStream.write(bytes,0,lens);
   }
   //返回 下载文件的路径的全路径的文件
   return BitmapFactory.decodeFile(enterpath.getAbsolutePath);
}

  1. In the Activity.java file, create a new internal class and inherit the AsyncTask<Void,Void,Bitmap> class,
    override the doInBackground method, and override the onPostExecute method, as follows:
package com.ilikelxystill.fuxi;

import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class InternetPictureActivity extends AppCompatActivity {
    
    
    private ImageView imageview;
    private SendUrlTask sendUrlTask;
    private int i=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_internet_picture);
        init_all();
        clickpituremax();
    }
    public void init_all(){
    
    
        imageview = (ImageView)findViewById(R.id.imgview);
        sendUrlTask = new SendUrlTask("http://img4.sycdn.imooc.com/5c7f636b000193f509600960-140-140.jpg");
        sendUrlTask.execute();
    }

    //点击图片方大
    public void clickpituremax(){
    
    
        imageview.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                if (i==0){
    
    
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(300,
                            300);//两个400分别为添加图片的大小
                    imageview.setLayoutParams(params);
                    i=1;
                }else{
    
    
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                            ViewGroup.LayoutParams.WRAP_CONTENT);//两个400分别为添加图片的大小
                    imageview.setLayoutParams(params);
                    i=0;
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
    
    
        super.onDestroy();
        if (sendUrlTask!=null){
    
    
            sendUrlTask.cancel(true);
        }
    }

    private class SendUrlTask extends AsyncTask<Void,Void,Bitmap>{
    
    
        private String Url;

        public SendUrlTask(String c_url){
    
    
            Url = c_url;
        }

        @Override
        protected Bitmap doInBackground(Void... voids) {
    
    
            return httpurlPicture.loadPicture(Url);
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
    
    
            super.onPostExecute(bitmap);
            if(bitmap!=null) {
    
    
                imageview.setImageBitmap(bitmap);
            }
        }



    }
}

  1. xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".InternetPictureActivity">
    <ImageView
        android:id="@+id/imgview"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="250dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

After running, you can get the picture of the specified address. For Bitmap related knowledge, you need to learn more carefully. You will often encounter it in future development. At the same time, there are many excellent network open source frameworks that do not need to write native code. Learning is endless, come on.

Guess you like

Origin blog.csdn.net/qq_41904106/article/details/108330768