android screenshot? [closed]

自作多情 提交于 2019-12-13 09:31:50

问题


      Button button = (Button)findViewById(R.id.btnTakeScreenshot);
      button.setOnClickListener(new View.OnClickListener() {
      //@Override
      public void onClick(View v) {
      final View content = findViewById(R.id.layoutroot);
      content.setDrawingCacheEnabled(true);
       Bitmap bitmap = content.getDrawingCache();
       File file = new File(Environment.getExternalStorageDirectory() + "/test.png");
       try 
       {
           file.createNewFile();
           FileOutputStream ostream = new FileOutputStream(file);
           bitmap.compress(CompressFormat.PNG, 100, ostream);
           ostream.close();
           Toast.makeText(content.getContext(), "HELLO", Toast.LENGTH_SHORT);
       } 
       catch (Exception e) 
       {
        System.out.print("error");
           e.printStackTrace();
       }
}
});

above code is to capture a screenshot, but it creates blank file of zero kb?


回答1:


file.createNewFile(); does exactly what you asked of it: creates a blank, empty file. Then if the drawing cache is empty you will get nothing in the file. Try this:

Button button = (Button)findViewById(R.id.btnTakeScreenshot);
      final View content = findViewById(R.id.layoutroot);
      content.setDrawingCacheEnabled(true);
      button.setOnClickListener(new View.OnClickListener() {
      //@Override
      public void onClick(View v) {
       Bitmap bitmap = content.getDrawingCache();
       File file = new File(Environment.getExternalStorageDirectory() + "/test.png");
       try 
       {
           file.createNewFile();
           FileOutputStream ostream = new FileOutputStream(file);
           bitmap.compress(CompressFormat.PNG, 100, ostream);
           ostream.close();
           Toast.makeText(content.getContext(), "HELLO", Toast.LENGTH_SHORT);
       } 
       catch (Exception e) 
       {
        System.out.print("error");
           e.printStackTrace();
       }
}
});


来源:https://stackoverflow.com/questions/6436899/android-screenshot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!