安卓单线程演示--从网下下载一张图片

uiHandler 简单演示

package com.zhy.thread_baidu;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    //创建消息码
    private static final int MESSAGE_GetGame_OK = 1;
    private static final int MESSAGE_GetGame_ERROR = 2;

    private Button m_btn;
    private ImageView m_imageView;
    private String m_imageUrl = "";

    //创建一个uiHandler
    private Handler uiHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MESSAGE_GetGame_OK: {
                    System.out.println("UI thread get Message from sub thread,ok");
                    Bitmap bm = (Bitmap) msg.obj;
                    displayImage(bm);
                    break;
                }
                case MESSAGE_GetGame_ERROR: {
                    System.out.println("UI thread get message from sub thread,error");
                    break;
                }
                default:
                    break;
            }//switch (msg.what)
        }//public void handleMessage

    }; //private Handler uiHandler = new Handler()

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.handlerBtn) {
            m_imageUrl = getImageUrlFromUI();
            // 创建子线程
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        //下载图片
                        Bitmap bmBitmap = downloadImage(m_imageUrl);

                        //创建消息
                        Message msg = Message.obtain();
                        msg.what = MESSAGE_GetGame_OK;
                        msg.obj = bmBitmap;

                        //发送消息
                        uiHandler.sendMessage(msg);
                    } catch (IOException e) {
                        e.printStackTrace();
                        //创建消息
                        Message msg = Message.obtain();
                        msg.what = MESSAGE_GetGame_ERROR;

                        uiHandler.sendMessage(msg);
                    }
                }
            });
            thread.start();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        m_btn = (Button) findViewById(R.id.handlerBtn);
        m_imageView = (ImageView) findViewById(R.id.handlerImageView);

        m_btn.setOnClickListener(this);
    }

    private Bitmap downloadImage(String urlString) throws IOException {
        if (urlString.equals("")) {
            System.out.println("Url is empty.");
            return null;
        }
        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();
        return BitmapFactory.decodeStream(conn.getInputStream());
    }

    public void displayImage(Bitmap bm) {
        m_imageView.setImageBitmap(bm);
    }

    private String getImageUrlFromUI() {//预配URL
        return "https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1591682139&di=de4ebaf40b6319d647501aceda38b4cd&src=http://n.sinaimg.cn/sinacn/w690h460/20180226/8a57-fyrwsqi4293849.jpg";
    }
}

修改AndroidManifest.xml

//添加权限
<uses-permission android:name="android.permission.INTERNT"/>

activity.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=".MainActivity">
    
    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="点击确定,获得图片"
        android:textSize="26dp"
        android:layout_marginTop="30dp"
        android:gravity="center"

        />

    <ImageView
        android:id="@+id/handlerImageView"
        android:layout_width="match_parent"
        android:layout_height="311dp"
        android:layout_marginTop="50dp"
        app:srcCompat="@drawable/ic_launcher_background" />

    <Button
        android:id="@+id/handlerBtn"
        android:layout_width="195dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="100dp"
        android:layout_marginTop="50dp"
        android:layout_marginRight="30dp"
        android:text="Button" />
</LinearLayout>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值