【问题标题】:A thread with a dialog is listening the back key, but i want that the main activity listen the back key带有对话框的线程正在监听后退键,但我希望主要活动监听后退键
【发布时间】:2012-10-17 20:58:19
【问题描述】:

我正在启动一个显示对话框的线程,如果我按下后退键(执行一些逻辑来停止线程),则不会调用活动的 onKeyDown 侦听器。这是因为它被带有对话框的线程捕获......我怎样才能避免这种情况?

这是我的代码:

public static void getRemoteImage(final String url, final Handler handler) {
        Thread thread = new Thread(){ 
            public void run() {
                try {
                    Looper.prepare();
                    handler.sendEmptyMessage(Util.SHOW_DIALOG);
                    final URL aURL = new URL(url);
                    final URLConnection conn = aURL.openConnection();
                    conn.connect();
                    final BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
                    image = BitmapFactory.decodeStream(bis);
                    bis.close();
                    handler.sendEmptyMessage(Util.HIDE_DIALOG); 
                    Looper.loop();  
                }catch (Exception e) {e.printStackTrace();}
            }
        };
        thread.start();
    }

【问题讨论】:

    标签: android android-dialog onkeydown


    【解决方案1】:

    如果您使对话框可取消,则可以在您的活动中使用此代码。 那么你根本不必使用onKeyDownListener。后退按钮自动调用onCancel()方法。

    onCreateDialog 代码将如下所示:

    updatingDialog = new ProgressDialog(this);
    updatingDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    updatingDialog.setMessage(getString(R.string.busy));
    updatingDialog.setCancelable(true);
    updatingDialog.setOnCancelListener(new OnCancelListener() {
        public void onCancel(DialogInterface dialog) {
            thread.interrupt();
        }
        });
    

    显然,decodeStream 方法不能轻易中断(参见 cmets)。更多信息在这里: SO answer

    【讨论】:

    • 中断不会停止位图的下载:S
    • 也许你需要在你的线程中添加这个:catch(InterruptedException e) { Thread.currentThread().interrupt(); }
    • 这里有更多信息:link
    • 不幸的是没有被中断的异常被调用,线程根本不会中断,因为 BitmapFactory.decodeStream(bis) 不能被中断,它是一个方法
    • 啊,具体方法请看:SO answer
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-08
    • 2016-12-30
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    相关资源
    最近更新 更多