2012-10-17 67 views
-1

我正在啓動顯示對話框的線程,並且如果按下後退鍵(要做一些邏輯來停止該線程),該活動的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(); 
    } 

回答

0

如果你讓你的對話框中取消,您可以在活動中使用此代碼。 然後,您根本不必使用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(); 
    } 
    }); 

Appearantly,該decodeStream方法不容易被打斷(見註釋)。點擊此處瞭解詳情: SO answer

+0

中斷不會停止的位圖下載:S – Pableras84

+0

也許你需要在你的線程補充一點:'趕上(InterruptedException的E){Thread.currentThread()中斷()。 }' – MarchingHome

+0

這裏有一些更多的信息:[鏈接](http://stackoverflow.com/questions/5361624/how-to-cancel-a-thread) – MarchingHome