尝试中止时NetworkOnMainThreadException

时间:2014-06-11 17:26:58

标签: android

我有一个AsyncTask,当它从URL获取数据时会弹出一个对话框,而一个处理程序会在对话框被取消时取消该请求。它在大多数情况下工作正常,但我发现它偶尔会崩溃一次NetworkOnMainThreadException。我的理论是,如果在doInBackground()完成之后但在onPostExecute()运行之前或之后对话框被解除,则CancelListener在主线程上运行。那么这个理论是否有意义,我将如何正确处理?试试并抓住?

以下是示例代码:

public class TestTask extends AsyncTask<Void, Void, Void>
{
    public ProgressDialog dialog;
    public Context context;
    public HttpUriRequest request;

    public TestTask(Activity activity)
    {
        context = activity;
    }

    @Override
    protected void onCancelled()
    {
        if (dialog != null)
            dialog.dismiss();
        super.onCancelled();
    }

    @Override
    protected void onPreExecute()
    {
        OnCancelListener cancelListener = new OnCancelListener()
        {
            @Override
            public void onCancel(DialogInterface dialog)
            {
                if (request != null)
                    request.abort(); // this causes NetworkOnMainThreadException sometimes
                TestTask.this.cancel(true);
            }
        };

        dialog = ProgressDialog.show(context, "", "Loading", true, true, cancelListener);
        dialog.setCanceledOnTouchOutside(false);
        dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... params)
    {
        String url = "some url";
        request = new HttpGet(url);
        // process request
        return null;
    }

    @Override
    protected void onPostExecute(Void result)
    {
        dialog.dismiss();
        super.onPostExecute(result);
    }

}

2 个答案:

答案 0 :(得分:0)

我不会在这里尝试/捕获 - 这只会解决问题,在这种情况下不会中止。你可以,例如产生一个线程来做中止

答案 1 :(得分:0)

尝试在中止前取消请求

@Override
public void onCancel(DialogInterface dialog)
{
    TestTask.this.cancel(true);
    if (request != null)
        request.abort(); // this causes NetworkOnMainThreadException sometimes
}