Android离线缓存的实例代码

Android离线缓存的实例代码,第1张

概述android做到一定程度,需要考虑缓存的问题,不信可以掏出手机看看淘宝等一些app是否无网的情况下还可以浏览,不过大部分app并没有考虑到这些问题,解决Android的缓存有哪些方法呢

androID做到一定程度,需要考虑缓存的问题,不信可以掏出手机看看淘宝等一些app是否无网的情况下还可以浏览,不过大部分app并没有考虑到这些问题,解决AndroID的缓存有哪些方法呢

1.IO流读写文件

2.数据库

3.LruCache和diskLruCache

个人比较喜欢sd卡文件读写的方式,原因自己可以去分析。

(1)权限

<uses-permission androID:name="androID.permission.WRITE_EXTERNAL_STORAGE" /><uses-permission androID:name="androID.permission.INTERNET"></uses-permission><uses-permission androID:name="androID.permission.ACCESS_NETWORK_STATE"></uses-permission><!-- 在SDCard中创建与删除文件权限 --><uses-permission androID:name="androID.permission.MOUNT_UNMOUNT_fileSYstemS"/><!-- 往SDCard写入数据权限 --><uses-permission androID:name="androID.permission.WRITE_EXTERNAL_STORAGE"/>

(2)判断网络连接的状态,有什么用呢?自己想

if (isNetworkAvailable(MainActivity.this)) {  Toast.makeText(getApplicationContext(),"当前有可用网络!",Toast.LENGTH_LONG).show();} else {  Toast.makeText(getApplicationContext(),"当前wu可用网络!",Toast.LENGTH_LONG).show();}public boolean isNetworkAvailable(Activity activity){  Context context = activity.getApplicationContext();  // 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)  ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);  if (connectivityManager == null)  {    return false;  }  else  {    // 获取NetworkInfo对象    NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();    if (networkInfo != null && networkInfo.length > 0)    {      for (int i = 0; i < networkInfo.length; i++)      {        System.out.println(i + "===状态===" + networkInfo[i].getState());        System.out.println(i + "===类型===" + networkInfo[i].getTypename());        // 判断当前网络状态是否为连接状态        if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED)        {          return true;        }      }    }  }  return false;}

(3)端口写入数据
 

  if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){  file sdCardDir = Environment.getExternalStorageDirectory();//获取SDCard目录  file savefile = new file(sdCardDir,"itcast.txt");  fileOutputStream outStream = new fileOutputStream(savefile);  outStream.write(result.getBytes());  outStream.close();}

(4)读取数据

file sdCardDir = Environment.getExternalStorageDirectory();//获取SDCard目录file savefile1  = new file(sdCardDir,"itcast.txt");BufferedReader br = null;try {  br = new BufferedReader(new fileReader(savefile1));  String readline = "";  StringBuffer sb = new StringBuffer();  while ((readline = br.readline()) != null) {    System.out.println("readline:" + readline);    sb.append(readline);  }  String str = sb.toString();

(5)部分完整demo1

if (isNetworkAvailable(MainActivity.this)) {  Toast.makeText(getApplicationContext(),Toast.LENGTH_LONG).show();  file sdCardDir = Environment.getExternalStorageDirectory();//获取SDCard目录  file savefile1  = new file(sdCardDir,"itcast.txt");  BufferedReader br = null;  try {    br = new BufferedReader(new fileReader(savefile1));    String readline = "";    StringBuffer sb = new StringBuffer();    while ((readline = br.readline()) != null) {      System.out.println("readline:" + readline);      sb.append(readline);    }    String str = sb.toString();    JsONObject JsonObject = new JsONObject(str);    JsONArray JsonArray = JsonObject.getJsONArray("data");    for (int i = 0; i < JsonArray.length(); i++) {      JsONObject object = JsonArray.getJsONObject(i);      String Title = object.getString("name");      String content = object.getString("description");      String url = object.getString("picSmall");      domainBean newsInfo = new domainBean(Title,content,url);      //String path = Environment.getExternalStorageDirectory() + "/" + name;      //ObjectOutputStream out =new ObjectOutputStream(new fileOutputStream(path));      //out.writeObject(newsInfo);      List.add(newsInfo);      //新建适配器      beanAdapter = new BeanAdapter(List,MainActivity.this);      //配置适配器      xListVIEw.setAdapter(beanAdapter);      br.close();    }  } catch (IOException e) {    e.printstacktrace();  } catch (JsONException e) {    e.printstacktrace();  }}

(6)部分完整demo2

 public String logoutPost(String URL){    String result = "";    try {      String data = URLEncoder.encode("UTF-8");// + "&password=" + URLEncoder.encode(password,"UTF-8");//传递的数据      URL url = new URL(URL);//2、url.openConnection()打开网络链接      httpURLConnection conn = (httpURLConnection) url.openConnection();//3、设置请求的方式      conn.setRequestMethod("POST");      conn.setDoinput(true);//发送POST请求必须设置允许输出      conn.setDoOutput(true);//发送POST请求必须设置允许输入      conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");      conn.setRequestProperty("Charset","utf-8");      conn.setRequestProperty("Content-Length",String.valueOf(data.getBytes().length));//5、获取输出流      OutputStream os = conn.getoutputStream();      os.write(data.getBytes());      os.flush();      BufferedReader in=new BufferedReader(new inputStreamReader(conn.getinputStream()));      String line;      while((line=in.readline())!=null){result+="\n"+line;}            if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){        file sdCardDir = Environment.getExternalStorageDirectory();//获取SDCard目录        file savefile = new file(sdCardDir,"itcast.txt");        fileOutputStream outStream = new fileOutputStream(savefile);        outStream.write(result.getBytes());        outStream.close();      }    } catch (UnsupportedEnCodingException e) {      e.printstacktrace();    } catch (ProtocolException e) {      e.printstacktrace();    } catch (MalformedURLException e) {      e.printstacktrace();    } catch (IOException e) {      e.printstacktrace();    }    return result;  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

总结

以上是内存溢出为你收集整理的Android离线缓存的实例代码全部内容,希望文章能够帮你解决Android离线缓存的实例代码所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1147232.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存