Set Wallpaper in whatsapp after getting the path - android

I am following this answer to accomplish my task. Everything works well except the last part,
if(result!=null)
{
Toast.makeText(getApplicationContext(), "Image saved in Gallery !", Toast.LENGTH_LONG).show();
if(isinint) //check if any app cares for the result
{
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND, Uri.fromFile(new File(result.toString()))); //Create a new intent. First parameter means that you want to send the file. The second parameter is the URI pointing to a file on the sd card. (openprev has the datatype File)
((Activity) ImageListActivity.this).setResult(Activity.RESULT_OK, shareIntent); //set the file/intent as result
((Activity) ImageListActivity.this).finish(); //close your application and get back to the requesting application like GMail and WhatsApp
return; //do not execute code below, not important
}
}
At last nothing crash but wallpaper is also not set in whatsapp.
Can anyone please let me know why it is not working?
Any help is appriciated.
Thanks

You can use the following code..
OnButtonClick(){
ImageProcessing imageProcessing = new ImageProcessing();
Bitmap bitmap = imageProcessing.takeScreenshot(getWindow().getDecorView().findViewById(R.id.view_thought));
imageProcessing.saveBitmap(bitmap);
Intent intent = imageProcessing.setAsOption(this,imageProcessing.getSavedImagePath());
startActivityForResult(Intent.createChooser(intent, "Set image as"), 200);
}
And Implement a new class ImageProcessing
public class ImageProcessing {
private File imagesPath;
public void saveBitmap(Bitmap bitmap) {
imagesPath = new File(Environment.getExternalStorageDirectory() + "/screenshot.jpg");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagesPath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("POS", e.getMessage(), e);
} catch (IOException e) {
Log.e("POS", e.getMessage(), e);
}
}
public File getSavedImagePath(){
imagesPath = new File(Environment.getExternalStorageDirectory() + "/screenshot.jpg");
return imagesPath;
}
public Bitmap takeScreenshot(View rootView) {
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
public Intent setAsOption(Context cntxt,File imagesPath){
/*File imagesPath = new File(Environment.getExternalStorageDirectory() + "/screenshot.jpg");*/
Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
if(imagesPath.exists()){
Uri contentUri = FileProvider.getUriForFile(cntxt, BuildConfig.APPLICATION_ID+".Utility.GenericFileProvider",imagesPath);
intent.setDataAndType(contentUri, "image/jpg");
intent.putExtra("mimeType", "image/jpg");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
}else {
Toast.makeText(cntxt,"Not a wallpaper",Toast.LENGTH_SHORT).show();
}
return intent;
}
}
And in menifest add :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.SET_WALLPAPER" />

Related

Capture image using camera and send that image as attachment in email : Android Studio

I want to capture image using camera and send it as attachment in Email.
I tried everything on Internet nothing is working for me. If anyone could help with code please.
public class MainActivity extends AppCompatActivity {
static final int REQUEST_IMAGE_CAPTURE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
if (resultCode == RESULT_OK) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
File file = savebitmap(thumbnail);
sendMail(file);
}
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
}
}
private File savebitmap(Bitmap bmp) {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
File file = new File(extStorageDirectory, "abcd" + ".jpg");
if (file.exists()) {
file.delete();
file = new File(extStorageDirectory, "abcd" + ".jpg");
}
try {
outStream = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return file;
}
void sendMail(File mFile){
Uri uri = null;
uri = Uri.fromFile(mFile);
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("image/jpeg");
intent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {"abc#gmail.com"});
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "subject");
intent.putExtra(android.content.Intent.EXTRA_TEXT, "body");
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(intent, "Share!"));
}
}
Saving the bitmap:
{
.....
File file = savebitmap(thumbnail);
sendMail(file);
}
private File savebitmap(Bitmap bmp) {
String extStorageDirectory = Environment.getExternalFilesDir().toString();
OutputStream outStream = null;
File file = new File(extStorageDirectory, temp + ".jpg");
if (file.exists()) {
file.delete();
file = new File(extStorageDirectory, temp + ".jpg");
}
try {
outStream = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return file;
}
//and then
void sendMail(File mFile){
Uri uri = null;
uri = Uri.fromFile(mFile);
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("image/jpeg");
intent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {""});
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, EMAIL_SUBJECT);
intent.putExtra(android.content.Intent.EXTRA_TEXT, EMAIL_BODY);
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(intent, "Share!"));
}
Here is an example from internet
https://androidexample.com/Camera_Photo_Capture_And_Show_Captured_Photo_On_Activity_/index.php?view=article_discription&aid=77&aaid=101
I am assuming you may not handle permission just like above link
when you run your app in 6.0 above like marshmallow device then need permission other wise no need to permission. that time your code work..
if run marshmallow device that time need permission then make below code ..
private void alertDialog(){
CharSequence menu[] = new CharSequence[]{"Take From Galery", "Open Camera"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a Picture");
builder.setItems(menu, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0){
Toast.makeText(getApplicationContext(), "galery", Toast.LENGTH_SHORT).show();
}else{
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivity(intent);
}
}
});
builder.show();
}
then above method put in permission code like below ..
if (ContextCompat.checkSelfPermission(webView.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(webView.this, Manifest.permission.CAMERA)) {
alertDialog();
}
else{
ActivityCompat.requestPermissions(webView.this, new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
}
}
add two permission into manifest file ..
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
your error main problem is permission if you add this below line is work.
if (ContextCompat.checkSelfPermission(webView.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(webView.this, Manifest.permission.CAMERA)) {
alertDialog();
}
else{
ActivityCompat.requestPermissions(webView.this, new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
}
}

Sharing an image in Android app using intent sends it as text file, not as a photo

I am trying to take a screenshot programatically and then share it to another app, using Intent. The problem that I face is that the photo is sent as a text file.
The button listener looks like this:
shareButton = rootView.findViewById(R.id.shareButton);
shareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Bitmap screenshot = Screenshot.takeScreenshot(view.getRootView());
String filename = "eduMediaPlayerScreenshot";
String sharePath = Screenshot.storeScreenshot(screenshot, filename);
Intent intent = Screenshot.shareScreenshot(sharePath, view.getRootView());
startActivity(intent);
}
});
And the Screenshot class like this:
public class Screenshot {
public static Bitmap takeScreenshot(View view) {
view.setDrawingCacheEnabled(true);
view.buildDrawingCache(true);
Bitmap screenshot = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
return screenshot;
}
public static String storeScreenshot(Bitmap screenshot, String filename) {
String path = Environment.getExternalStorageDirectory().toString() + "/" + filename;
OutputStream out = null;
File imageFile = new File(path);
try {
out = new FileOutputStream(imageFile);
screenshot.compress(Bitmap.CompressFormat.JPEG, 99, out);
out.flush();
} catch (FileNotFoundException e) {
Log.i("Exception:", "File not found.");
} catch (IOException e) {
Log.i("Exception:", "Cannot write to output file.");
} finally {
try {
if (out != null) {
out.close();
return imageFile.toString();
}
} catch (Exception e) {
Log.i("Exception:", "No output file to close.");
}
}
return null;
}
public static Intent shareScreenshot(String sharePath, View view) {
File file = new File(sharePath);
Uri uri = FileProvider.getUriForFile(view.getContext(),
BuildConfig.APPLICATION_ID + ".provider", file);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
return intent;
}
}
The shared photo looks like this:
not-the-best-photo
As Android will not recognize by default an image without extension, you should add .jpg to the end of the filename in the intent above. Without it, there should be a MIME type specified. More details on that here.
This is the code you might want to use.
shareButton = rootView.findViewById(R.id.shareButton);
shareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Bitmap screenshot = Screenshot.takeScreenshot(view.getRootView());
String filename = "eduMediaPlayerScreenshot.jpg";
String sharePath = Screenshot.storeScreenshot(screenshot, filename);
Intent intent = Screenshot.shareScreenshot(sharePath, view.getRootView());
startActivity(intent);
}
});

Using ShareActionProvider on a CardView in a Recyclerview

I am trying to provide a share feature on the cards displayed in my android application. I have learn't about the ShareactionProvider. This actionProvider is suppose to be present on every cardview. I have placed the code for the ShareActionprovider on my onBindViewHolder in the Adapter. When the app starts, all the cards execute their share at the same time. I will like to call this share only when the user requests.
#Override
public void onBindViewHolder(final ViewHolder viewHolder, final Cursor cursor) {
final NewsFacade facade = NewsFacade.fromCursor(cursor);
MenuItem shareMenuItem = viewHolder.toolbar.getMenu().findItem(R.id.share);
ShareActionProvider shareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(shareMenuItem);
shareActionProvider.setShareIntent(viewHolder.sendShareIntent(facade, context));
shareActionProvider.setShareHistoryFileName("custom_share_history.xml");
And Here are the Helper Methods to aid in the sharing:
public Intent sendShareIntent(NewsFacade facade, Context context)
{
saveImageToCache(facade, context);
return shareImage(context);
}
private void saveImageToCache(NewsFacade facade, Context context)
{
try {
Bitmap bitmap = facade.getThumb();
File cachePath = new File(context.getCacheDir(), "images");
cachePath.mkdirs();
FileOutputStream stream = new FileOutputStream(cachePath + "/image.png"); // overwrites this image every time
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
stream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private Intent shareImage(Context context)
{
File imagePath = new File(context.getCacheDir(), "images");
File newFile = new File(imagePath, "image.png");
Uri contentUri = FileProvider.getUriForFile(context, "com.example.clinton.companion.fileprovider", newFile);
if (contentUri != null) {
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // temp permission for receiving app to read this file
shareIntent.setDataAndType(contentUri,context.getContentResolver().getType(contentUri));
shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
context.startActivity(Intent.createChooser(shareIntent, "Choose an app"));
return shareIntent;
}
return null;
}
I know, I am calling the ActionProvider in the wrong place. But where else, should I call this, I need an instance of the object that cardview holds, so I can get the image in the cardview to share.
Please any help will be apreciated.
I fixed it.
I was calling
context.startActivity(Intent.createChooser(shareIntent, "Choose an app"));
which automatically executes the sharing.

How to send drawable Images from android app as MMS or on any social media app?

I'm not able to share my image from the app for messaging as an attachment
I have a list of int array of drawable images
final int [] imagelistId={
R.drawable.birthday1,
R.drawable.birthday2,
R.drawable.birthday3,
R.drawable.birthday4,
R.drawable.birthday5,
R.drawable.birthday6,
};
After that i have this code for sharing an image as an attachment
smsBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent smsIntent = new Intent(Intent.ACTION_SENDTO);
// add the message at the sms_body extra field
smsIntent.setData(Uri.parse("mmsto:"));
smsIntent.setType("image/*");
smsIntent.putExtra("sms_body", "Image");
smsIntent.putExtra("subject", "Image Message");
smsIntent.putExtra(Intent.EXTRA_STREAM,Uri.parse("android.resource://com.example.finalgreetings/" + imagelistId[pos]) );
try{
mcontext.startActivity(smsIntent);
} catch (Exception ex) {
Toast.makeText(mcontext, "Your sms has failed...",
Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
}
});
I have seen many stack overflow questions but none answered my problem.
I have also read about converting drawable to bitmap and save to internal or external storage then share it but dont know how to do it.
Kindly suggest me best and easy solution. Thanx in advance.
Try this..!!!
smsBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.yourimage);//put here your image id
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/LatestShare.png";
OutputStream out = null;
File file = new File(path);
try {
out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
path = file.getPath();
Uri bmpUri = Uri.parse("file://" + path);
Intent shareIntent = new Intent();
shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
shareIntent.setType("image/png");
startActivity(Intent.createChooser(shareIntent, "Share with"));
}
});

How to capture an image and store it with the native Android Camera

I am having a problem capturing an image and storing it from the native camera app. Here is a sample of some of my code.
_path = Environment.getExternalStorageDirectory() + "make_machine_example.jpg";
File file = new File( _path );
Uri outputFileUri = Uri.fromFile( file );
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE );
intent.putExtra( MediaStore.EXTRA_OUTPUT, outputFileUri );
startActivityForResult( intent, 0 );
After the picture has been taken and I'm returned back to my original Activity, When I navigate to my sd card via Android DDMS File Explorer the picture is not there. Anyone know why this is not being saved?
Here was the final product in case anyone is still visiting this thread:
public class CameraCapture extends Activity {
protected boolean _taken = true;
File sdImageMainDirectory;
protected static final String PHOTO_TAKEN = "photo_taken";
#Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
File root = new File(Environment
.getExternalStorageDirectory()
+ File.separator + "myDir" + File.separator);
root.mkdirs();
sdImageMainDirectory = new File(root, "myPicName");
startCameraActivity();
}
} catch (Exception e) {
finish();
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
}
protected void startCameraActivity() {
Uri outputFileUri = Uri.fromFile(sdImageMainDirectory);
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (resultCode) {
case 0:
finish();
break;
case -1:
try {
StoreImage(this, Uri.parse(data.toURI()),
sdImageMainDirectory);
} catch (Exception e) {
e.printStackTrace();
}
finish();
startActivity(new Intent(CameraCapture.this, Home.class));
}
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState.getBoolean(CameraCapture.PHOTO_TAKEN)) {
_taken = true;
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(CameraCapture.PHOTO_TAKEN, _taken);
}
public static void StoreImage(Context mContext, Uri imageLoc, File imageDir) {
Bitmap bm = null;
try {
bm = Media.getBitmap(mContext.getContentResolver(), imageLoc);
FileOutputStream out = new FileOutputStream(imageDir);
bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
bm.recycle();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Have you checked what the output of Environment.getExternalStorageDirectory() is, because if it does not contain a trailing file seperator (/) then your image will end up in a directory that does not reside on the SDcard such as:
/mnt/sdcardmake_machine_example.jpg
When what you really want is:
/mnt/sdcard/make_machine_example.jpg
Try this code instead:
_path = Environment.getExternalStorageDirectory() + File.separator + "make_machine_example.jpg";
1 . Just use
new File(Environment.getExternalStorageDirectory(), "make_machine_example.jpg");
and don't bother about separators.
2 . Faced the same problem before. SenseUI phones have a custom camera application that doesn't create file. What device are you using? It may already be fixed in latest devices but it may also still be an issue. So here's a complete sample how to overcome it Problems saving a photo to a file.
You should perform a media scanning after saving the image
sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
Add this line into AndroidManifest.xml file and remove extension make_machine_example:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
It will start to capture the Photo and store into the SDcard.

Categories

Resources