Intent share = new Intent(Intent.ACTION_SEND);
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("android.resource://" + ContextID.getPackageName() + "/" + ResourceID));
share.setType("audio/*");
ContextID.startActivity(Intent.createChooser(share, "Condividi il suono"));
The above code works fine with Gmail, while Whatsapp gives a toast message like "Share a file failed, please try it again"
Maybe i've the same problem of this guy: Intent.ACTION_SEND Whatsapp
But how can i temporarily copy my resources on sd card and then share them?
File dest = Environment.getExternalStorageDirectory();
InputStream in = ContextID.getResources().openRawResource(ResourceID);
try
{
OutputStream out = new FileOutputStream(new File(dest, "lastshared.mp3"));
byte[] buf = new byte[1024];
int len;
while ( (len = in.read(buf, 0, buf.length)) != -1)
{
out.write(buf, 0, len);
}
in.close();
out.close();
}
catch (Exception e) {}
Intent share = new Intent(Intent.ACTION_SEND);
share.putExtra(Intent.EXTRA_STREAM, Uri.parse(Environment.getExternalStorageDirectory().toString() + "/lastshared.mp3"));
share.setType("audio/*");
ContextID.startActivity(Intent.createChooser(share, "Condividi il suono \"" + TheButton.getText() + "\""));
return true;
manifest:
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
...
</manifest>
please change this line from your code and you will be able to share
write ("audio/mp3") as bellow instead ("audio/*")
share.setType("audio/mp3");
this is because share type for whatsapp doesn't support ("audio/*") or ("*/*")
Related
After reading multiple post concerning this subject I have been able to put together the info needed to download an update for my apk and have it install. This is successful for versions under 23. After reading more post I discovered for versions 23> there is a slight difference in the way to execute the install. I have put together this info in the following code but I am still encountering a problem with the version 23>. I pretty much understand what the code is doing, but I have no idea why it fails to run.
try {
URL url = new URL(arg0[0]);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath() +"/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "maga.apk");
if(outputFile.exists()){
Log.i("SCROLLS ", "file exist-delete");
outputFile.delete();
}
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
if(outputFile.exists()){
Log.i("SCROLLS ", "file exist");
}
if (Build.VERSION.SDK_INT >= 23) {
File toInstall=new File(Uri.parse(PATH+"maga.apk").getPath());
Log.i("SCROLLS ", "toInstall "+ toInstall);
Uri apkUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", toInstall);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
} else {
File toInstall = new File(PATH, "maga" + ".apk");
Uri apkUri = Uri.fromFile(toInstall);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
} catch (Exception e) {
Log.e("SCROLLS ", "Update error! " + e.getMessage());
}
return null;
}
}
When executed on an emulator with Version <23 all works. On an emulator over 23, the progress gets into the If statement and sets the toInstall value but nothing happens after that. The only thing I see in Logcat resembling and error that pertains to this is
03-24 01:35:16.562 5300-5300/com.google.android.packageinstaller E/InstallStart: Requesting uid 10079 needs to declare permission android.permission.REQUEST_INSTALL_PACKAGES
Looking into this it's my understanding that this permission is for system apps so adding it to Manifest does no good. Is there something missing from my code or a permission? I have added the provider to the manifest and the provider_paths.xml file to the project. Thanks for any help.
I'm trying to share an audio file from my res/raw folder. What I've done so far is:
Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.sound); //parse path to uri
Intent share = new Intent(Intent.ACTION_SEND); //share intent
share.setType("audio/*");
share.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(share, "Share sound to"));
When I choose to share it on GMail, for example, it says something like "Failed to attach empty file". Looks like I'm not getting the right file path, so I'm basically sharing nothing. What am I doing wrong?
Any help would be much appreciated.
Copy the audio file from the resource to external storage and then share it:
InputStream inputStream;
FileOutputStream fileOutputStream;
try {
inputStream = getResources().openRawResource(R.raw.sound);
fileOutputStream = new FileOutputStream(
new File(Environment.getExternalStorageDirectory(), "sound.mp3"));
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, length);
}
inputStream.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM,
Uri.parse("file://" + Environment.getExternalStorageDirectory() + "/sound.mp3" ));
intent.setType("audio/*");
startActivity(Intent.createChooser(intent, "Share sound"));
Add WRITE_EXTERNAL_STORAGE permission to AndroidManifest.xml file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
What am I doing wrong?
Few apps handle android.resource Uri values correctly. Your choices are:
Drop the feature, or
Copy the data from the resource into a file, then use FileProvider, perhaps in conjunction with my LegacyCompatCursorWrapper, or
Use my StreamProvider, which can serve raw resources directly, or
Copy the data from the resource into a file, then use Uri.fromFile(), but this looks like it will stop working with the next version of Android, based on preliminary results from testing with the N Developer Preview
EDIT: It was causing a NullPointException. This is what was I doing:
File dest = Environment.getExternalStorageDirectory();
InputStream in = getResources().openRawResource(R.raw.sound);
try
{
OutputStream out = new FileOutputStream(new File(dest, "sound.mp3"));
byte[] buf = new byte[1024];
int len;
while ( (len = in.read(buf, 0, buf.length)) != -1){
out.write(buf, 0, len);
}
in.close();
out.close();
}catch (Exception e) {}
final Uri uri = FileProvider.getUriForFile(Soundboard.this, "myapp.folagor.miquel.folagor", dest); //NullPointerException right here!!
final Intent intent = ShareCompat.IntentBuilder.from(Soundboard.this)
.setType("audio/*")
.setSubject(getString(R.string.share_subject))
.setStream(uri)
.setChooserTitle(R.string.share_title)
.createChooserIntent()
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET)
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
The code was just fine. The only problem was that on the Manifest's permisions, I had "WRITE_EXTERNAL_STORAGE" instead of "android.permissions.WRITE_EXTERNAL_STORAGE". So I was not having permision to write in the external storage, which caused a FileNotFoundException due to the lack of permision. Now it works fine!
I have a problem. I'd like to share my MP3 File to Whatsapp but it don't work! Here my Share Intent:
public void shareAchieve() {
Intent shareAchievement = new Intent();
shareAchievement.setType("audio/*");
shareAchievement.putExtra(Intent.EXTRA_STREAM, Uri.parse("android.resource://de.logtainment.ungesoundboard/" + R.raw.achieve + ".mp3"));
startActivity(Intent.createChooser(shareAchievement, "Teile Längstes Achievement"));
}
But it doesnt work! Sorry for my bad english i'm from germany.
As #CommonsWare Said Very few apps support the android:resource scheme
To make your app compatible with all apps.
You have to copy your raw resource to Internal Storage by this method
private String CopyRAWtoSDCard(int raw_id,String sharePath) throws IOException {
InputStream in = getResources().openRawResource(raw_id);
FileOutputStream out = new FileOutputStream(sharePath);
byte[] buff = new byte[1024];
int read = 0;
try {
while ((read = in.read(buff)) > 0) {
out.write(buff, 0, read);
}
} finally {
in.close();
out.close();
}
return sharePath;
}
Replace your method by below code
public void shareAchieve() {
Intent shareAchievement = new Intent(Intent.ACTION_SEND);
shareAchievement.setType("audio/*");
String sPath= null;
try {
sPath = CopyRAWtoSDCard(R.raw.filename, Environment.getExternalStorageDirectory()+"/filename.mp3");
} catch (IOException e) {
e.printStackTrace();
}
Uri uri = Uri.parse(sPath);
shareAchievement.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
shareAchievement.putExtra(Intent.EXTRA_STREAM,uri);
startActivity(Intent.createChooser(shareAchievement, "Teile Längstes Achievement"));
}
Also add
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
You have missed adding /raw/ to the path and change your Intent like
change
Intent shareAchievement= new Intent();
shareAchievement.putExtra(Intent.EXTRA_STREAM, Uri.parse("android.resource://de.logtainment.ungesoundboard/" + R.raw.achieve + ".mp3"));
to
Intent shareAchievement= new Intent(Intent.ACTION_SEND);
shareAchievement.putExtra(Intent.EXTRA_STREAM, Uri.parse("android.resource://de.logtainment.ungesoundboard/raw/achieve.mp3"));
In My Application I download PDF file to internal storage. after this I want to send mail with the file. I see the file is dowloaded in internal memory
com.my.app -> files-> pdffile.pdf
and it has permissions -rw-------
when I attach to mail the file and send gmail says: could't send attachment. But why ?? I have permission
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
this is code for dowloading file. it runs in async task
public static boolean saveFile(String fileName, Context context){
String fileDirectory = context.getFilesDir().getAbsolutePath()
+ "//"+fileName;
String urlServ = Constants.serverUrl+ "upload/forms/"+fileName;
urlServ = urlServ.replace(" ", "%20");
urlServ = urlServ.replace("\n", "%0d");
urlServ = urlServ.replace("\"", "%22");
int count;
URI fUri = URI.create("file://" + fileDirectory);
File f = new File(fileDirectory);
if (f.exists()){
f.delete();
}
try {
URL url = new URL(urlServ);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(fileDirectory);
//OutputStream output = context.openFileOutput(fileDirectory, Context.MODE_PRIVATE);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
return false;
}
return true;
}
And this is code for sending mail :
public static void sendMail(Context context, String filename) {
String fileDirectory = context.getFilesDir().getAbsolutePath()
+ "/"+filename;
File f = new File(fileDirectory);
Uri URI =Uri.fromFile(f);
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"mytestmail#gmail.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "subject of email");
i.putExtra(Intent.EXTRA_STREAM, URI);
i.putExtra(Intent.EXTRA_TEXT , "body of email");
try {
context.startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(context, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
What is wrong ? it sands mail only with subject and text... maybe there is some permissions issue. How can I donwload file and give it full permissions
EDIT:
It is permission issue, because when I send file with different permission from the same directory, mail with attachment is being sent. -rw-rw-rw- with this permission
How Can i donwload file and set -rw-rw-rw- permission to it ???
I have solved the problem, if anyone faces the same issue. When opening OutputStream like this
it gives new file permission -rw-rw-rw. and other application(Gmail in this case) can use it.
OutputStream output = context.openFileOutput( fileName, Context.MODE_WORLD_READABLE);
The problem here is that although your app has permissions to read the file, the email application doesn't have permission to read the file. Since Jelly Bean, StrictMode has produced a warning when you try to share a File URI outside your application because this kind of problem can occur where the app you are sharing a file with does not have permission to access the file. It is advised to use a content:// URI when sharing files between apps instead of a file:// URI.
I'd suggest using the FileProvider class, which provides a relatively simple way to share your files using a content:// URI.
I want to attach image within some text to MMS in Android.I found a lot here on SO as well as on Google but still not get the right solution yet.My code is as:
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("image/png");
sendIntent.putExtra("sms_body",
getResources().getText(R.string.Message));
// sendIntent.setType("vnd.android-dir/mms-sms");
Uri mms_uri = Uri.parse("android.resource://"
+ getPackageName() + "/" + R.drawable.app_logo);
sendIntent.putExtra(Intent.EXTRA_STREAM, mms_uri.toString());
startActivity(Intent.createChooser(sendIntent, ""));
Please Help me for my this Issue.
Have you had any luck with this? I tried a similar approach, and found that
Uri mms_uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.drawable.app_logo);
is not universal. I managed to do it by making a copy of the image file in the assets folder and converting it into a File. You could do something like this:
File f = new File(getCacheDir()+"/app_logo.png");
if (!f.exists()) try {
InputStream is = getAssets().open("R.drawable.app_logo");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
FileOutputStream fos = new FileOutputStream(f);
fos.write(buffer);
fos.close();
} catch (Exception e) { throw new RuntimeException(e); }
sharePicture = f.getPath();