I'm developing an Android application to capture screenshots. What I'm trying to do is make a service with a button on the top of the screen and taking screenshot by tapping it.
I wonder if it may work, with service as I said. Also I want the button excluded from the screenshot. Am I able to do this?
Here is the code that allowed my screenshot to be stored on sd card and used later for whatever your needs are:
First, add proper permission to save file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
And this is the code (running in an Activity):
private void takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or OOM
e.printStackTrace();
}
}
And this is how you can open the recently generated image:
private void openScreenshot(File imageFile) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(imageFile);
intent.setDataAndType(uri, "image/*");
startActivity(intent);
}
to exclude the button, you can make button hide and then take screen show after some time interval.
Related
I am building a wallpaper app in java. When user selects an image, a small default menu should pop up like in the provided screenshot, where user can select which app should set the wallpaper.
So far I used WallpaperManager for setting the wallpaper but that doesnt give user an option to move the image etc. This is my first android app ever so I am learning with every step I take, so sorry if this is an easy task. I also have not found SO question that solves my problem.
Can you please point me to the right direction, waht should I google, look for, or show me some code that does this? Thank you in advance.
the followin code my solve your problem
File f=new File("wallpaper_file_path");
Intent i=new Intent(Intent.ACTION_SET_WALLPAPER,Uri.fromFile(f));
startActivity(i);
I made a wallpaper app, in that, I used a zoom image library so that I can adjust the image then I take the cache of that image view are and set it as wallpaper. and I can set it for the home screen, lock screen and for both
public void SetHomeAndLockScreen()
{
bmap=((BitmapDrawable)imageview.getDrawable()).getBitmap();//get the cache from zoomable imageview
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
WallpaperManager wpm = WallpaperManager.getInstance(getApplicationContext());
try {
wpm.setBitmap(bmap, null, true, WallpaperManager.FLAG_LOCK);
wpm.setBitmap(bmap);
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Wallpaper Applied", Toast.LENGTH_SHORT).show();
}
I was understand that you need to crop image from gallery try this use phone screen width for x and screen height for y
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setClassName("com.android.camera", "com.android.camera.CropImage");
File file = new File(filePath);
Uri uri = Uri.fromFile(file);
intent.setData(uri);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 4);
intent.putExtra("aspectY", 16);
intent.putExtra("outputX", 720);
intent.putExtra("outputY", 1080);
intent.putExtra("noFaceDetection", true);
intent.putExtra("return-data", true);
startActivityForResult(intent, REQUEST_CROP_ICON);`
When the picture select Activity return will be selected to save the contents.in
onActivityResult:
Bundle extras = data.getExtras();
if(extras != null ) {
Bitmap photo = extras.getParcelable("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 75, stream);
// The stream to write to a file or directly using the photo
} and set the wall paper using wallpaper manager
Modern solution :)
/**
* Set as wallpaper method
*/
public void setWallpaper() {
Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // Android 7.0+ required
Uri wallUri = getImageUri(this, wallpaperDrawableBitmap);
intent.setDataAndType(wallUri, "image/jpeg");
intent.putExtra("mimeType", "image/jpeg");
this.startActivity(Intent.createChooser(intent, "Set as:"));
}
Modern solution for static contexts :)
/**
* Set as wallpaper
*/
public static void setWallpaper(Activity activity) {
Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // Android 7.0+ required
Uri wallUri = getImageUri(activity, wallpaperDrawableBitmapStatic);
intent.setDataAndType(wallUri, "image/jpeg");
intent.putExtra("mimeType", "image/jpeg");
activity.startActivity(Intent.createChooser(intent, "Set as:"));
}
Note that setDataAndType(...) requires the image URI.
I am new to android studio and stack overflow so I may not make any sense but I want to pass some data from one activity to another. I have managed to do it through the putExtra() on the intent with all the text that I want passed to the activity. However, I do not know how to set a getIntent on an image that has to be produced with setImageResource().
FavActivity
Cursor cursor = (Cursor) mylist.getItemAtPosition(position);
String listName = cursor.getString(1);
String displayName = db.getName(listName);
if (!displayName.isEmpty()) {
String isleName = db.getIsle(listName);
String rowName = db.getRow(listName);
String locationImage = db.getLocationImage(listName);
Intent myIntent = new Intent(view.getContext(),MainActivity.class);
myIntent.putExtra("name", displayName);
myIntent.putExtra("isle", "Isle: " + isleName);
myIntent.putExtra("row", "Row: " +rowName);
myIntent.putExtra("image", locationImage);
startActivity(myIntent);
MainActivity
textView.setText(getIntent().getStringExtra("name"));
textView3.setText(getIntent().getStringExtra("isle"));
textView4.setText(getIntent().getStringExtra("row"));
Image location has to be set like this as its converting from database text
locationView.setImageResource(getResources().getIdentifier(locationImage, "drawable", getPackageName()));
How do I set an intent to do this?
Store the image in a file and pass the file path through the intent to the other activty and you can access the image from that file path in the other activity
You can pass an image but I would suggest storing the image in Internal storage and pass them using Intent.
As of API 24, there is 1 MB restriction else it would throw TransactionTooLarge Exception and may cost you too much memory
Saving image to Internal Storage-
public String createImageFromBitmap(Bitmap bitmap) {
String fileName = "myImage";//no .png or .jpg needed
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
FileOutputStream fo = openFileOutput(fileName, Context.MODE_PRIVATE);
fo.write(bytes.toByteArray());
// remember close file output
fo.close();
} catch (Exception e) {
e.printStackTrace();
fileName = null;
}
return fileName;
}
and then pass that file name in Bundle
Bitmap bitmap = BitmapFactory.decodeStream(context
.openFileInput("myImage"));
An another example to be used
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.my_layout);
Bitmap bitmap = getIntent().getParcelableExtra("image");
ImageView imageView = (ImageView) findViewById(R.id.imageview);
imageView.setImageBitmap(bitmap);
}
Hiii,
You can send an image in Base64 format and convert it to an image after receiving in next Activity.
Though make sure that you can send maximum 50kb data using Intents.
Otherwise, your app might misbehave on sending and receiving data.
I know this question has been answered, but I would like to get a better explanation as I have tried implementing it but it doesn't seem to work.
I have the following code :
private void takeScreenshot() {
ContextWrapper cw = new ContextWrapper(getApplicationContext());
//Get screenshot
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
Date fileName = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", fileName);
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
File image = new File(directory,fileName+".jpg");
try {
FileOutputStream fos = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
}
}
What I would like to happen is to take a screenshot of the screen, save it to a folder with my app name, and have it be readable by the android phone's gallery. My code does none of the above. I do not see any folder w/ the name of my app when I use file explorer, and it doesn't appear in the gallery as well. It seems it doesn't even save the image. Can you please tell me what is wrong with my code?
The code below creates a directory called "AppName" and then stores the screenshot in that directory. This will be readable by the gallery as well. Your code (and the code below) will not work if you do not have the WRITE_EXTERNAL_STORAGE permission.
private static File getOutputMediaFile() {
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp"); //change to your app name
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_" + timeStamp + ".jpg");
return mediaFile;
}
private void takeScreenshot(){
//Get screenshot
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File pictureFile = getOutputMediaFile();
if (pictureFile == null){
Log.d(TAG, "error creating media file, check storage permission");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
bitmap.recycle();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found" + e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
}
Ensure to add
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
to your manifest and ask for permissions on runtime with
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
00);
The code finds and/or creates a directory with the app name in the getOutputMediaFile() method, then returns a file in the directory with timestamp as its name. Then in the takeScreenshot() method, the screenshot bitmap is converted to a byte[] and a fileOutputStream is used to write this byte[] to the file returned by getOutputMediaFile().
The result is a screenshot saved to the gallery in the directory "MyCameraApp" (Change to whatever your app's name is)
Hope this helps!
I built my own camera so it could be launched from inside my other android app, i want to save the images inside this app and not in the default gallery, i was using getExternalFilesDir() because i wanna keep the data just inside my app. But it is not working quite right, does anybody know what i have to change?? I do have the permission in my manifest.
My phone is an HTC phone
private void dispatchTakePictureIntent(int actionCode) {
imageURI = getExternalFilesDir(null) + File.separator
+ System.currentTimeMillis() + ".jpg";
File mFile = new File(getFilesDir(), "newImage.jpg");
if(!mFile.exists()) {
try{
mFile.createNewFile();
} catch (Exception e){
return;
}
}
//Uri iURI = Uri.parse(imageURI);
Log.v("camera", mFile.toString()); // Debugging statement
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mFile));
startActivityForResult(takePictureIntent, actionCode);
}
Here is the code that i am using to do it.
To hide the images from gallery you should create .nomedia file in the folder with images, or create your own camera app.
I have a bitmap that I have saved in the external storage. I already have a method that loads and returns the bitmap. My question is, how do I attach this image to an email Intent.
Note: I know how to start the email intent, I simply need to know how to attach the bitmap. Thanks.
This is how I am saving the pic:
private void savePicture(String filename, Bitmap b, Context ctx) {
try {
FileOutputStream out;
out = ctx.openFileOutput(filename, Context.MODE_WORLD_READABLE);
b.compress(Bitmap.CompressFormat.JPEG, 40, out);
if (b.compress(Bitmap.CompressFormat.JPEG, 40, out) == true)
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
try this for Attach Image with Email
Fetch Image From SdCard
String path = Environment.getExternalStorageDirectory().toString();
File file = new File(path,"YourImageName.JPEG");
Uri pngUri = Uri.fromFile(file);
Email Intent
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("text/html");
emailIntent.putExtra(android.content.Intent.EXTRA_STREAM, pngUri);