Android连续截屏代码
时间: 2023-05-12 16:06:05 浏览: 122
android截屏代码
4星 · 用户满意度95%
以下是一个简单的 Android 连续截屏代码示例:
```java
public class MainActivity extends AppCompatActivity {
private Handler handler = new Handler();
private int delay = 1000; // 截屏间隔时间,单位毫秒
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler.postDelayed(new Runnable() {
@Override
public void run() {
takeScreenshot();
handler.postDelayed(this, delay);
}
}, delay);
}
private void takeScreenshot() {
try {
// 获取屏幕截图
View view = getWindow().getDecorView().getRootView();
view.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
// 保存截图到文件
String filename = "screenshot_" + System.currentTimeMillis() + ".png";
File file = new File(Environment.getExternalStorageDirectory(), filename);
FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
Log.d("MainActivity", "Screenshot saved to " + file.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
这个示例代码会每隔一定时间截取一张屏幕截图,并保存到外部存储器中。注意需要在 AndroidManifest.xml 中添加读写外部存储器的权限:
```xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
```
阅读全文