处理Android异步任务失败

时间:2016-02-09 15:06:02

标签: android asynchronous httprequest

我的应用程序将JSON POST回API,该API在成功时返回响应。它通常可以工作(90%的时间),但偶尔用户按下同步按钮似乎没有任何事情发生。在后台,Async Task可能已经运行,但UI永远不会更新,应用程序也无法处理响应。 用户问题可以通过重新启动平板电脑,打开应用并再次进行同步来解决,它将首次运行。 重新启动平板电脑可能会解决此问题的原因是什么?

这是我的同步方法

private void Sync()
{
    if (connectedToNetwork())
    {
        syncStatus.setImageResource(0);
        syncStatus.setTag(0);
        status.setText(""); // Clear out text
        mProgressDialog.setMessage("Please wait for the sync to complete...");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setCancelable(false);
        mProgressDialog.show();

        new SyncJob().execute();
    }
    else
    {
        // Do nothing
        HelperMethods.ShowToast(getString(R.string.wifi_not_connected), getApplicationContext());
    }
}

这会调用异步任务

   class SyncJob extends AsyncTask<String, String,SyncResponse>
{
    private Response response=null;

    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();

    }

    protected SyncResponse doInBackground(String... args) {

        SyncResponse syncResponse = new SyncResponse();

        // Get JWT
        String hash = HelperMethods.GenerateToken(settings.getAudienceName(), settings.getAuthPrivateApiKey(), settings.getRequestedResource(), HelperMethods.getTicks());
        response = JSONParser.makeHttpTokenRequest(url_get_jwt, "GET", null, hash);

        String jwt = response.getToken();

        if (response.getResponseCode()==200 && jwt != null) {
            syncResponse.setGetJWTSucceeded(true);
            publishProgress("\nAuthenticated");
        }
        else
        {
            if (response.isUnknownHostException()) {
                publishProgress("\nUnknown Host Exception - Check the internet connection");
            }
            else {
                publishProgress("\nFailed to Authenticate");
            }
            syncResponse.setGetJWTSucceeded(false);
            return syncResponse;
        }

        // Post candidates
        List<Candidate> listOfCandidates = HelperMethods.GetCandidates(SyncActivity.this);
        if (listOfCandidates != null)
        {
            int count = listOfCandidates.size();
            publishProgress("\n" + count +  " candidates to be uploaded");
            String jarray = HelperMethods.GetCandidatesAsJSONString(listOfCandidates, versionName, settings.getCountryCode());

            response = JSONParser.makeHttpPostRequest(url_create_candidate, "POST", jarray, jwt);

            if (response.getResponseCode()==200)
            {
                syncResponse.setPostCandidateSucceeded(true);
                publishProgress(HelperMethods.ProcessCandidatePOSTResponse(response.getjObj(), SyncActivity.this));
            }
            else
            {
                if (response.isUnknownHostException()) {
                    publishProgress("\nUnknown Host Exception - Check the internet connection");
                }
                publishProgress("\nUnable to upload Candidates");
                syncResponse.setPostCandidateSucceeded(false);
            }
        }
        else
        {
            publishProgress("\nNothing to upload");
        }

        // Get Subjects
        publishProgress("\nUpdating subjects...");
        response = JSONParser.makeHttpGetRequest(url_all_subjects, "GET", null, jwt);
        try {
            JSONArray subjects = response.getjObj().getJSONArray(TAG_SUBJECTS);
            if (response.getResponseCode()==200)
            {
                syncResponse.setGetSubjectsSucceeded(true);
                String numberSubjectsAdded = HelperMethods.AddSubjects(SyncActivity.this, subjects);
                publishProgress("\n" + numberSubjectsAdded);
            }
            else
            {
                if (response.isUnknownHostException()) {
                    publishProgress("\nUnknown Host Exception - Check the internet connection");
                }
                syncResponse.setGetSubjectsSucceeded(false);
                publishProgress("\nUnable to download subjects");
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        // Update events
        publishProgress("\nUpdating events...");
        response = JSONParser.makeHttpGetEventsRequest(url_get_events, "GET", null, jwt);
        try {
            JSONArray events = response.getjObj().getJSONArray(TAG_EVENTS);
            if (response.getResponseCode()==200)
            {
                //syncResponse.setGetSubjectsSucceeded(true);
                String numberEventsAdded = HelperMethods.AddEvents(SyncActivity.this, events);
                publishProgress("\n" + numberEventsAdded);
            }
            else
            {
                if (response.isUnknownHostException()) {
                    publishProgress("\nUnknown Host Exception - Check the internet connection");
                }
                //syncResponse.setGetSubjectsSucceeded(false);
                publishProgress("\nUnable to download events");
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return syncResponse;
    }

    protected void onPostExecute(SyncResponse response) {

        if (response.PostCandidateSucceeded())
        {
            syncStatus = (ImageView)findViewById(R.id.syncStatusImg);
            syncStatus.setTag(R.drawable.success);
            syncStatus.setImageResource(R.drawable.success);
        }

        try {
            mProgressDialog.dismiss();
        } catch (Exception e) {

        }
    }

    @Override
    protected  void onProgressUpdate(String...progress) {

        status = (TextView) findViewById(R.id.uploadStatusTextView);
        status.setText(status.getText() + progress[0]);
    }

}

非常感谢任何帮助

0 个答案:

没有答案