Android 定期动态更改启动页

来源:互联网 发布:网络直播申请备案 编辑:程序博客网 时间:2024/06/05 18:24

我们用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


原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 苹果8plus掉了怎么办 淘宝账户被限制使用怎么办 飞利浦电脑显示器黑屏怎么办打开 微信忘记密码手机号停用怎么办 淘宝账号登录密码忘记了怎么办 淘宝支付密码输错了怎么办 淘宝支付密码忘记了怎么办 淘宝货品上架后显示过期怎么办 被淘宝客监控了怎么办 助学贷款支付宝账号忘记怎么办 离婚支付宝的钱怎么办 扫码加载不出来怎么办 淘宝店铺被投诉售假怎么办 刚开的新店没人怎么办 淘宝访客量突然下降怎么办 支付宝账号封了怎么办 苹果x手机黑屏打不开怎么办 淘宝支付密码被锁定怎么办 淘宝支付密码锁定了怎么办 很抱歉手机淘宝停止运行怎么办 苹果手机桌面淘宝图标不见了怎么办 提示网页上有错误怎么办 淘宝定制家具违约两个月怎么办 同行在买家评价下面评论怎么办 淘宝知识产权侵权被投诉了怎么办 闲鱼买家说是假货退货怎么办 日验证失败次数上限怎么办 淘宝卖家发货不全怎么办 子账号登录不上怎么办 淘宝宝贝曝光量少怎么办 淘宝买东西退款卖家拒绝怎么办 华为手机淘宝不能收藏宝贝怎么办 包裹发出不想要了怎么办 淘宝改登录密码忘记了怎么办 三星s8应用闪退怎么办 淘宝购物商家不发货怎么办 淘宝商家迟迟不发货怎么办 买家地址写错了怎么办 买家写错快递地址怎么办 淘宝退款选择服务类型出不来怎么办 网购东西发错了怎么办