Volley网络请求框架如何在Android 应用中使用

发布时间:2020-12-08 16:26:08 作者:Leah
来源:亿速云 阅读:128

Volley网络请求框架如何在Android 应用中使用?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

首先第一步

用到的RequetQueue

RequestQueue.Java

  RequestQueue请求队列首先得先说一下,ReuqestQueue是如何对请求进行管理的...RequestQueue是对所有的请求进行保存...然后通过自身的start()方法开启一个CacheDispatcher线程用于缓存调度,开启若干个NetWorkDispatcher线程用于网络调度...那么为什么要这样设计呢?

  因为一个请求如果已经提交了一次,那么就只需要处理这一次结果就可以了,对于多次重复的请求,我们完全可以使用一个缓存来进行保存..从而减少一些不必要的网络请求,减小服务器的负担...如果一个请求在缓存中没存在过,那么我们再执行网络请求就可以了

  总而言之,设计理念就是从RequestQueue取出请求,先判断缓存是否命中,如果缓存命中,则从缓存中取出数据,如果缓存没有命中,则提交网络请求,从服务器端获取数据

导入volley.jar 到您的Project libs里面,然后Add to Build path

然后创建NetCacheActivity类

package com.Android.xiong.gridlayoutTest;


import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;


import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;


public class NetCacheActivity extends Activity {
private static final String URL = "http://sina.com";//请求的url
private RequestQueue mRequestQueue;
private Button btn_request;
private ImageView iv_request;


@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initView();
 mRequestQueue = Volley.newRequestQueue(getApplicationContext());  
}


private void initView() {
// TODO Auto-generated method stub
btn_request = (Button) findViewById(R.id.btn_request);
iv_request=(ImageView) findViewById(R.id.iv_request);
}


public void onClick(View v) {
//volleyRequest();从网络上获取图片
imageRequest();
LoadImageView();//ImageLoader加载图片

}
private void imageRequest() {
// TODO Auto-generated method stub
 ImageRequest mImageRequest=new ImageRequest("http://www.bz55.com/uploads/allimg/130716/1-130G6111637.jpg", new Response.Listener<Bitmap>() {
            //需要的注意的是导入Response.Listener<Bitmap>别导错包!

@Override
public void onResponse(Bitmap response) {
// 将网络请求的图片返回并显示在ImageView中
  try {
Thread.sleep(3000);//休眠3秒 
iv_request.setImageBitmap(response);
Toast.makeText(getApplicationContext(), " onResponse", Toast.LENGTH_SHORT).show();
Log.d(" onResponse", response.toString());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
},0, 0, Config.RGB_565, new Response.ErrorListener() {


@Override
public void onErrorResponse(VolleyError error) {
// 默认加载图片资源
iv_request.setImageResource(R.drawable.ic_launcher);
Toast.makeText(getApplicationContext(), " onErrorResponse", Toast.LENGTH_SHORT).show();
Log.d(" onErrorResponse", error.toString());
}
});
 mRequestQueue.add(mImageRequest);//强图片请求添加到请求队列

}
public void LoadImageView() {
// 利用ImageLoader异步加载图片
final ImageLoader mImageLoader = new ImageLoader(mquest,
new BitmapCache());
ImageListener listener = ImageLoader.getImageListener(iv_request,
R.drawable.voice_to_short, R.drawable.ic_launcher);
        //get请求方式
mImageLoader
.get("http://img.my.csdn.NET/uploads/201404/13/1397393290_5765.jpeg",
listener);
Log.d("ImageLoader", mImageLoader.toString());
}

// import com.android.volley.Response.ErrorListener;
private void volleyRequest() {
StringRequest mRequest = new StringRequest(Method.GET, URL,
new Response.Listener<String>() {


@Override
public void onResponse(String response) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "onResponse ",
Toast.LENGTH_LONG).show();
Log.d("on onResponse", response.toString());//请求成功
}
}, new Response.ErrorListener() {


@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"onErrorResponse", Toast.LENGTH_SHORT).show();
Log.d("on ErrorReponse", error.toString());//请求失败
}
});
     mRequestQueue.add(mRequest);
     }
}

BitmapCache

package com.weixin.cache;


import android.graphics.Bitmap;
import android.support.v4.util.LruCache;


import com.android.volley.toolbox.ImageLoader.ImageCache;


public class BitmapCache implements ImageCache { 
 
  private LruCache<String, Bitmap> cache; 
 
  public BitmapCache() { 
    cache = new LruCache<String, Bitmap>(8 * 1024 * 1024) { 
      @Override 
      protected int sizeOf(String key, Bitmap bitmap) { 
        return bitmap.getRowBytes() * bitmap.getHeight(); 
      } 
    }; 
  } 
 
  @Override 
  public Bitmap getBitmap(String url) { 
    return cache.get(url); 
  } 
 
  @Override 
  public void putBitmap(String url, Bitmap bitmap) { 
    cache.put(url, bitmap); 
  } 
} 

布局文件activity_main.xml

<&#63;xml version="1.0" encoding="utf-8"&#63;>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/RelativeLayout1"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical" >

  <ImageView
    android:id="@+id/iv_request"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scaleType="fitXY"
    android:src="@drawable/bitmap" />


  <Button
    android:id="@+id/btn_request"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:onClick="onClick"
    android:text="获取网络请求信息" />


</RelativeLayout>

看完上述内容,你们掌握Volley网络请求框架如何在Android 应用中使用的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

推荐阅读:
  1. android Volley 使用
  2. 基于Google Volley的Android Http连接库

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

android volley roi

上一篇:java中守护线程与非守护线程的区别有什么

下一篇:利用java怎么对oracle或mysql数据库进行连接

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》