Android離線緩存的實例代碼
android做到一定程度,需要考慮緩存的問題,不信可以掏出手機看看淘寶等一些app是否無網(wǎng)的情況下還可以瀏覽,不過大部分app并沒有考慮到這些問題,解決Android的緩存有哪些方法呢
1.IO流讀寫文件
2.數(shù)據(jù)庫
3.LruCache和DiskLruCache
個人比較喜歡sd卡文件讀寫的方式,原因自己可以去分析。
(1)權(quán)限
<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中創(chuàng)建與刪除文件權(quán)限 --> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> <!-- 往SDCard寫入數(shù)據(jù)權(quán)限 --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
(2)判斷網(wǎng)絡(luò)連接的狀態(tài),有什么用呢?自己想
if (isNetworkAvailable(MainActivity.this)) { Toast.makeText(getApplicationContext(), "當前有可用網(wǎng)絡(luò)!", Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), "當前wu可用網(wǎng)絡(luò)!", 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 + "===狀態(tài)===" + networkInfo[i].getState()); System.out.println(i + "===類型===" + networkInfo[i].getTypeName()); // 判斷當前網(wǎng)絡(luò)狀態(tài)是否為連接狀態(tài) if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) { return true; } } } } return false; }
(3)端口寫入數(shù)據(jù)
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)讀取數(shù)據(jù)
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(), "當前有可用網(wǎng)絡(luò)!", Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), "當前wu可用網(wǎng)絡(luò)!", 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");//傳遞的數(shù)據(jù) URL url = new URL(URL); //2、url.openConnection()打開網(wǎng)絡(luò)鏈接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //3、設(shè)置請求的方式 conn.setRequestMethod("POST"); conn.setDoInput(true);//發(fā)送POST請求必須設(shè)置允許輸出 conn.setDoOutput(true);//發(fā)送POST請求必須設(shè)置允許輸入 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; }
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
ComposeDesktop開發(fā)桌面端多功能APK工具
這篇文章主要為大家介紹了ComposeDesktop開發(fā)桌面端多功能APK工具實現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-07-07淺談Android中關(guān)于靜態(tài)變量(static)的使用問題
本文主要介紹了Android中關(guān)于靜態(tài)變量(static)的使用問題,具有一定的參考作用,下面跟著小編一起來看下吧2017-01-01Android中ListView如何分頁加載數(shù)據(jù)
這篇文章主要介紹了Android中ListView如何分頁加載數(shù)據(jù),本文就結(jié)合實例來演示一下使用ListView獲取數(shù)據(jù)的過程,需要的朋友可以參考下2015-12-12Android錄音--AudioRecord、MediaRecorder的使用
本篇文章主要介紹了Android錄音--AudioRecord、MediaRecorder的使用,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02