android截屏功能實現(xiàn)代碼
android開發(fā)中通過View的getDrawingCache方法可以達到截屏的目的,只是缺少狀態(tài)欄!
原始界面

截屏得到的圖片

代碼實現(xiàn)
1. 添加權(quán)限(AndroidManifest.xml文件里)
2. 添加1個Button(activity_main.xml文件)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />
<Button
android:id="@+id/btn_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Screenshot"
/>
</RelativeLayout>
3. 實現(xiàn)截屏(MainActivity.java文件)
package com.example.androidtest;
import java.io.File;
import java.io.FileOutputStream;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.graphics.Bitmap;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) this.findViewById(R.id.btn_save);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
screenshot();
}
});
}
private void screenshot()
{
// 獲取屏幕
View dView = getWindow().getDecorView();
dView.setDrawingCacheEnabled(true);
dView.buildDrawingCache();
Bitmap bmp = dView.getDrawingCache();
if (bmp != null)
{
try {
// 獲取內(nèi)置SD卡路徑
String sdCardPath = Environment.getExternalStorageDirectory().getPath();
// 圖片文件路徑
String filePath = sdCardPath + File.separator + "screenshot.png";
File file = new File(filePath);
FileOutputStream os = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, os);
os.flush();
os.close();
} catch (Exception e) {
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android?掃碼槍輸入時屏蔽軟鍵盤和頂部狀態(tài)欄的解決方案
在Android設(shè)備上,使用掃碼槍時常遇到軟鍵盤和頂部狀態(tài)欄顯示問題,本文介紹了在Android 7.1.2版本上,如何通過設(shè)置inputType為none屏蔽軟鍵盤,以及通過hideStatusBar和NoActionBar方法隱藏頂部狀態(tài)欄,以優(yōu)化掃碼槍使用界面,這些方法有助于提升使用掃碼槍場景的用戶體驗2024-10-10
Android中自定義ImageView添加文字設(shè)置按下效果詳解
這篇文章主要給大家介紹了關(guān)于Android中自定義ImageView添加文字設(shè)置按下效果的相關(guān)資料,實現(xiàn)后的效果非常利用用戶的體驗,文中給出了詳細的示例代碼供大家參考學(xué)習(xí),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)下吧。2017-08-08
android中RecyclerView自定義分割線實現(xiàn)
本篇文章主要介紹了android中RecyclerView自定義分割線實現(xiàn),由于RecyclerView的布局方式多種多樣,所以它的分割線也根據(jù)布局的不同有所差異,本文只針對LinearLayoutManager線性布局。2017-03-03
Android開發(fā)筆記之: 數(shù)據(jù)存儲方式詳解
本篇文章是對Android中數(shù)據(jù)存儲方式進行了詳細的分析介紹,需要的朋友參考下2013-05-05

