我们用android手机打开一个app,会发现一个现象就是好多的app的首页是定期变化的(说白了其实就是服务器端的图片定期被更新了,android端需要定期检测并确定是否需要开启线程进行下载并保存起来),下面小编介绍一下自己是怎么搞的,大家互相学习交流!
1.本次用到了java中SoftReference,即对象的软引用。如果一个对象具有软引用,内存空间足够,垃圾回收器就不会回收它;如果内存空间不足了,就会回收这些对象的内存。只要垃圾回收器没有回收它,该对象就可以被程序使用。软引用可用来实现内存敏感的高 速缓存。使用软引用能防止内存泄露,增强程序的健壮性。
2.本次运用afinal_0.5_bin.jar向服务器发送或请求消息;
一堆代码来袭:
- package com.demo.mouse.welcome;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.os.Handler;
- import android.os.Message;
- import android.text.TextUtils;
- import android.util.Log;
- import android.widget.ImageView;
- <pre name="code" class="java">package com.demo.mouse.welcome;
- import android.content.SharedPreferences;
- import android.graphics.Bitmap;
- import android.support.v7.app.AppCompatActivity;
- import android.os.Bundle;
- import android.util.Log;
- import android.widget.ImageView;
- import android.widget.RelativeLayout;
- import net.tsz.afinal.FinalHttp;
- import net.tsz.afinal.http.AjaxCallBack;
- import org.json.JSONObject;
- import java.util.Timer;
- import java.util.TimerTask;
- /**
- * 启动页
- */
- public class MainActivity extends AppCompatActivity {
- private static String TAG="MainActivity";
- private RelativeLayout welcome;
- private ImageView welocome_image;
- private SharedPreferences sps;
- private AsyncBitmapLoader aBitmapLoader;
- public Timer timer = new Timer();
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- sps = getSharedPreferences(Contant.SP, MODE_PRIVATE);
- aBitmapLoader=new AsyncBitmapLoader();
- welcome = (RelativeLayout) findViewById(R.id.welcome);
- welocome_image = (ImageView) findViewById(R.id.welocome_image);
- FinalHttp http = new FinalHttp();
- http.get(Contant.QDYURL, new AjaxCallBack<String>() {
- @Override
- public void onFailure(Throwable t, int errorNo, String strMsg) {
- super.onFailure(t, errorNo, strMsg);
- Log.i("pig", 1 + errorNo+"----"+strMsg);
- initImage();
- }
- @Override
- public void onSuccess(String json) {
- super.onSuccess(json);
- Log.i("pig", 2 + "");
- try {
- JSONObject jsons = new JSONObject(json + "");
- Log.i(TAG,"jsons" + jsons);
- String res = jsons.optString("img_url");
- sps.edit().putString(Contant.SP, res).commit();
- Log.i("start image url is", res);
- Bitmap bitmap = aBitmapLoader.loadBitMap(
- welocome_image, res, new AsyncBitmapLoader.ImageCallBack() {
- @Override
- public void imageLoad(ImageView imageView,
- Bitmap bitmap) {
- // TODO Auto-generated method stub
- welocome_image.setImageBitmap(bitmap);
- }
- });
- if (bitmap == null) {
- welocome_image.setImageResource(R.mipmap.ic_launcher);
- } else {
- welocome_image.setImageBitmap(bitmap);
- }
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- });
- init();
- }
- private void initImage() {
- // TODO Auto-generated method stub
- Bitmap bitmap = aBitmapLoader.loadBitMap(welocome_image,
- sps.getString(Contant.SP, ""), new AsyncBitmapLoader.ImageCallBack() {
- @Override
- public void imageLoad(ImageView imageView, Bitmap bitmap) {
- // TODO Auto-generated method stub
- welocome_image.setImageBitmap(bitmap);
- }
- });
- if (bitmap == null) {
- welocome_image.setImageResource(R.mipmap.ic_launcher);
- } else {
- welocome_image.setImageBitmap(bitmap);
- }
- }
- /**
- * 启动页动画
- */
- private void init() {
- TimerTask task = new TimerTask() {
- @Override
- public void run() {
- SharedPreferences sp = getSharedPreferences(
- "mouse", MODE_PRIVATE);
- if (sp.getBoolean(Contant.ISFIRST, true)) {
- // 首次进入提示viewpager页
- //跳到引导页
- //........
- finish();
- } else {
- //跳到主页面
- //........
- finish();
- }
- }
- };
- timer.schedule(task, 3 * 1000 + 200);
- }
- }
- package com.demo.mouse.welcome;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.os.Handler;
- import android.os.Message;
- import android.text.TextUtils;
- import android.util.Log;
- import android.widget.ImageView;
- import org.apache.http.HttpResponse;
- import org.apache.http.client.ClientProtocolException;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.impl.client.DefaultHttpClient;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.lang.ref.SoftReference;
- import java.net.URI;
- import java.util.HashMap;
- public class AsyncBitmapLoader {
- private static String TAG="AsyncBitmapLoader";
- private HashMap<String, SoftReference<Bitmap>> imageCache = null;//用Map集合缓存软引用的Bitmap对象
- public AsyncBitmapLoader(){
- imageCache= new HashMap<>();
- }
- public Bitmap loadBitMap(final ImageView imageView, final String imageUrl, final ImageCallBack imageCallback){
- //如果在内存缓存中,则返回Bitmap对象
- if(imageCache.containsKey(imageUrl)){
- SoftReference<Bitmap>sr=imageCache.get(imageUrl);软引用的Bitmap对象
- Bitmap bitmap=sr.get();///取出Bitmap对象,如果由于内存不足Bitmap被回收,将取得空
- if (bitmap!=null){
- return bitmap;
- }
- }else {//本地缓存的查找
- String bitmapName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
- File file = new File(Contant.IMAGEURL);
- File[] cacheFiles = file.listFiles();
- if (cacheFiles != null) {
- int i = 0;
- for (; i < cacheFiles.length; i++) {
- //目前本地保存的图片与当前服务器端提供的图片相同时
- if (bitmapName.equals(cacheFiles[i].getName())) {
- break;//就直接退出这个for循环方法,就不需要更新
- }
- }
- if (i < cacheFiles.length) {//如果
- //根据本地图片位置url返回bitmap,不存在则返回空
- return BitmapFactory.decodeFile(Contant.IMAGEURL + bitmapName);
- }
- }
- }
- final Handler handler=new Handler(){
- @Override
- public void handleMessage(Message msg) {
- super.handleMessage(msg);
- imageCallback.imageLoad(imageView, (Bitmap) msg.obj);
- }
- };
- /**
- * 如果上面的软内存缓存和本地缓存都不存在,那么就要开启线程进行下载咯
- */
- new Thread(){
- @Override
- public void run() {
- super.run();
- InputStream is=getStreamFromURL(imageUrl);
- Bitmap bitmap = BitmapFactory.decodeStream(is);
- imageCache.put(imageUrl, new SoftReference<>(bitmap));
- Message msg = handler.obtainMessage(0, bitmap);
- handler.sendMessage(msg);//向Handler发送消息,让Handler进行处理任务
- File dir = new File(Contant.IMAGEURL);
- if(!dir.exists())
- {
- dir.mkdirs();
- }
- File bitmapFile = new File(Contant.IMAGEURL+ imageUrl.substring(imageUrl.lastIndexOf("/") + 1));
- if(!bitmapFile.exists())
- {
- try
- {
- bitmapFile.createNewFile();
- }
- catch (IOException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- FileOutputStream os;
- try
- {
- os = new FileOutputStream(bitmapFile);
- bitmap.compress(Bitmap.CompressFormat.PNG,
- 100, os);//100 meaning compress for max quality
- os.close();
- }
- catch (FileNotFoundException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- catch (IOException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }.start();
- return null;
- }
- public static InputStream getStreamFromURL(String imageURL){
- DefaultHttpClient client = new DefaultHttpClient();
- HttpGet get = new HttpGet();
- if(TextUtils.isEmpty(imageURL)){
- Log.i(TAG, "imageUrl访问的地址为空");
- return null;
- }
- get.setURI(URI.create(imageURL));
- try {
- HttpResponse response = client.execute(get);
- if (response.getStatusLine().getStatusCode() == 200) {
- InputStream inputStream = response.getEntity().getContent();
- return inputStream;
- }
- } catch (ClientProtocolException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
- public interface ImageCallBack
- {
- public void imageLoad(ImageView imageView, Bitmap bitmap);
- }
- }
- public interface Contant {
- static String IMAGEURL="/mouse/sdcard/test/";
- static String SP="sp";
- static String QDYURL="";//此处添加发送请求的URL
- static String ISFIRST="isFirst";
- }
注意添加
<uses-permission android:name="android.permission.INTERNET" />
http://download.csdn.net/detail/u010343650/9429546