在网上查了好久,都找不到完整的截屏源码。要不是有的能够通过编译,但是没有反应;要是就直接在模拟器上运行的时候直接就挂掉了。修改了好久,终于搞好了一份能够完全截图的代码。完整代码:
package com.lip.screenshot;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.os.Bundle;
import android.os.Environment;
import android.text.format.Time;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class ScreenShotActivity extends Activity
{
/** Called when the activity is first created. */
Button shoot;
Time time;
String fileName;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
shoot = (Button) findViewById(R.id.shoot);
shoot.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
time=new Time("GMT+8");
time.setToNow();//获得当前时间
fileName=time.year+"_"+time.month+"_"+time.monthDay+"_"+
time.hour+"_"+time.minute+"_"+time.second+".png";//格式化文件名
boolean b=screenShot(fileName);
//boolean b=ScreenShot.shoot(ScreenShotActivity.this,fileName);
if(b)
{
Toast.makeText(ScreenShotActivity.this,"截图成功",2000).show();
}
}
});
}
public boolean screenShot(String fileName)
{
//Context context = getApplicationContext();
View rootView = findViewById(R.id.rootLayout);
Bitmap newb = Bitmap.createBitmap(320, 480, Config.ARGB_8888);
Canvas canvas = new Canvas(newb);
rootView.draw(canvas);
File file = new File(Environment.getExternalStorageDirectory()+ "/" + fileName);
FileOutputStream f = null;
try
{
f = new FileOutputStream(file);
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
boolean shoot = newb.compress(Bitmap.CompressFormat.PNG, 100, f);
return shoot;
}
}
通过调用screenShot函数,可以生成一个以filename.png的图片保存在sd卡的根目录。
还有一点非常重要。就是获取Sd卡的读写权限。在AndroidManifest.XML文件中增加如下代码:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
这样 就可以在成功截屏了。
欢迎交流。