Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android離線緩存的實例代碼

Android離線緩存的實例代碼

編輯:關於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;
  }

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持本站。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved