运行此代码时ANR强制关闭

时间:2011-11-10 11:08:54

标签: java android json android-asynctask

此代码导致ANR强制关闭如何改进此代码?我尝试使用asynctask,但我无法在此代码中使用它:

我在这里尝试做的是更新程序活动将检查最新版本,如果有新版本,它会弹出 alertdialog 以要求用户在市场中更新< / p>

public class Updater extends Activity {

    private int newVerCode = 0;
    private String newVerName = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        if (getServerVerCode()) {
            int vercode = Config.getVerCode(this);
            if (newVerCode > vercode) {
                doNewVersionUpdate();

            } else {
                notNewVersionShow();
            }
        }

    }
//check version using json
    private boolean getServerVerCode() {
        try {
            String verjson = NetworkTool.getContent(Config.UPDATE_SERVER
                    + Config.UPDATE_VERJSON);
            JSONArray array = new JSONArray(verjson);
            if (array.length() > 0) {
                JSONObject obj = array.getJSONObject(0);
                try {
                    newVerCode = Integer.parseInt(obj.getString("verCode"));
                    newVerName = obj.getString("verName");
                } catch (Exception e) {
                    newVerCode = -1;
                    newVerName = "";
                    return false;
                }
            }
        } catch (Exception e) {

            return false;

        }
        return true;
    }
//Found No new version
    private void notNewVersionShow() {
        Updater.this.finish(); // End updater activity
    }

//Found New version
    private void doNewVersionUpdate() {
//Display alertdialog
    }
}

1 个答案:

答案 0 :(得分:2)

您可以使用AsyncTask - 是的。在doInBackground中,您可以添加getServerVerCode()onPostExecute if (getServerVerCode())中所有内容的代码。 doInBackground可以返回布尔值,因此您可以在onPostExecute中知道结果是什么。 像这样:

private class GetServerVerCode extends AsyncTask<Void, Void, Boolean> { 

    @Override 
    protected Boolean doInBackground(Void... params) {
      try {
        String verjson = NetworkTool.getContent(Config.UPDATE_SERVER
                + Config.UPDATE_VERJSON);
        JSONArray array = new JSONArray(verjson);
        if (array.length() > 0) {
            JSONObject obj = array.getJSONObject(0);
            try {
                newVerCode = Integer.parseInt(obj.getString("verCode"));
                newVerName = obj.getString("verName");
            } catch (Exception e) {
                newVerCode = -1;
                newVerName = "";
                return false;
            }
        }
    } catch (Exception e) {

        return false;

    }
    return true;
    } 

    @Override
    protected void onPostExecute(Boolean result) {
        if (result) {
            int vercode = Config.getVerCode(this);
            if (newVerCode > vercode) {
                doNewVersionUpdate();

            } else {
                notNewVersionShow();
            }
        }
    }
}