java - 在 Android 中本地缓存等待互联网连接的数据

标签 java android caching androidhttpclient

我正在开发一个需要将数据(JSON 字符串)发布到网络服务器的应用程序。我正在使用 Apache HTTP 客户端(下面的附加代码)执行此操作。当有互联网连接时,一切正常,但如果没有互联网连接,项目规范需要我在本地缓存数据,并等到我连接到服务器。

这是我的问题: 1. 什么是在本地缓存 JSON 字符串并在我连接到互联网时发送它们的最佳方式。我能想到的唯一方法是将它们存储在数据库中,直到找到与服务器的连接。

  1. 如何检查我是否有互联网连接?

来自 POST 的代码在这里,如果我必须捕获数据,我假设我将必须执行它来代替异常句柄中的“无连接”错误对话框。

Thread t = new Thread() 
     {  

         public void run() 
            {
                Looper.prepare(); //For Preparing Message Pool for the child Thread
                HttpClient client = new DefaultHttpClient();
                HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
                HttpResponse response;
                try {
                        HttpPost post = new HttpPost("http:xxxxx");

                        StringEntity se = new StringEntity( flat.toString());  
                        se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                        post.setEntity(se);
                        response = client.execute(post);


                    //  /*Checking response */
                        if(response!=null){
                            InputStream in = response.getEntity().getContent(); //Get the data in the entity
                        }

                    } catch(Exception e) 
                    {
                            e.printStackTrace();
                            //createDialog("Error", "Cannot Estabilish Connection");
                            Toast.makeText(getApplicationContext(), "cannot establish concetion",Toast.LENGTH_SHORT).show();
                    }

                Looper.loop(); //Loop in the message queue
            }
        };

        t.start();     

最佳答案

  1. What would be the best way to cache the JASON strings locally and send them on their way when I get an internet connection.

您可以将它们放入数据库,但实际上我会将它们存储在本地应用程序文件中,该文件的路径可以存储在 SharedPreferences 中。

How do I check if I have an Internet connection?

使用android.net.conn.CONNECTIVITY_CHANGE广播:Broadcast receiver for checking internet connection in android app

在这个广播接收器中,你可以检查你的数据库或本地文件是否有东西要发送到服务器。

请注意,即使您的应用程序被置于后台,连接也可能恢复,此时 android 可能会终止您的应用程序。广播(如果放在 list 中)将恢复您的应用程序并允许重新发送任何 json 数据。

关于java - 在 Android 中本地缓存等待互联网连接的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22096324/

相关文章:

python - Beaker 的 @beaker_cache 缓存在 Pylons 中的位置

ASP.NET数据缓存设计

java - Spring MVC 4 @RequestParam DTO 强制属性

java - Realm 对象只能在创建它们的线程上访问

java - 处理 JPanel 中生成的形状

java - 如何在不因 NPE 导致设备崩溃的情况下将变量从一个 Activity 传递到另一个 Activity ?

android 键盘打开问题

java - Android-OnClick 在 gridview 行内

asp.net - ASP.NET 中的缓存模式

android - 游标索引越界异常(android SQLite)