首先,我正在編寫根應用程序,因此根權限不成問題。我搜索並搜索了很多代碼,這些代碼從來沒有爲我工作,這是我拼湊到目前爲止,有些作品。當我說sorta我的意思是它使我/ sdcard/test.png上的圖像,但該文件是0字節,顯然無法查看。Android以編程方式拍攝屏幕截圖
public class ScreenShot extends Activity{
View content;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.blank);
content = findViewById(R.id.blankview);
getScreen();
}
private void getScreen(){
Bitmap bitmap = content.getDrawingCache();
File file = new File("/sdcard/test.png");
try
{
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(CompressFormat.PNG, 100, ostream);
ostream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
任何幫助,我可以通過代碼在Android的屏幕截圖將不勝感激,謝謝!
===編輯===
以下是一切我使用的圖像在我的SD卡是由並且不再0bytes但整個事情是黑色的就沒有什麼了。我已經將活動綁定到了我的搜索按鈕,所以當我在手機上的某處我長時間按下搜索按鈕時,它應該會拍攝一個屏幕截圖,但我只是得到一個黑色圖像?一切設置透明的所以我覺得應該抓住什麼是在屏幕上,但我只是不斷收到黑
清單
<activity android:name=".extras.ScreenShot"
android:theme="@android:style/Theme.Translucent.NoTitleBar"
android:noHistory="true" >
<intent-filter>
<action android:name="android.intent.action.SEARCH_LONG_PRESS" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00000000"
android:id="@+id/screenRoot">
</LinearLayout>
截圖類
public class ScreenShot extends Activity{
View content;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screenshot);
content = findViewById(R.id.screenRoot);
ViewTreeObserver vto = content.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
content.getViewTreeObserver().removeGlobalOnLayoutListener(this);
getScreen();
}
});
}
private void getScreen(){
View view = content;
View v = view.getRootView();
v.setDrawingCacheEnabled(true);
Bitmap b = v.getDrawingCache();
String extr = Environment.getExternalStorageDirectory().toString();
File myPath = new File(extr, "test.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myPath);
b.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
MediaStore.Images.Media.insertImage(getContentResolver(), b, "Screen", "screen");
}catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finish();
}
}
ķ感謝您的回答要看看你的問題明天此刻只是太累了。我還有另外一個問題,但是當我這樣做時,怎麼不叫根?並且這段代碼是否僅僅是爲了佈局的屏幕截圖而已,因爲我想基本上在屏幕上顯示屏幕上的內容,當它長時間按下時,它會將搜索鍵綁定到屏幕上。 – user577732
好的。它的工作很好。但是,如果我使用該代碼來拍攝相機視圖的屏幕截圖,那麼它不會起作用。 –