I'm trying to pass the screenshot of screen with an explicit intent but the screen shows black screenshot(refer image here). As soon as i click share, a toast appears saying sending failed. Here's the code to capture screenshot and send it to other app:
public void getScreenShot(View view) {
View screenView = view.getRootView();
screenView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
screenView.setDrawingCacheEnabled(false);
f = new File(this.getFilesDir(), "screenshotFile");
try {
if (!f.exists())
f.createNewFile();
} catch (IOexception e) {
e.printStackTrace();
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 10, bos);
byte[] bitmapdata = bos.toByteArray();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
This code sends the data to whatsapp:
public void shareWhatsapp(View view) {
try {
myVib.vibrate(50);
getScreenShot(view);
//String fileName = "screenshotFile";
//Bitmap bitmap = BitmapFactory.decodeFile(f.getAbsolutePath());
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
try {
intent.setPackage("com.whatsapp");
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "App not installed", Toast.LENGTH_SHORT).show();
}
//TODO: APP CAN CRASH HERE
if (position > 0) {
try {
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f);
} catch (Exception e) {
e.printStackTrace();
} finally {
intent.putExtra(Intent.EXTRA_TEXT, Titles.get(position - 1) + ": " + Links.get(position - 1)); //position problems
}
} else {
try {
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f);
} catch (Exception e) {
e.printStackTrace();
} finally {
intent.putExtra(Intent.EXTRA_TEXT, Titles.get(0) + ": " + Links.get(0)); //position problems
}
}
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
Can someone help me with this?
First, you are writing the file to internal storage. Third-party apps do not have access to your app's internal storage.
Second, you are using Uri.fromFile(), which is starting to be discontinued.
Your safest long-term course of action is to have a ContentProvider serve your file from its location on internal storage, then use a Uri associated with that ContentProvider.
Related
Getting the path as of following but cannot access the screenshot, any idea?
Brings up path : /storage/emulated/0/test-screenshots/screenshot-001.png
while using the method:
Trying to capture a screenshot using the following method in Android Espresso:
takeScreenshot("screenshot-001", getActivity());
public static void takeScreenshot(String name, Activity activity)
{
// In Testdroid Cloud, taken screenshots are always stored
// under /test-screenshots/ folder and this ensures those screenshots
// be shown under Test Results
String path = Environment.getExternalStorageDirectory()+ "/test-screenshots/" + name + ".png";
Log.d("Logs", "Image Path is " + path);
View scrView = activity.getWindow().getDecorView().getRootView();
scrView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(scrView.getDrawingCache());
scrView.setDrawingCacheEnabled(false);
OutputStream out = null;
File imageFile = new File(path);
try {
out = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
} catch (java.io.FileNotFoundException e) {
// exception
} catch (java.io.IOException e) {
// exception
} finally {
try {
if (out != null) {
out.close();
}
} catch (Exception exc) {
}
}
}
I am trying to use getCropAndSetWallpaperIntent method of WallpaperManager class, but face problems with uri it need. First I tried to get Uri from drawable resourse, but I concluded that this is impossible, and decided to write file to internal storage and get its Uri. Now it gives an error, that uri type must be content. How can I fix this error? Maybe writing file to memory is totally wrong and there are other solutions?
Here is my code:
public void onclick(View v){
switch (v.getId())
{
case R.id.set:
// try{
//R.drawable.file1
File file =new File(this.getFilesDir(),getResources().getResourceName(R.drawable.file1));
file.setWritable(true);
if (!file.exists())
{
Bitmap bm= BitmapFactory.decodeResource(getResources(),R.drawable.file1);
try {
FileOutputStream outputStream=new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG,100,outputStream);
outputStream.flush();
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Uri uri=Uri.fromFile(file);
Intent i=wmanager.getCropAndSetWallpaperIntent(uri);
startActivity(i);
break;
case R.id.clear:
try{
wmanager.clear();
}
catch (IOException ioex){
ioex.printStackTrace();
}
}
}
I have seen the same problem, fixed by following method and works fine.
#TargetApi(Build.VERSION_CODES.KITKAT) private void setWallpaperKitkat(File file) {
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(WallpaperManager.ACTION_CROP_AND_SET_WALLPAPER);
String mime = "image/*";
intent.setDataAndType(uri, mime);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
//handle error
}
}
i have a imageview , i am trying to save bitmap from imageview by this method
bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
the rgb of saved image is not like that it looks in running app,so i am wondering if there is any way to save image view directly to a sd card rather getting the bitmap and then save it to sd card.
please help me i have tried everything.
You can read and write object using below code :
public static void witeObjectToFile(Context context, Object object, String filename)
{
ObjectOutputStream objectOut = null;
try
{
FileOutputStream fileOut = context.openFileOutput(filename, Activity.MODE_PRIVATE);
objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(object);
fileOut.getFD().sync();
} catch (IOException e)
{
e.printStackTrace();
} finally
{
if (objectOut != null)
{
try
{
objectOut.close();
} catch (IOException e)
{
// do nowt
}
}
}
}
public static Object readObjectFromFile(Context context, String filename)
{
ObjectInputStream objectIn = null;
Object object = null;
try
{
FileInputStream fileIn = context.getApplicationContext().openFileInput(filename);
objectIn = new ObjectInputStream(fileIn);
object = objectIn.readObject();
} catch (FileNotFoundException e)
{
// Do nothing
} catch (IOException e)
{
e.printStackTrace();
} catch (ClassNotFoundException e)
{
e.printStackTrace();
} finally
{
if (objectIn != null)
{
try
{
objectIn.close();
} catch (IOException e)
{
// do nowt
}
}
}
return object;
}
For example ArrayList can be saved as :
ImageView abcImage = (ImageView) readObjectFromFile(context, AppConstants.FILE_PATH_TO_DATA);
and write as :
witeObjectToFile(context, abcImage, AppConstants.FILE_PATH_TO_DATA);
Try to use this
public void onClick(View v) {
if (v.getId() == R.id.btnSaveImage) {
imageView.setDrawingCacheEnabled(true);
Bitmap bm = imageView.getDrawingCache();
storeImage(bm);
}
}
private boolean storeImage(Bitmap imageData) {
// get path to external storage (SD card)
String iconsStoragePath = Environment.getExternalStorageDirectory() + "/yourappname/";
File sdIconStorageDir = new File(iconsStoragePath);
// create storage directories, if they don't exist
sdIconStorageDir.mkdirs();
try {
File file = new File(sdIconStorageDir.toString() + File.separator + "fileName");
FileOutputStream fileOutputStream = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
imageData.compress(CompressFormat.PNG, 100, bos);
bos.flush();
bos.close();
MediaScannerConnection.scanFile(this, new String[] { file.getPath() },
new String[] { "image/jpeg" }, null);
Toast.makeText(this, "Snapshot Saved to " + file, Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
return false;
} catch (IOException e) {
return false;
}
return true;
}
I unable to attach Audio file to Some of the Samsung Devices like Samsung GalaxyS2,Nexus etc.I don't know whats the problem.I am able to attach all other devices.Please someone help me for my this issue.My code is as:
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra("sms_body",
getResources().getText(R.string.Message));
sendIntent.setClassName("com.android.mms",
"com.android.mms.ui.ComposeMessageActivity");
AssetManager mngr = getAssets();
InputStream path = null;
try {
path = mngr.open("*.mp3");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedInputStream bis = new BufferedInputStream(path, 1024);
// get the bytes one by one
int current = 0;
//
try {
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
} catch (IOException e) {
// /TODO Auto-generated catch block
e.printStackTrace();
}
byte[] bitmapdata = baf.toByteArray();
File file = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath(), "*.mp3");
// if (file.exists() == true) {
// } else {
// Log.v("directory is created", "new dir");
// file.mkdir();
// }
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
fos.write(bitmapdata);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
// handle exception
} catch (IOException e) {
// handle exception
}
final File file1 = new File(Environment
.getExternalStorageDirectory().getAbsolutePath(),
"*.mp3");
Uri uri = Uri.fromFile(file1);
Log.e("Path", "" + uri);
sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
sendIntent.setType("audio/mp3");
// sendIntent.putExtra(Intent.EXTRA_STREAM, mms_uri.toString());
startActivity(Intent.createChooser(sendIntent, ""));
// startActivity(sendIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again later!", Toast.LENGTH_LONG)
.show();
e.printStackTrace();
}
Don't set the class name explicitly by calling setClassName(). Instead just set the action, type and extra as described here.
You are assuming that there is ExternalStorage i.e. sd card available on the device. Your S2 or Nexus probably does not have the sd card. I have seen this issue before.
Hi I have a gallery in my app which shows the image in an image view when you click on the thumbnail. I am setting up a Long Click Listener for an alert dialog that has 2 buttons one to set as wallpaper and one to share. I have the share intent and the get drawing cache somewhat working. It works in the emulator but not on my phone. I have used many of the examples on this site to get this going but its not working at all. it keeps force closing the app on my phone. any help is appreciated.
alertDialog.setButton2("Share",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
imgView.setDrawingCacheEnabled(true);
Bitmap b = imgView.getDrawingCache();
File sdCard = Environment.getExternalStorageDirectory();
File file = new File(sdCard.getAbsolutePath() + "image.jpg");
try {
file.createNewFile();
OutputStream fos = null;
fos = new FileOutputStream(file);
b.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("Save Example", "Image saved.");
Intent shareIntent = new Intent(Intent.ACTION_SEND);
Uri phototUri = Uri.parse("file:///sdcard/image.jpg");
shareIntent.setData(phototUri);
shareIntent.setType("image/jpeg");
shareIntent.putExtra(Intent.EXTRA_STREAM, phototUri);
startActivity(Intent.createChooser(shareIntent, "Share Via"));
}
});
alertDialog.show();
return true;
}
});
Update: it seems to be a problem with
b.compress(CompressFormat.JPEG, 95, fos);
it keeps saying null pointer.
Turns out the null pointer is actually a read_only error..So its not actually writing the file i get a ioexception read-only file system. Why is it doing this?
ok here s what i ended up doing to get this to share the pictures in case others need it. It turns out my ImageView was not being rendered as a BitMap so it was make files with nothing in them. So instead i am just calling the drawable from its postion and saving that. Its a lot cleaner code for this simple gallery. I have it in an alert dialog but it can be set to a regular button also.
alertDialog.setButton2("Share",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
long currentTime = System.currentTimeMillis();
imgView.setDrawingCacheEnabled(true);
String newFolder = "/CFW";
String extStorageDirectory = Environment
.getExternalStorageDirectory()
.toString();
File sdCard = new File(extStorageDirectory
+ newFolder);
sdCard.mkdir();
File file = new File(sdCard.getAbsolutePath()
+ "/cfw" + currentTime + ".jpg");
try {
InputStream is = getResources()
.openRawResource(pics[position]);
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("Save Example", "Image saved.");
Intent shareIntent = new Intent(
Intent.ACTION_SEND);
Uri photoUri = Uri
.parse("file:///sdcard/CFW/cfw"
+ currentTime + ".jpg");
shareIntent.setData(photoUri);
shareIntent.setType("image/jpeg");
shareIntent.putExtra(Intent.EXTRA_STREAM,
photoUri);
startActivity(Intent.createChooser(shareIntent,
"Share Via"));
}
});
alertDialog.show();
return true;
}
});
}