2014-02-26 47 views
-1

從設備屏幕截取屏幕截圖。它需要幾秒鐘之後纔會執行操作,並顯示帶動畫的烤麪包消息。 這裏是我的代碼:Android按鈕onClick()很慢

public void onClick(View v) { 
      v.startAnimation(animAlpha); 
      try { 
       Toast.makeText(GlobalTouchService.this, "Start process", 5000).show(); 
       Process sh = Runtime.getRuntime().exec("su", null,null); 
       OutputStream os = sh.getOutputStream(); 
       os.write(("/system/bin/screencap -p " + "/sdcard/img.png").getBytes("ASCII")); 
       os.flush(); 
       os.close(); 
       sh.waitFor(); 
       Toast.makeText(GlobalTouchService.this, "Screenshot captured", 5000).show(); 
      } catch (IOException io){ 
       io.printStackTrace(); 
      } catch (InterruptedException ie){ 
       ie.printStackTrace(); 
      } 

我不能在這裏使用位圖。我不關心慢動作,但我希望在點擊後立即顯示某些內容(因爲我想知道該按鈕已被點擊)。有什麼建議麼?

回答

2

在做大量工作時,您可以做一個AsyncTask

/// your button click event 
public void onClick(View v) { 
    new TakePrintScreen().execute(); 
    } 


private class TakePrintScreen extends AsyncTask<Void, String, String> { 
    private ProgressDialog progress; 

    @Override 
    protected void onPreExecute() { 
     progress = ProgressDialog.show(this, "Information", 
       "Please Wait.. ", true); 
    } 


    @Override 
    protected String doInBackground(Void... params) { 
     try { 
      v.startAnimation(animAlpha);   
     Process sh = Runtime.getRuntime().exec("su", null,null); 
     OutputStream os = sh.getOutputStream(); 
     os.write(("/system/bin/screencap -p " + "/sdcard/img.png").getBytes("ASCII")); 
     os.flush(); 
     os.close(); 
     sh.waitFor(); 
     } catch (Exception e) { 
      Log.e(Tag, e.getMessage().toString()); 
     } 
     return ""; 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     progress.dismiss(); 
    } 
} 
+0

謝謝,這個工程 – user1835337

0

您可以優化您的代碼並從try catch塊中顯示Toast消息。

public void onClick(View v) { 
      // put toast here 
      Toast.makeText(GlobalTouchService.this, "Start process", 5000).show(); 
      v.startAnimation(animAlpha); 
      try { 

       Process sh = Runtime.getRuntime().exec("su", null,null); 
       OutputStream os = sh.getOutputStream(); 
       os.write(("/system/bin/screencap -p " + "/sdcard/img.png").getBytes("ASCII")); 
       os.flush(); 
       os.close(); 
       sh.waitFor(); 
       Toast.makeText(GlobalTouchService.this, "Screenshot captured", 5000).show(); 
      } catch (IOException io){ 
       io.printStackTrace(); 
      } catch (InterruptedException ie){ 
       ie.printStackTrace(); 
      } 
+0

這真的不應該對速度有任何影響。 –