Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
943 views
in Technique[技术] by (71.8m points)

how to take a screen shot on a button click can anyone provide a android code

I want to take the screen shot of current screen when,I click a button.Can anyone provide a android code.I need to save the image in the gallery also.this is what i tried

public class CaptureScreenShots extends Activity {
LinearLayout L1;
ImageView image;
 @Override
     protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.screen_shots);
    L1 = (LinearLayout) findViewById(R.id.LinearLayout01);
    Button but = (Button) findViewById(R.id.munchscreen);
    but.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            View v1 = L1.getRootView();
            v1.setDrawingCacheEnabled(true);
            Bitmap bm = v1.getDrawingCache();
            BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
            image = (ImageView) findViewById(R.id.screenshots);
            image.setBackgroundDrawable(bitmapDrawable);
        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.screen_shots, menu);
    return true;
}

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

set button click listener

share = (Button)findViewById(R.id.share);
share.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Bitmap bitmap = takeScreenshot();
        saveBitmap(bitmap);

    }
});

then you have to create two method

public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}

public void saveBitmap(Bitmap bitmap) {
File imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
FileOutputStream fos;
try {
    fos = new FileOutputStream(imagePath);
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
    fos.flush();
    fos.close();
} catch (FileNotFoundException e) {
    Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
    Log.e("GREC", e.getMessage(), e);
}
}

After add this code into your app, run the app and check your local storage, you have created screen shot of whole page.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...