如何在android中的单独线程中读取Alert Dialog?

时间:2014-08-11 05:42:37

标签: android multithreading alertdialog

我在课堂上有一个AlertDialog构建器。我正在设置一些来自阅读文件的消息。之前因为文件文件太大而无法轻松加载,现在因为文本增长更多,所以需要花费一些时间来加载对话框并阻止UI。我怎么能在线程中运行它?

编辑代码:

enter image description here

public class Eula TaskCompleteListner{ {

static interface OnEulaAgreedTo {
        void onEulaAgreedTo();
    }


public static boolean show(final Activity activity,final Context context,final Boolean flag) {
        final Preferences prefs = Preferences.getInstance();
        Log.d(TAG, "insideEula");

if (!prefs.getEulaStatus(context)) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(
                    activity);
            Log.d(TAG, "insideEulaLaunch");
            builder.setTitle(R.string.eula_title);
            builder.setCancelable(true);
            builder.setPositiveButton(R.string.eula_accept,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            prefs.setEulaStatus(context, true);
                            if (activity instanceof OnEulaAgreedTo) {
                                ((OnEulaAgreedTo) activity).onEulaAgreedTo();

                            }

                        }
                    });
            builder.setNegativeButton(R.string.eula_refuse,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            refuse(activity);

                        }
                    });
            builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
                public void onCancel(DialogInterface dialog) {
                    refuse(activity);
                }
            });

            MyAsync async= new MyAsync(activity, new TaskCompleteListner() {
            public boolean onComplete(String result) {
                builder.setMessage(data);
                builder.create().show();
                return false;
              }
            }) ; 

            MyAsync async= new MyAsync(this, activity) ; 
            async.excecute(); 

            //builder.setMessage(readEula(activity)); //READING FILE AND SETTING HERE
            //builder.create().show();
            return false;
        }
        return true;
    }

    private static void refuse(Activity activity) {
        activity.finish();
    }

    @Override
    public boolean onComplete(String result) {
    // TODO Auto-generated method stub
    builder.setMessage(readEula(activity)); //READING FILE AND SETTING HERE
    builder.create().show();
    return false;
}

异步任务类

  public class MyAsync extends AsyncTask<Void, Void, String>{
    public static final String ASSET_EULA = "EULA";
    TaskCompleteListner taskCompleteListner;
    Activity activity;
    public interface TaskCompleteListner{
        public boolean onComplete(String result);

    }

    public MyAsync(TaskCompleteListner taskCompleteListner,Activity activity) {
        this.taskCompleteListner = taskCompleteListner;
        this.activity=activity;
    }

    @Override
    protected String doInBackground(Void... params) {

      String data=(String)readEula(activity);
      return data;
    }

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

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        taskCompleteListner.onComplete(result);
    }

    private static CharSequence readEula(Activity activity) {  //READING FILE HERE
            BufferedReader in = null;
            try {
                in = new BufferedReader(new InputStreamReader(activity.getAssets().open(ASSET_EULA)));
                String line;
                StringBuilder buffer = new StringBuilder();
                while ((line = in.readLine()) != null)
                    buffer.append(line).append('\n');

                byte[] latin1 = buffer.toString().getBytes("ISO-8859-1");
                return new String(latin1);

                //return buffer;
            } catch (IOException e) {
                return "";
            } finally {
                closeStream(in);
            }
        }

        private static void closeStream(Closeable stream) {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    // Ignore
                }
        }   
    }
}

4 个答案:

答案 0 :(得分:3)

您可以使用AsyncTask课程,在doInBackground()中阅读您的数据,然后返回CharSequence并在onPostExecute()中执行dialog.show()。

编辑:

继承人你能做什么,

创建一个类

private static class MyAsyncClass extends AsyncTask<Void,Void,CharSequence > {

    Activity activity;
    ProgressDialog dialog 

    public MyAsyncClass(Activity activity){
        this.activity = activity;
    }

    @Override
    protected void onPreExecute() {
        dialog = new ProgressDialog(activity);
        dialog.setMessage("Reading data");
        dialog.setCancelable(false);
        dialog.show();
    }

    @Override
    protected CharSequence doInBackground(Void... params) {
        return readEula(activity);
    }

    protected void onPostExecute(CharSequence data) {
        if(dialog!=null && dialog.isShowing())
                dialog.dismiss();

        final AlertDialog.Builder builder = new AlertDialog.Builder(
                activity);
        Log.d(TAG, "insideEulaLaunch");
        builder.setTitle(R.string.eula_title);
        builder.setCancelable(true);
        builder.setPositiveButton(R.string.eula_accept,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        prefs.setEulaStatus(context, true);
                        if (activity instanceof OnEulaAgreedTo) {
                            ((OnEulaAgreedTo) activity).onEulaAgreedTo();

                        }

                    }
                });
        builder.setNegativeButton(R.string.eula_refuse,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        refuse(activity);

                    }
                });
        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
            public void onCancel(DialogInterface dialog) {
                refuse(activity);
            }
        });

        builder.setMessage(data); 
        builder.create().show();
    }
}

然后将此类称为

if (!prefs.getEulaStatus(context)) {
    MyAsyncClass myAsyncClass = new MyAsyncClass(activity);
    myAsyncClass.execute();
}

更正您的修改:

    你的Eula班的

  1. 改变这个,

    MyAsync async = new MyAsync(activity,new TaskCompleteListner(){         public boolean onComplete(String result){             builder.setMessage(数据);             builder.create()表示();             返回false;           }         });

        MyAsync async= new MyAsync(this, activity) ; 
        async.excecute();
    
  2. 到此,

    MyAsync async= new MyAsync(activity, new TaskCompleteListner() {
            public boolean onComplete(String result) {
                builder.setMessage(data);
                builder.create().show();
                return false;
              }
            }) ; 
    
            async.excecute();
    
      您的Async类中的
    1. 将构造函数更改为,

      public MyAsync(Activity activity,TaskCompleteListner taskCompleteListner){     this.taskCompleteListner = taskCompleteListner;     this.activity =活性; }

答案 1 :(得分:1)

使用此异步类来获取文本

public class MyAsync extends AsyncTask<Void, Void, String>{
TaskCompleteListner taskCompleteListner;
Activity activity;
public interface TaskCompleteListner{
    public boolean onComplete(String result);

}

public MyAsync(TaskCompleteListner taskCompleteListner,Activity activity) {
    this.taskCompleteListner = taskCompleteListner;
    this.activity=activity;
}

@Override
protected String doInBackground(Void... params) {

  String data=(String) readEula(activity);
    return data;
}


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

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    taskCompleteListner.onComplete(result);
}

 private static CharSequence readEula(Activity activity) {  //READING FILE HERE
        BufferedReader in = null;
        try {
            in = new BufferedReader(new InputStreamReader(activity.getAssets().open(ASSET_EULA)));
            String line;
            StringBuilder buffer = new StringBuilder();
            while ((line = in.readLine()) != null)
                buffer.append(line).append('\n');

            byte[] latin1 = buffer.toString().getBytes("ISO-8859-1");
            return new String(latin1);

            //return buffer;
        } catch (IOException e) {
            return "";
        } finally {
            closeStream(in);
        }
    }

    private static void closeStream(Closeable stream) {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                // Ignore
            }
        }   
}
}

您可以在Eula课程中使用它,如下所示:

if (!prefs.getEulaStatus(context)) {
        MyAsync async= new  MyAsync(activity,new TaskCompleteListner() {

            @Override
            public boolean onComplete(String result) {
                //TODO show your alert dialog here. Result has the string needed
                return false;
            }
        }) ;  


    }

希望这有帮助。

答案 2 :(得分:0)

异步任务将是更好的方法。 1.在doInBackGround中执行后台操作(readEula(活动活动)) 2.在onPostExecute方法中显示对话框。

在另一种方法中创建线程并在其中执行操作(readEula(act))并使用handler与此线程进行通信,并仅在您的活动中显示警告对话框。

答案 3 :(得分:0)

如果只需要显示一个对话框,您可以使用以下活动的方法:

public final void runOnUiThread (Runnable action)

AsyncTask将是一种更清洁的方法。但是,如果您正在寻找快速切换到主线程,这将为您省去额外代码的麻烦。