微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Android 不断尝试 POST 直到它通过

如何解决Android 不断尝试 POST 直到它通过

我有一条 POST 消息,在特定情况下我绝对必须在 Android 上发送,以至于我希望它继续尝试直到完成。我了解该设置:

urlConnection.setConnectTimeout(0);

会继续尝试连接直到它通过,但实际发生的是 try 块失败,而是抛出 UnkNownHostException:

private class SenDalert extends AsyncTask<String,String,String> { 
protected String doInBackground(String... strings) {
      Log.d(TAG,"sendAlarm: sending alarm");
      String stringUrl = createUri();
      HttpsURLConnection urlConnection = null;
      BufferedReader reader = null;

      String postData = "";
      Log.d(TAG,"sendAlarm: apikey: " + apiKey);
         try{
            Log.d(TAG,"sendAlarm: trying");
            URL finalURL = new URL(stringUrl);              
            urlConnection = (HttpsURLConnection)finalURL.openConnection();
            urlConnection.setReadTimeout(10000);
            urlConnection.setConnectTimeout(0);
            urlConnection.setRequestProperty("Content-Type","application/json;charset=UTF-8");
            urlConnection.setRequestProperty("Accept","application/json");
            urlConnection.setRequestProperty("x-api-key",apiKey);
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);

            int responseCode = urlConnection.getResponseCode();
            Log.d(TAG,"doInBackground: response code = " + responseCode);

        }catch (MalformedURLException e) {
            e.printstacktrace();
            Log.d(TAG,"doInBackground: error 1 " + e.toString());
        }catch(UnkNownHostException e){
            Log.d(TAG,"doInBackground: e: " + e);
            Log.d(TAG,"doInBackground: retrying");
        }          
        
        catch(Exception e){
            Log.d(TAG,"doInBackground: error 2 " + e.toString());
        }

想知道在 Android 上设置帖子消息的最佳方法是什么,即使手机处于飞行模式 5 小时,也要继续尝试连接直到连接成功。

编辑:下面@user3252344的回答,直接在AyncTask的catch块中再次调用函数有什么问题:

catch(UnkNownHostException e){
            Log.d(TAG,"doInBackground: retrying");
            SendAlarm sendAlarm = new SendAlarm;
            sendAlarm.execute();
        }     

解决方法

将连接超时设置为 0 意味着它不会超时,但如果连接失败,它仍然不会处理它。我猜你会收到一个 UnknownHostException,因为它无法解析 url,因为它无法访问 DNS 服务器。

我建议你设置一个合理的连接超时,如果超时异常发生并重新运行。

final int READ_TIMEOUT = 500; // Timeout
final int RETRY_MS = 2000; //Retry every 2 seconds
final Handler handler = new Handler();

Runnable myUrlCall = () -> {
    try {
        //Make things
        urlConnect.setReadTimeout(READ_TIMEOUT);
        //Make the URL call,do response
    } catch (SocketTimeoutException e) {
        handler.postDelayed(myUrlCall,RETRY_MS);
    } catch (/* other unintended errors*/ e) {
        //Log the error or alert the user
    }
};

handler.post(myUrlCall);

可能更好的主意:在您拨打电话之前使用 Android 设置检查是否有互联网。如果没有互联网,请使用更长的延迟。 Something like this would be the code you're looking for

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。