Android按钮onClick()很慢

时间:2014-02-26 14:35:41

标签: android button click screenshot

从设备屏幕截取屏幕截图。它需要几秒钟才能执行,并且将显示动画的Toast消息。 这是我的代码:

    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 个答案:

答案 0 :(得分: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();
    }
}

答案 1 :(得分: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();
            }