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;
  }

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

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。