开发者

How to prevent freezing PhoneGap app in Android when doing asynchronous AJAX call?

I have PhoneGap-Android app and I am using Jquery. 开发者_运维技巧I am doing ASYNCHRONOUS AJAX call and during the call, app just freezes and waits after AJAX call finish ( it is mainly noticeable when on GSM connection ).

I would understand this, if I would be doing synchronous request, but I have:

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

Anybody can help ?


Ran into the same problem today. Solved it by using a setTimeout with a 10ms delay.

Not sure why it works, which is scary. But does work.


Can you get your AJAX call off the main UI thread? Example:

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;
            }
        }

    }

}


I had the same problem, and I solved this by calling the ajax request on "deviceready" event fired by phonegap.

I read an tutorial by accident here which says that the ajax request can be sent after the application is loaded properly. First bind to document deviceready event and send the ajax request inside the event handler. Doing in this way can solve the blocking UI problem.

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

I hope this can also solve your issue.


From the Jquery docs:

async Boolean Default: true By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

Since the phonegap code is running on localhost it will be cross-domain. If you can, do a request via GET instead of POST.


Try this code:

 $(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");
       }
            });

     });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜