(转)android定期动态更新启动页

来源:互联网 发布:国家统计局统计局数据 编辑:程序博客网 时间:2024/06/05 12:00

原地址:http://blog.csdn.net/u010343650/article/details/50647502


我们用android手机打开一个app,会发现一个现象就是好多的app的首页是定期变化的(说白了其实就是服务器端的图片定期被更新了,android端需要定期检测并确定是否需要开启线程进行下载并保存起来),下面小编介绍一下自己是怎么搞的,大家互相学习交流!

1.本次用到了java中SoftReference,即对象的软引用。如果一个对象具有软引用,内存空间足够,垃圾回收器就不会回收它;如果内存空间不足了,就会回收这些对象的内存。只要垃圾回收器没有回收它,该对象就可以被程序使用。软引用可用来实现内存敏感的高 速缓存。使用软引用能防止内存泄露,增强程序的健壮性。  

2.本次运用afinal_0.5_bin.jar向服务器发送或请求消息;

一堆代码来袭:

[java] view plain copy
 print?
  1. package com.demo.mouse.welcome;  
  2.   
  3. import android.graphics.Bitmap;  
  4. import android.graphics.BitmapFactory;  
  5. import android.os.Handler;  
  6. import android.os.Message;  
  7. import android.text.TextUtils;  
  8. import android.util.Log;  
  9. import android.widget.ImageView;  
  10. <pre name="code" class="java">package com.demo.mouse.welcome;  
  11.   
  12. import android.content.SharedPreferences;  
  13. import android.graphics.Bitmap;  
  14. import android.support.v7.app.AppCompatActivity;  
  15. import android.os.Bundle;  
  16. import android.util.Log;  
  17. import android.widget.ImageView;  
  18. import android.widget.RelativeLayout;  
  19.   
  20. import net.tsz.afinal.FinalHttp;  
  21. import net.tsz.afinal.http.AjaxCallBack;  
  22.   
  23. import org.json.JSONObject;  
  24.   
  25. import java.util.Timer;  
  26. import java.util.TimerTask;  
  27.   
  28. /** 
  29.  * 启动页 
  30.  */  
  31. public class MainActivity extends AppCompatActivity {  
  32.     private static String TAG="MainActivity";  
  33.     private  RelativeLayout welcome;  
  34.     private ImageView welocome_image;  
  35.     private SharedPreferences sps;  
  36.     private AsyncBitmapLoader aBitmapLoader;  
  37.     public Timer timer = new Timer();  
  38.   
  39.     @Override  
  40.     protected void onCreate(Bundle savedInstanceState) {  
  41.         super.onCreate(savedInstanceState);  
  42.         setContentView(R.layout.activity_main);  
  43.         sps = getSharedPreferences(Contant.SP, MODE_PRIVATE);  
  44.         aBitmapLoader=new AsyncBitmapLoader();  
  45.         welcome = (RelativeLayout) findViewById(R.id.welcome);  
  46.         welocome_image = (ImageView) findViewById(R.id.welocome_image);  
  47.         FinalHttp http = new FinalHttp();  
  48.         http.get(Contant.QDYURL, new AjaxCallBack<String>() {  
  49.             @Override  
  50.             public void onFailure(Throwable t, int errorNo, String strMsg) {  
  51.                 super.onFailure(t, errorNo, strMsg);  
  52.                 Log.i("pig"1 + errorNo+"----"+strMsg);  
  53.                 initImage();  
  54.             }  
  55.   
  56.             @Override  
  57.             public void onSuccess(String json) {  
  58.                 super.onSuccess(json);  
  59.                 Log.i("pig"2 + "");  
  60.                 try {  
  61.                     JSONObject jsons = new JSONObject(json + "");  
  62.                     Log.i(TAG,"jsons" + jsons);  
  63.                     String res = jsons.optString("img_url");  
  64.                     sps.edit().putString(Contant.SP, res).commit();  
  65.                     Log.i("start image url is",  res);  
  66.                     Bitmap bitmap = aBitmapLoader.loadBitMap(  
  67.                             welocome_image, res, new AsyncBitmapLoader.ImageCallBack() {  
  68.   
  69.                                 @Override  
  70.                                 public void imageLoad(ImageView imageView,  
  71.                                                       Bitmap bitmap) {  
  72.                                     // TODO Auto-generated method stub  
  73.                                     welocome_image.setImageBitmap(bitmap);  
  74.                                 }  
  75.                             });  
  76.                     if (bitmap == null) {  
  77.                         welocome_image.setImageResource(R.mipmap.ic_launcher);  
  78.                     } else {  
  79.                         welocome_image.setImageBitmap(bitmap);  
  80.                     }  
  81.                 } catch (Exception e) {  
  82.                     // TODO Auto-generated catch block  
  83.                     e.printStackTrace();  
  84.                 }  
  85.   
  86.             }  
  87.   
  88.         });  
  89.         init();  
  90.     }  
  91.   
  92.   
  93.     private void initImage() {  
  94.         // TODO Auto-generated method stub  
  95.         Bitmap bitmap = aBitmapLoader.loadBitMap(welocome_image,  
  96.                 sps.getString(Contant.SP, ""), new AsyncBitmapLoader.ImageCallBack() {  
  97.   
  98.                     @Override  
  99.                     public void imageLoad(ImageView imageView, Bitmap bitmap) {  
  100.                         // TODO Auto-generated method stub  
  101.                         welocome_image.setImageBitmap(bitmap);  
  102.                     }  
  103.                 });  
  104.         if (bitmap == null) {  
  105.             welocome_image.setImageResource(R.mipmap.ic_launcher);  
  106.         } else {  
  107.             welocome_image.setImageBitmap(bitmap);  
  108.         }  
  109.     }  
  110.   
  111.     /** 
  112.      * 启动页动画 
  113.      */  
  114.     private void init() {  
  115.         TimerTask task = new TimerTask() {  
  116.             @Override  
  117.             public void run() {  
  118.                 SharedPreferences sp = getSharedPreferences(  
  119.                         "mouse", MODE_PRIVATE);  
  120.                 if (sp.getBoolean(Contant.ISFIRST, true)) {  
  121.                     // 首次进入提示viewpager页  
  122.                    //跳到引导页  
  123.                     //........  
  124.                     finish();  
  125.                 } else {  
  126.                     //跳到主页面  
  127.                     //........  
  128.                     finish();  
  129.                 }  
  130.             }  
  131.         };  
  132.         timer.schedule(task, 3 * 1000 + 200);  
  133.     }  
  134.   
  135. }  

[java] view plain copy
 print?
  1. package com.demo.mouse.welcome;  
  2.   
  3. import android.graphics.Bitmap;  
  4. import android.graphics.BitmapFactory;  
  5. import android.os.Handler;  
  6. import android.os.Message;  
  7. import android.text.TextUtils;  
  8. import android.util.Log;  
  9. import android.widget.ImageView;  
  10.   
  11. import org.apache.http.HttpResponse;  
  12. import org.apache.http.client.ClientProtocolException;  
  13. import org.apache.http.client.methods.HttpGet;  
  14. import org.apache.http.impl.client.DefaultHttpClient;  
  15. import java.io.File;  
  16. import java.io.FileNotFoundException;  
  17. import java.io.FileOutputStream;  
  18. import java.io.IOException;  
  19. import java.io.InputStream;  
  20. import java.lang.ref.SoftReference;  
  21. import java.net.URI;  
  22. import java.util.HashMap;  
  23.   
  24. public class AsyncBitmapLoader {  
  25.     private static String TAG="AsyncBitmapLoader";  
  26.     private HashMap<String, SoftReference<Bitmap>> imageCache = null;//用Map集合缓存软引用的Bitmap对象  
  27.     public AsyncBitmapLoader(){  
  28.         imageCache= new HashMap<>();  
  29.     }  
  30.     public  Bitmap loadBitMap(final ImageView imageView, final String imageUrl, final ImageCallBack imageCallback){  
  31.         //如果在内存缓存中,则返回Bitmap对象  
  32.         if(imageCache.containsKey(imageUrl)){  
  33.             SoftReference<Bitmap>sr=imageCache.get(imageUrl);////软引用的Bitmap对象  
  34.             Bitmap bitmap=sr.get();///取出Bitmap对象,如果由于内存不足Bitmap被回收,将取得空  
  35.             if (bitmap!=null){  
  36.                 return bitmap;  
  37.             }  
  38.         }else {//本地缓存的查找  
  39.             String bitmapName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);  
  40.             File file = new File(Contant.IMAGEURL);  
  41.             File[] cacheFiles = file.listFiles();  
  42.             if (cacheFiles != null) {  
  43.                 int i = 0;  
  44.                 for (; i < cacheFiles.length; i++) {  
  45.                     //目前本地保存的图片与当前服务器端提供的图片相同时  
  46.                     if (bitmapName.equals(cacheFiles[i].getName())) {  
  47.                         break;//就直接退出这个for循环方法,就不需要更新  
  48.                     }  
  49.                 }  
  50.                 if (i < cacheFiles.length) {//如果  
  51.                     //根据本地图片位置url返回bitmap,不存在则返回空  
  52.                    return BitmapFactory.decodeFile(Contant.IMAGEURL + bitmapName);  
  53.                 }  
  54.             }  
  55.         }  
  56.   
  57.         final Handler handler=new Handler(){  
  58.   
  59.             @Override  
  60.             public void handleMessage(Message msg) {  
  61.                 super.handleMessage(msg);  
  62.                 imageCallback.imageLoad(imageView, (Bitmap) msg.obj);  
  63.             }  
  64.         };  
  65. /** 
  66.  * 如果上面的软内存缓存和本地缓存都不存在,那么就要开启线程进行下载咯 
  67.  */  
  68.         new  Thread(){  
  69.             @Override  
  70.             public void run() {  
  71.                 super.run();  
  72.                 InputStream is=getStreamFromURL(imageUrl);  
  73.                 Bitmap bitmap = BitmapFactory.decodeStream(is);  
  74.                 imageCache.put(imageUrl, new SoftReference<>(bitmap));  
  75.                 Message msg = handler.obtainMessage(0, bitmap);  
  76.                 handler.sendMessage(msg);//向Handler发送消息,让Handler进行处理任务  
  77.                 File dir = new File(Contant.IMAGEURL);  
  78.                 if(!dir.exists())  
  79.                 {  
  80.                     dir.mkdirs();  
  81.                 }  
  82.                 File bitmapFile = new File(Contant.IMAGEURL+ imageUrl.substring(imageUrl.lastIndexOf("/") + 1));  
  83.                 if(!bitmapFile.exists())  
  84.                 {  
  85.                     try  
  86.                     {  
  87.                         bitmapFile.createNewFile();  
  88.                     }  
  89.                     catch (IOException e)  
  90.                     {  
  91.                         // TODO Auto-generated catch block  
  92.                         e.printStackTrace();  
  93.                     }  
  94.                 }  
  95.                 FileOutputStream os;  
  96.                 try  
  97.                 {  
  98.                     os = new FileOutputStream(bitmapFile);  
  99.                     bitmap.compress(Bitmap.CompressFormat.PNG,  
  100.                             100, os);//100 meaning compress for max quality  
  101.                     os.close();  
  102.                 }  
  103.                 catch (FileNotFoundException e)  
  104.                 {  
  105.                     // TODO Auto-generated catch block  
  106.                     e.printStackTrace();  
  107.                 }  
  108.                 catch (IOException e)  
  109.                 {  
  110.                     // TODO Auto-generated catch block  
  111.                     e.printStackTrace();  
  112.                 }  
  113.             }  
  114.         }.start();  
  115.         return null;  
  116.     }  
  117.   
  118.     public static InputStream getStreamFromURL(String imageURL){  
  119.         DefaultHttpClient client = new DefaultHttpClient();  
  120.         HttpGet get = new HttpGet();  
  121.   
  122.         if(TextUtils.isEmpty(imageURL)){  
  123.             Log.i(TAG, "imageUrl访问的地址为空");  
  124.             return null;  
  125.         }  
  126.         get.setURI(URI.create(imageURL));  
  127.   
  128.         try {  
  129.             HttpResponse response = client.execute(get);  
  130.             if (response.getStatusLine().getStatusCode() == 200) {  
  131.                 InputStream inputStream = response.getEntity().getContent();  
  132.                 return inputStream;  
  133.             }  
  134.         } catch (ClientProtocolException e) {  
  135.             e.printStackTrace();  
  136.         } catch (IOException e) {  
  137.             e.printStackTrace();  
  138.         }  
  139.         return null;  
  140.     }  
  141.   
  142.     public interface ImageCallBack  
  143.     {  
  144.         public void imageLoad(ImageView imageView, Bitmap bitmap);  
  145.     }  
  146.   
  147.   
  148. }  

[java] view plain copy
 print?
  1. public interface Contant {  
  2.     static  String IMAGEURL="/mouse/sdcard/test/";  
  3.     static String SP="sp";  
  4.     static String QDYURL="";//此处添加发送请求的URL  
  5.     static String  ISFIRST="isFirst";  
  6. }  

注意添加
<uses-permission android:name="android.permission.INTERNET" />

http://download.csdn.net/detail/u010343650/9429546