【问题标题】:How to prevent freezing PhoneGap app in Android when doing asynchronous AJAX call?进行异步 AJAX 调用时如何防止在 Android 中冻结 PhoneGap 应用程序?
【发布时间】:2011-05-17 04:33:29
【问题描述】:

我有 PhoneGap-Android 应用程序,我正在使用 Jquery。我正在做 ASYNCHRONOUS AJAX 通话,在通话期间,应用程序只是冻结并在 AJAX 通话完成后等待(主要在 GSM 连接时很明显)。

如果我要进行同步请求,我会理解这一点,但我有:

$.ajax({type: 'POST',url: 'http://www.example.com', data: data,async:true,success:callback});

有人可以帮忙吗?

【问题讨论】:

    标签: jquery android ajax asynchronous cordova


    【解决方案1】:

    今天遇到了同样的问题。通过使用具有 10 毫秒延迟的 setTimeout 来解决它。

    不确定它为什么会起作用,这很可怕。但确实有效。

    【讨论】:

      【解决方案2】:

      你能让你的 AJAX 调用脱离主 UI 线程吗?示例:

      public class JsonParsingActivity extends Activity {
      
          private static final String url = "http://search.twitter.com/search.json?q=javacodegeeks";
          protected InitTask _initTask;
      
          @Override
          public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.main);
      
              Button button = (Button)findViewById(R.id.button1);
              button.setOnClickListener(new View.OnClickListener() {
                  public void onClick(View v) {
                      _initTask = new InitTask();
                      _initTask.execute( getApplicationContext() );
                  }
              });
          }
      
          @Override
          public void onStop() {
              super.onStop();
              _initTask.cancel(true);
          }
      
          protected class InitTask extends AsyncTask<Context, String, SearchResponse>
          {
              @Override
              protected SearchResponse doInBackground( Context... params ) 
              {
                  InputStream source = retrieveStream(url);
                  SearchResponse response = null;
                  if (source != null) {
                      Gson gson = new Gson();
                      Reader reader = new InputStreamReader(source);
                      try {
                          response = gson.fromJson(reader, SearchResponse.class);
                          publishProgress( response.query );
                          reader.close();
                      } catch (Exception e) {
                          Log.w(getClass().getSimpleName(), "Error: " + e.getMessage() + " for URL " + url);
                      }
                  }
                  if (!this.isCancelled()) {
                      return response;
                  } else {
                      return null;
                  }
              }
      
              @Override
              protected void onProgressUpdate(String... s) 
              {
                  super.onProgressUpdate(s);
                  Toast.makeText(getApplicationContext(), s[0], Toast.LENGTH_SHORT).show();
              }
      
              @Override
              protected void onPostExecute( SearchResponse response ) 
              {
                  super.onPostExecute(response);
                  StringBuilder builder = new StringBuilder();
                  if (response != null) {
                      String delim = "* ";
                      List<Result> results = response.results;
                      for (Result result : results) {
                          builder.append(delim).append(result.fromUser);
                          delim="\n* ";
                      }
                  }
                  if (builder.length() > 0) {
                      Toast.makeText(getApplicationContext(), builder.toString(), Toast.LENGTH_SHORT).show();
                  } else {
                      Toast.makeText(getApplicationContext(), "The response was empty.", Toast.LENGTH_SHORT).show();
                  }
      
              }
      
              @Override
              protected void onCancelled() {
                  super.onCancelled();
                  Toast.makeText(getApplicationContext(), "The operation was cancelled.", 1).show();
              }
      
              private InputStream retrieveStream(String url) {
                  DefaultHttpClient client = new DefaultHttpClient(); 
                  HttpGet getRequest;
                  try {
                      getRequest = new HttpGet(url);
                      HttpResponse getResponse = client.execute(getRequest);
                      HttpEntity getResponseEntity = getResponse.getEntity();
                      return getResponseEntity.getContent();
                  } catch (Exception e) {
                      Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
                      return null;
                  }
              }
      
          }
      
      }
      

      【讨论】:

      • 感谢您的回答,但我实际上是在 jQuery 中寻找解决方案,因为我的应用程序是使用 PhoneGap 以 HTML5 编写的...
      • 抱歉没有帮助。我正在将它添加到我的收藏夹中。我也会对答案感兴趣。 +1
      【解决方案3】:

      我遇到了同样的问题,我通过在 phonegap 触发的“deviceready”事件上调用 ajax 请求解决了这个问题。

      无意中读到了一篇教程here,里面说可以在应用程序正确加载后发送ajax请求。首先绑定到文档 deviceready 事件并在事件处理程序中发送 ajax 请求。这样做可以解决阻塞UI的问题。

      function appReady(){
        // do the ajax here
      }
      document.addEventListener("deviceready", appReady, false);
      

      我希望这也能解决你的问题。

      【讨论】:

        【解决方案4】:

        来自 Jquery 文档:

        异步 布尔值 默认值:真 默认情况下,所有请求都是异步发送的(即默认设置为 true)。如果您需要同步请求,请将此选项设置为 false。跨域请求和 dataType: "jsonp" 请求不支持同步操作。请注意,同步请求可能会暂时锁定浏览器,从而在请求处于活动状态时禁用任何操作。

        由于 phonegap 代码在 localhost 上运行,它将是跨域的。如果可以,请通过 GET 而不是 POST 发出请求。

        【讨论】:

        • 没有意义 - 它说跨域支持同步。 GET 与 POST 在这里没有区别。
        【解决方案5】:

        试试这个代码:

         $(document).ready(function () {
                $.ajax({     
                type: "POST",
                url: "https://demo.yoursuppliernetwork.com/tnvrs/userservice/login/checkUser",
                data:{"username":login,"password":password},
                dataType:"json",
                contentType: "application/json; charset=utf-8",
                success: function(html)
                {
                    ss=html; 
                    console.log(ss);
                    document.write("success");
                },
               error:function(error)
               {
                console.log(error.status)
                document.write("error");
               },
               complete:function(html){
               console.log()
               document.write("complete");
               }
                    });
        
             });
        

        【讨论】:

          猜你喜欢
          • 2011-12-20
          • 1970-01-01
          • 1970-01-01
          • 2022-06-21
          • 2019-09-14
          • 2022-01-10
          • 2016-03-19
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多