1. 程式人生 > >Android-HttpClient-Get請求獲取網路圖片設定桌布

Android-HttpClient-Get請求獲取網路圖片設定桌布

第一種方式使用httpclient-*.jar (需要在網上去下載httpclient-*.jar包)

把httpclient-4.5.jar/httpclient-4.4.1.jar包放入到libs裡,然後點選sync project ...才能使用httpclient-4.5.jar包

httpclient-4.5.jar不好用,建議使用httpclient-4.4.1.jar

 

 

第二種方式:配置AndroidStudio 的方式獲取 HttpClient

在相應的module下的build.gradle中加入:useLibrary 'org.apache.http.legacy'

這條語句一定要加在 android{ } 當中,然後rebulid

例如:

 

 


 

 app/build.gradle android { useLibrary 'org.apache.http.legacy' }

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "liudeli.async"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    useLibrary 'org.apache.http.legacy'
} dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:28.0.0' implementation 'com.android.support.constraint:constraint-layout:1.1.3' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' }

 

在AndroidManifest.xml加入許可權:

  <!-- 訪問網路是危險的行為 所以需要許可權 -->
    <uses-permission android:name="android.permission.INTERNET" />

    <!-- 設定桌布是危險的行為 所以需要許可權 -->
    <uses-permission android:name="android.permission.SET_WALLPAPER" />

 

 MainActivity5:

package liudeli.async;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.HttpResponse;


import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;

public class MainActivity5 extends Activity {

    private final static String TAG = MainActivity5.class.getSimpleName();

    // 圖片地址
    private final String PATH = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000" +
            "&sec=1544714792699&di=3c2de372608ed6323f583f1c1b445e51&imgtype=0&src=http%3A%2F%2Fp" +
            "2.qhimgs4.com%2Ft0105d27180a686e91f.jpg";

    private ImageView imageView;
    private Button bt_set_wallpaper;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main4);

        imageView = findViewById(R.id.iv_image);
        bt_set_wallpaper = findViewById(R.id.bt_set_wallpaper);

        Button bt_get_image = findViewById(R.id.bt_get_image);
        bt_get_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 讓非同步任務執行耗時操作
                new DownloadImage().execute(PATH);
            }
        });

        bt_set_wallpaper.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != bitmap) {
                    try {
                        setWallpaper(bitmap);
                        Toast.makeText(MainActivity5.this, "桌布設定成功", Toast.LENGTH_LONG).show();
                    } catch (IOException e) {
                        e.printStackTrace();
                        Toast.makeText(MainActivity5.this, "桌布設定失敗", Toast.LENGTH_LONG).show();
                    }
                }
            }
        });
    }

    private Bitmap bitmap;

    class DownloadImage extends AsyncTask<String, Void, Object> {

        /**
         * 執行耗時操作前執行
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // 彈出進度條
            progressDialog = new ProgressDialog(MainActivity5.this);
            progressDialog.setMessage("Download ...");
            progressDialog.show();
        }

        /**
         * 執行耗時操作
         * @param strings
         * @return
         */
        @Override
        protected Object doInBackground(String... strings) {
            try {

                /**
                 * 第一步
                 * HttpClient是介面 不能直接例項化,需要通過HttpClient介面的子類 DefaultHttpClient來例項化
                 */
                HttpClient httpClient = new DefaultHttpClient();

                /**
                 * 第三步
                 * 例項化HttpGet物件,Get請求方式,應該說是請求物件
                 */
                HttpUriRequest getRequest = new HttpGet(PATH);

                /**
                 * 第二步
                 * 執行任務
                 */
                HttpResponse response = httpClient.execute(getRequest);

                /**
                 * 第四步
                 * 判斷請求碼 是否請求成功
                 */
                int responseCode = response.getStatusLine().getStatusCode();
                Log.d(TAG, "responseCode:" + responseCode);
                if (HttpURLConnection.HTTP_OK == responseCode) {
                    /**
                     * 第五步
                     * 獲取到服務區響應的位元組流資料 然後轉換成圖片Bitmap資料
                     */
                    InputStream inputStream = response.getEntity().getContent();
                    bitmap = BitmapFactory.decodeStream(inputStream);
                    return bitmap;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        /**
         * 耗時執行過程中 更新進度條刻度操作
         * @param values
         */
        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }

        /**
         * 耗時操作執行完成,用於更新UI
         * @param o
         */
        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);

            if (o != null) { // 成功
                bitmap = (Bitmap) o;

                // 故意放慢兩秒,模仿網路差的效果
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        // 設定從網上下載的圖片
                        imageView.setImageBitmap(bitmap);
                        // 設定為可以點選
                        bt_set_wallpaper.setEnabled(true);

                        // 關閉進度條
                        progressDialog.dismiss();
                    }
                }, 2000);
            } else { //失敗
                bt_set_wallpaper.setEnabled(false);
                Toast.makeText(MainActivity5.this, "下載失敗,請檢查原因", Toast.LENGTH_LONG).show();
                // 關閉進度條
                progressDialog.dismiss();
            }
        }
    }
}

 

activity_layout5.xml :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/bt_get_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="獲取圖片"
        android:onClick="getImage"
        android:layout_marginLeft="20dp"
        />

    <Button
        android:id="@+id/bt_set_wallpaper"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="設定桌布"
        android:layout_alignParentRight="true"
        android:layout_marginRight="20dp"
        android:enabled="false"
        />

    <ImageView
        android:id="@+id/iv_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/bt_get_image" />


</RelativeLayout>

 

操作結果: