一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Android离线缓存的实例代码

时间:2017-01-24 编辑:简简单单 来源:一聚教程网

android做到一定程度,需要考虑缓存的问题,不信可以掏出手机看看淘宝等一些app是否无网的情况下还可以浏览,不过大部分app并没有考虑到这些问题,解决Android的缓存有哪些方法呢

1.IO流读写文件

2.数据库

3.LruCache和DiskLruCache

个人比较喜欢sd卡文件读写的方式,原因自己可以去分析。

(1)权限

 

 代码如下 复制代码

 

(2)判断网络连接的状态,有什么用呢?自己想

 

 代码如下 复制代码

if(isNetworkAvailable(MainActivity.this)) {

  Toast.makeText(getApplicationContext(),"当前有可用网络!", Toast.LENGTH_LONG).show();

 

}else{

  Toast.makeText(getApplicationContext(),"当前wu可用网络!", Toast.LENGTH_LONG).show();

}

publicbooleanisNetworkAvailable(Activity activity)

{

  Context context = activity.getApplicationContext();

  // 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)

  ConnectivityManager connectivityManager = (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)){

  File sdCardDir = Environment.getExternalStorageDirectory();//获取SDCard目录

  File saveFile =newFile(sdCardDir,"itcast.txt");

  FileOutputStream outStream =newFileOutputStream(saveFile);

  outStream.write(result.getBytes());

  outStream.close();

}

 

(4)读取数据

 

 代码如下 复制代码

File sdCardDir = Environment.getExternalStorageDirectory();//获取SDCard目录

File saveFile1  =newFile(sdCardDir,"itcast.txt");

BufferedReader br =null;

try{

  br =newBufferedReader(newFileReader(saveFile1));

  String readline ="";

  StringBuffer sb =newStringBuffer();

  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  =newFile(sdCardDir,"itcast.txt");

  BufferedReader br =null;

  try{

    br =newBufferedReader(newFileReader(saveFile1));

    String readline ="";

    StringBuffer sb =newStringBuffer();

    while((readline = br.readLine()) !=null) {

      System.out.println("readline:"+ readline);

      sb.append(readline);

    }

    String str = sb.toString();

    JSONObject jsonObject =newJSONObject(str);

    JSONArray jsonArray = jsonObject.getJSONArray("data");

    for(inti =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 =newdomainBean(title, content, url);

 

      //String path = Environment.getExternalStorageDirectory() + "/" + name;

      //ObjectOutputStream out =new ObjectOutputStream(new FileOutputStream(path));

      //out.writeObject(newsInfo);

      list.add(newsInfo);

      //新建适配器

      beanAdapter =newBeanAdapter(list, MainActivity.this);

      //配置适配器

      xListView.setAdapter(beanAdapter);

      br.close();

 

    }

 

  }catch(IOException e) {

    e.printStackTrace();

  }catch(JSONException e) {

    e.printStackTrace();

  }

}

 

(6)部分完整demo2

 

 代码如下 复制代码

publicString logoutPost(String URL){

    String result ="";

    try{

      String data = URLEncoder.encode("UTF-8");

// + "&password=" + URLEncoder.encode(password, "UTF-8");//传递的数据

      URL url =newURL(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=newBufferedReader(newInputStreamReader(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 =newFile(sdCardDir,"itcast.txt");

        FileOutputStream outStream =newFileOutputStream(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();

    }

 

    returnresult;

  }

 

热门栏目