欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android离线缓存的实例代码

程序员文章站 2024-02-16 19:13:22
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();

} else {
  toast.maketext(getapplicationcontext(), "当前wu可用网络!", 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;
  }

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