从带有appcontext的后台线程显示AlertDialog [英] Show an AlertDialog from a background Thread with the appcontext

查看:125
本文介绍了从带有appcontext的后台线程显示AlertDialog的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用对getApplicationContext()的引用从后台线程引发AlertDialog?

Is possible to raise an AlertDialog from a background thread using a reference to getApplicationContext()?

我正在尝试使用该代码,但是它不起作用

I'm trying with that code but it doesn't work

    new Thread(){
        public void run(){
            new AlertDialog.Builder(appcontext)
            .setMessage("Test")
            .setPositiveButton("Ok", null)
            .show();
        }
    }.start();

预先感谢

推荐答案

最简单的解决方案是使用AsyncTask.

Simplest Solution is to use an AsyncTask.

尝试以下代码

  private class LaunchDialog extends AsyncTask<Void,Void,Void>{
        Context context;
        public LaunchDialog(Context ctx){
           context =  ctx;
         }

    @Override
    protected  ArrayList<CategoryObj> doInBackground(Void... params) {
        //do the task to be done on NON-UI thread , or NON-Blocking thread
       // publishProgress(null);
    }

        @Override
        protected void onProgressUpdate(Void... v){
           //stuff done on UI thread , can be invoked from doInBackground

        }
    @Override
    protected void onPostExecute(Void x){
            //stuff to be done after task executes(done on UI thread)

         new AlertDialog.Builder(context)
            .setMessage("Test")
            .setPositiveButton("Ok", null)
            .show();

    }
    @Override
    protected void onPreExecute(){
             //stuff to be done before task executes (done on UI thread)
    }
}

只需启动线程即可

new LaunchDialog(this).execute();

在此处阅读有关无痛线程的文章- http://developer.android. com/resources/articles/painless-threading.html

read article about painless threading here -- http://developer.android.com/resources/articles/painless-threading.html

这篇关于从带有appcontext的后台线程显示AlertDialog的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆