java - 异步任务的问题

标签 java android multithreading asynchronous android-alertdialog

我正在尝试从网络服务器获取数据并显示一条消息“确定”或“无效 key ”。当它获取数据时,它应该产生一个进度对话框。我尝试了很多方法,包括将其放入线程内,但是在线程内,警报对话框将不起作用。我尝试过使用异步任务方法,但它似乎也不起作用。有人可以帮我找到解决方案吗?谢谢

verifyCode.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
    //I surround the async task with the progressdialog so that it should show while the method is working in the background
        final ProgressDialog progressDialog = ProgressDialog.show(
                    Activate.this, "", "Loading...");
            new checkActivationCode().execute(activationCode.toString().toUpperCase()
                    );

            progressDialog.dismiss();       
        }
    });

   public class checkActivationCode extends AsyncTask<String, Void, Void> {

    @Override
    protected Void doInBackground(String... activationCode) {
        // TODO Auto-generated method stub
        try {
            DefaultHttpClient httpclient = new DefaultHttpClient();
            HttpPost httpost = new HttpPost(
                    "https://iphone-radar.com/accounts/confirmation");

            JSONObject holder = new JSONObject();

            holder.put("code", activationCode);
            StringEntity se = new StringEntity(holder.toString());
            httpost.setEntity(se);
            httpost.setHeader("Accept", "application/json");
            httpost.setHeader("Content-type", "application/json");

            ResponseHandler responseHandler = new BasicResponseHandler();
            String response = httpclient.execute(httpost, responseHandler);

            if (response != null) {
                org.json.JSONObject obj = new org.json.JSONObject(response);

                if ("00000000-0000-0000-0000-000000000000".equals(obj
                        .getString("id"))) {
                    new AlertDialog.Builder(Activate.this)
                            .setTitle(
                                    getResources().getString(
                                            R.string.InvalidKey))
                            .setMessage(
                                    getResources()
                                            .getString(
                                                    R.string.PleaseEntervalidRegistration))
                            .setNeutralButton("OK", null).show();

                } else {
                    // add permanent variables
                    SharedPreferences prefs = getSharedPreferences(
                            "Settings", 0);
                    SharedPreferences.Editor editor = prefs.edit();

                    editor.putBoolean("ACTIVATED", true);
                    editor.putString("ID", obj.getString("id"));
                    editor.commit();

                    Intent imTracking = new Intent(Activate.this,
                            ImTracking.class);
                    imTracking.putExtra("ActivationSuccessful", true);
                    // transfer more data
                    startActivity(imTracking);
                }
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }
        return null;
    }

}

最佳答案

您无法通过 doInBackground() 方法显示任何类型的对话框或进度对话框,因为它不在 UI 线程上运行。您将需要使用 onProgressUpdate() 方法通过进度更新来更新 UI。如果您想在完成时显示 AlertDialog,请使用 onPostExecute() 方法。 onProgressUpdate()onPostExecute() 都在 UI 线程上运行,因此您的 AlertDialog 代码将正常工作。

这里是 AsyncTask 页面,其中包含一些有关如何正确使用它的示例代码(包括在何处提供 UI 更新):http://developer.android.com/reference/android/os/AsyncTask.html

这里有一些涉及同一主题的问题:How to use AsyncTask to show a ProgressDialog while doing background work in Android?

Updating progress dialog in Activity from AsyncTask

How can I remove an alert dialog after a AsyncTask has done it's work

关于java - 异步任务的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7071364/

相关文章:

java - GraphStream 中更好的图形可视化 - JAVA

java - 更改去电号码,添加前缀

c# - Task.ContinueWith(..., TaskScheduler.FromCurrentSynchronizationContext()) *不* 在 UI 线程上运行的任何场景?

java - 尝试使用 java EventHubClient API 将事件发送到 Azure 事件中心时出现“连接中止”错误

java - 如何在不生根的情况下 hibernate 或强制停止应用程序..?

java - 从 csv 文件加载数据时出现问题 - Java

java - 尝试关闭蓝牙套接字时,它变为空(错误: null object reference)

android - 如何在通知中重新打开 Activity 单击我的android

java - 如何通过另一个线程停止一个线程?

r - 如何在多线程遍历迭代之前和之后减少 foreach 花费的时间?