Android离线缓存的实例代码
android做到一定程度,需要考虑缓存的问题,不信可以掏出手机看看淘宝等一些app是否无网的情况下还可以浏览,不过大部分app并没有考虑到这些问题,解决Android的缓存有哪些方法呢
1.IO流读写文件
2.数据库
3.LruCache和DiskLruCache
个人比较喜欢sd卡文件读写的方式,原因自己可以去分析。
(1)权限
<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permissionandroid:name="android.permission.INTERNET"></uses-permission> <uses-permissionandroid:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission> <!--在SDCard中创建与删除文件权限--> <uses-permissionandroid:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> <!--往SDCard写入数据权限--> <uses-permissionandroid: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(); } publicbooleanisNetworkAvailable(Activityactivity) { Contextcontext=activity.getApplicationContext(); //获取手机所有连接管理对象(包括对wi-fi,net等连接的管理) ConnectivityManagerconnectivityManager=(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); if(connectivityManager==null) { returnfalse; } else { //获取NetworkInfo对象 NetworkInfo[]networkInfo=connectivityManager.getAllNetworkInfo(); if(networkInfo!=null&&networkInfo.length>0) { for(inti=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) { returntrue; } } } } returnfalse; }
(3)端口写入数据
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ FilesdCardDir=Environment.getExternalStorageDirectory();//获取SDCard目录 FilesaveFile=newFile(sdCardDir,"itcast.txt"); FileOutputStreamoutStream=newFileOutputStream(saveFile); outStream.write(result.getBytes()); outStream.close(); }
(4)读取数据
FilesdCardDir=Environment.getExternalStorageDirectory();//获取SDCard目录 FilesaveFile1=newFile(sdCardDir,"itcast.txt"); BufferedReaderbr=null; try{ br=newBufferedReader(newFileReader(saveFile1)); Stringreadline=""; StringBuffersb=newStringBuffer(); while((readline=br.readLine())!=null){ System.out.println("readline:"+readline); sb.append(readline); } Stringstr=sb.toString();
(5)部分完整demo1
if(isNetworkAvailable(MainActivity.this)){ Toast.makeText(getApplicationContext(),"当前有可用网络!",Toast.LENGTH_LONG).show(); }else{ Toast.makeText(getApplicationContext(),"当前wu可用网络!",Toast.LENGTH_LONG).show(); FilesdCardDir=Environment.getExternalStorageDirectory();//获取SDCard目录 FilesaveFile1=newFile(sdCardDir,"itcast.txt"); BufferedReaderbr=null; try{ br=newBufferedReader(newFileReader(saveFile1)); Stringreadline=""; StringBuffersb=newStringBuffer(); while((readline=br.readLine())!=null){ System.out.println("readline:"+readline); sb.append(readline); } Stringstr=sb.toString(); JSONObjectjsonObject=newJSONObject(str); JSONArrayjsonArray=jsonObject.getJSONArray("data"); for(inti=0;i<jsonArray.length();i++){ JSONObjectobject=jsonArray.getJSONObject(i); Stringtitle=object.getString("name"); Stringcontent=object.getString("description"); Stringurl=object.getString("picSmall"); domainBeannewsInfo=newdomainBean(title,content,url); //Stringpath=Environment.getExternalStorageDirectory()+"/"+name; //ObjectOutputStreamout=newObjectOutputStream(newFileOutputStream(path)); //out.writeObject(newsInfo); list.add(newsInfo); //新建适配器 beanAdapter=newBeanAdapter(list,MainActivity.this); //配置适配器 xListView.setAdapter(beanAdapter); br.close(); } }catch(IOExceptione){ e.printStackTrace(); }catch(JSONExceptione){ e.printStackTrace(); } }
(6)部分完整demo2
publicStringlogoutPost(StringURL){ Stringresult=""; try{ Stringdata=URLEncoder.encode("UTF-8"); //+"&password="+URLEncoder.encode(password,"UTF-8");//传递的数据 URLurl=newURL(URL); //2、url.openConnection()打开网络链接 HttpURLConnectionconn=(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、获取输出流 OutputStreamos=conn.getOutputStream(); os.write(data.getBytes()); os.flush(); BufferedReaderin=newBufferedReader(newInputStreamReader(conn.getInputStream())); Stringline; while((line=in.readLine())!=null){result+="\n"+line;} if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ FilesdCardDir=Environment.getExternalStorageDirectory();//获取SDCard目录 FilesaveFile=newFile(sdCardDir,"itcast.txt"); FileOutputStreamoutStream=newFileOutputStream(saveFile); outStream.write(result.getBytes()); outStream.close(); } }catch(UnsupportedEncodingExceptione){ e.printStackTrace(); }catch(ProtocolExceptione){ e.printStackTrace(); }catch(MalformedURLExceptione){ e.printStackTrace(); }catch(IOExceptione){ e.printStackTrace(); } returnresult; }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。