Handler进行网络连接获取数据

访问网络数据

访问网络要在线程中执行,写一个NetworkRunnable类

package com.example.hasee.handler;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by hasee on 2016/8/30.
 */
public class NetworkRunnable implements Runnable,Handler.Callback{
    private String url;
    private MyCallback callback;
    private Handler handler;
    public NetworkRunnable(String url, MyCallback callback) {
        this.url = url;
        this.callback = callback;
        handler = new Handler(Looper.getMainLooper(),this);
    }

    @Override
    public void run() {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setRequestMethod("GET");
            connection.setDoInput(true);
            int code = connection.getResponseCode();
            if (code == 200) {
                InputStream is = connection.getInputStream();
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                int length;
                byte[] buffer = new byte[102400];
                while ((length = is.read(buffer)) != -1) {
                    bos.write(buffer, 0, length);
                }
                String text = bos.toString("UTF-8");
                handler.obtainMessage(0, text).sendToTarget();
            } else {
                RuntimeException exception = new RuntimeException("ResponseCode" + code);
                String s = "服务器异常";
                Bundle bundle = new Bundle();
                bundle.putString("s", s);
                bundle.putSerializable("exception", exception);
                Message message = handler.obtainMessage(1);
                message.setData(bundle);
                handler.sendMessage(message);
            }
        } catch (Exception e) {
            String s = "服务器异常";
            Bundle bundle = new Bundle();
            bundle.putString("s", s);
            bundle.putSerializable("exception", e);
            Message message = handler.obtainMessage(1);
            message.setData(bundle);
            handler.sendMessage(message);
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case 0:
                callback.onSuccess((String)msg.obj);
                break;
            case 1:
                Bundle data = msg.getData();
               Exception exception = (Exception) data.getSerializable("exception");
                String s = data.getString("s");
                callback.onFail(exception,s);
                break;
        }
        return true;
    }

    public interface MyCallback {
        void onSuccess(String text);
        void onFail(Exception e,String s);
    }

}

在Activity中实现NetworkRunnable.MyCallback接口 执行

 textView = (TextView) findViewById(R.id.main2);
        NetworkRunnable runnable = new NetworkRunnable("http://www.baidu.com", this);
        new Thread(runnable).start();
 @Override
    public void onSuccess(String text) {
        textView.setText(text);
    }

    @Override
    public void onFail(Exception e, String s) {
        e.printStackTrace();
        Toast.makeText(Main2Activity.this, s, Toast.LENGTH_SHORT).show();
    }

获取网络图片

关键代码如下,其余代码参考上面
不获取百分比

 InputStream is = connection.getInputStream();
     Bitmap bitmap = BitmapFactory.decodeStream(is);//此方法不能获取百分比
     handler.obtainMessage(0, bitmap).sendToTarget();

获取百分比

  InputStream is = connection.getInputStream();
                int contentLength = connection.getContentLength();
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                int length;
                byte[] buffer = new byte[102400];
                while ((length = is.read(buffer)) != -1) {
                    bos.write(buffer, 0, length);
                    int size = bos.size();
                    handler.obtainMessage(2, size, contentLength).sendToTarget();
                }
                byte[] bytes = bos.toByteArray();
                Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

handlerMessage方法里执行

 case 2:
                float v = msg.arg1 * 100.0f / msg.arg2;
                callback.onProgress(v);
                break;

接口里方法

 public interface MyCallback {
        void onSuccess(Bitmap bitmap);
        void onFail(Exception e, String s);
        void onProgress(float percent);//获取百分比
    }

主Activity里

 @Override
    public void onSuccess(Bitmap bitmap) {
            imageView.setImageBitmap(bitmap);
    }

    @Override
    public void onFail(Exception e, String s) {
        e.printStackTrace();
        Toast.makeText(Main2Activity.this, s, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onProgress(float percent) {
        textView.setText(String.format(Locale.CHINA,"%.2f%%",percent));
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Lambda Query Wrapper 是一个方便的工具,用于在 AWS Lambda 中执行 DynamoDB 查询和扫描操作。以下是使用 Lambda Query Wrapper 获取数据的一些基本步骤: 1. 在 AWS Lambda 函数中安装 Lambda Query Wrapper 包。 2. 创建一个 DynamoDB 表,该表包含您要检索的数据。 3. 在 Lambda 函数中编写查询或扫描 DynamoDB 表的代码。 4. 使用 Lambda Query Wrapper 实例化 DynamoDB 查询或扫描操作。 5. 执行查询或扫描操作,并获取结果。 以下是一个使用 Lambda Query Wrapper 获取 DynamoDB 表中所有项目的示例代码: ```python import boto3 from lambda_query_wrapper import DynamoDBQueryWrapper def lambda_handler(event, context): dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('my-table') query_wrapper = DynamoDBQueryWrapper(table) # Execute a scan operation to retrieve all items in the table results = query_wrapper.scan() # Print out the results for item in results: print(item) ``` 在此示例中,我们使用 Lambda Query Wrapper 实例化了一个 DynamoDBQueryWrapper 对象,该对象连接到名为“my-table”的 DynamoDB 表。然后,我们执行了一个扫描操作,该操作检索了表中的所有项目,并将结果存储在结果变量中。最后,我们迭代结果并将每个项目打印到控制台中。 这只是使用 Lambda Query Wrapper 获取数据的一个示例。根据您的具体需求和查询操作,您可能需要使用 DynamoDBQueryWrapper 的其他方法。请查看 Lambda Query Wrapper 的文档以获取更多信息。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值