android截屏代码
时间: 2023-10-03 14:10:10 浏览: 32
以下是 Android 中截取屏幕的代码:
```java
// 获取屏幕截图
public Bitmap takeScreenshot() {
View rootView = getWindow().getDecorView().findViewById(android.R.id.content);
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
// 保存屏幕截图
public void saveScreenshot(Bitmap bitmap) {
String filePath = Environment.getExternalStorageDirectory() + "/screenshot.png";
File file = new File(filePath);
try {
FileOutputStream outputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
outputStream.flush();
outputStream.close();
Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "保存失败", Toast.LENGTH_SHORT).show();
}
}
```
其中,`takeScreenshot()` 方法用于获取屏幕截图,`saveScreenshot()` 方法用于保存屏幕截图到文件系统中。在 AndroidManifest.xml 中需要添加以下权限:
```xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)