Share video from Android raw folder to any app - java

I am making one app to allow user to share all video from any sharing app. My issue is file attached successfully but the file content is not attaching. below is my full source code. Let me know where I am making a mistake.
private void shareVideo() {
Intent localIntent = new Intent("android.intent.action.SEND");
Uri localUri = Uri.fromFile(new File(CorporateAdaptor.this.rawVideoId + ".mp4"));
String str = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(localUri.toString()));
localIntent.setType(str);
localIntent.setAction("android.intent.action.SEND");
if (str == null) {
str = "*/*";
}
localIntent.setType(str);
localIntent.putExtra("android.intent.extra.STREAM", localUri);
CorporateAdaptor.this.mContext.startActivity(Intent.createChooser(local Intent, "Where you want to share?"));
}
This is my code that was I am using when user click on the share button. It will open a share dialog and when I select the gmail app, the file is attached but it's showing me a toast message "Couldn't find attachment". And when I click on send email file was not sending.

Related

Can't play video in videoview android studio?

I know that there is too many solutions were given, but I can't get the exact solution. My problem is that I have picked one video from internal storage device and after picking video then I have converted to String and set the video to videoView but then also it shows that "Can't play this video" in videoView.
can anyone please help me to find out the solution :(
here is my code
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Download/videos.mp4");
Log.d("video",""+file);
if (file.exists()) {
Uri uri = Uri.fromFile(file);
String video = String.valueOf(uri);
Log.d("video",""+uri);
videoView.setMediaController(new MediaController(this));
videoView.setVideoURI(Uri.parse(video));
videoView.requestFocus();
videoView.start();
}else {
Toast.makeText(this, "No video found", Toast.LENGTH_SHORT).show();
}
With scoped storage (required from API 30) you can't access files directly unless you request the MANAGE_EXTERNAL_STORAGE (on Google Play you need to request it to Google).
The new way is to use the file uri. You can try those ways:
Ask the user to select the file.
private final ActivityResultLauncher<String[]> openDoc =
registerForActivityResult(new ActivityResultContracts.OpenDocument(),
new ActivityResultCallback<Uri>() {
#Override
public void onActivityResult(Uri uri) {
// use uri
}
});
Call it with:
// Use the mimetype you want (optional). Like "text/plain"
openDoc.launch(new String[]{"text/plain"});
Read more here
Get the Media file uri with MediaStore
Read more here
You'll also need the READ_EXTERNAL_STORAGE permission if the file was not created by your app.

How to send app invites from my application (via whatsapp,hike,message)

I am new for Android. I created a simple food app. I want to send invitation to my friends from my app via Whatsapp, message etc. while clicking the invite button. I don't have any idea about that. Can you anyone guide me (Show some examples means more helpful to me).
Thanks in advance!
Refer this link
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");
startActivity(sendIntent);
private void onShareClicked() {
String link = "https://play.google.com/store/apps/details?id=com.recharge2mePlay.recharge2me";
Uri uri = Uri.parse(link);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, link.toString());
intent.putExtra(Intent.EXTRA_TITLE, "Recharge2me");
startActivity(Intent.createChooser(intent, "Share Link"));
}
And simply call this function in onClickListner.
btn_tellAFreind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onShareClicked();
}
});
try this tutorial from google using Firebase, maybe this can help you:
https://codelabs.developers.google.com/codelabs/firebase-android/#10
You can generate short link by using the following codes:
DynamicLink dynamicLink = FirebaseDynamicLinks.getInstance().createDynamicLink()
.setLink(Uri.parse("https://play.google.com/store/apps/details?id=com.example"))
.setDynamicLinkDomain("abc.app.goo.gl")
.setAndroidParameters(new DynamicLink.AndroidParameters.Builder().build())
.buildDynamicLink();
Task<ShortDynamicLink> shortLinkTask = FirebaseDynamicLinks.getInstance().createDynamicLink()
.setLongLink(dynamicLink.getUri())
.buildShortDynamicLink()
.addOnCompleteListener(ReferrerActivity.this, new OnCompleteListener<ShortDynamicLink>() {
#Override
public void onComplete(#NonNull Task<ShortDynamicLink> task) {
if (task.isSuccessful()) {
Uri shortLink = task.getResult().getShortLink();
Uri flowchartLink = task.getResult().getPreviewLink();
Log.i(TAG, "onComplete: SHORTLINK " + shortLink.toString());
Log.i(TAG, "onComplete: FLOW LINK " + flowchartLink.toString());
} else {
Log.i(TAG, "onComplete: ERROR " + task.isSuccessful() + " " + task.isComplete());
}
}
});
Once you received the short link in onComplete method, share it using intent.
Firebase Invites are an out-of-the-box solution for app referrals and sharing via email or SMS.
Connect your app to your Firebase project from Firebase console
Enabled Firebase Dynamic Links from the Firebase console by opening the Dynamic Links section and accepting the terms of service if prompted.
Add Firebase to your Android project
Add the dependency for Firebase Invites to your app-level build.gradle file:
compile 'com.google.firebase:firebase-invites:10.0.1'
Send invitations:
Start by building an Intent using the AppInviteInvitation.IntentBuilder class:
Intent intent = new AppInviteInvitation.IntentBuilder(getString(R.string.invitation_title))
.setMessage(getString(R.string.invitation_message))
.setDeepLink(Uri.parse(getString(R.string.invitation_deep_link)))
.setCustomImage(Uri.parse(getString(R.string.invitation_custom_image)))
.setCallToActionText(getString(R.string.invitation_cta))
.build();
startActivityForResult(intent, REQUEST_INVITE);
Launching the AppInviteInvitation intent opens the contact chooser where the user selects the contacts to invite. Invites are sent via email or SMS. After the user chooses contacts and sends the invite, your app receives a callback to onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, "onActivityResult: requestCode=" + requestCode + ", resultCode=" + resultCode);
if (requestCode == REQUEST_INVITE) {
if (resultCode == RESULT_OK) {
// Get the invitation IDs of all sent messages
String[] ids = AppInviteInvitation.getInvitationIds(resultCode, data);
for (String id : ids) {
Log.d(TAG, "onActivityResult: sent invitation " + id);
}
} else {
// Sending failed or it was canceled, show failure message to the user
// ...
}
}
}
Check out here for more details about Send and Receive Firebase Invites from Your Android App
Update:
Use Branch sdk to support invite feature on another platform like WhatsApp, Facebook and other social media apps.
Check out here to know How branch link works?
Checkout here for Install guide & code example
If I understand the question correctly, you want to make the share differentiate when the user clicks share and if he selects to invite via WhatsApp, for example, it will show only Whatsapp as a medium option to share the invite through.
If that is what you want, you should to set the package in the intent you will use for sharing, so if we add to #Vishal answer above
sendIntent.setPackage("com.whatsapp");
You should do the same for any needed social media
You need to add Firebase Dynamic link. Earlier it was Firebase Invites but it is depreciated now. Firebase Dymanic Link is build over Firebase Invites So you can see the invites dependency on gradle file.
You can follow this tutorial for complete example about "How to Create Refer a friend Link"
There is Two ways to create "Refer a Friend Link"
Using Firebase base Dynamic Object
Manually Create Refer a Link
1) Option :-
DynamicLink dynamicLink = FirebaseDynamicLinks.getInstance().createDynamicLink()
.setLink(Uri.parse("https://www.example.com/"))
//.setDomainUriPrefix("https://example.page.link") // no longer in user please
.setDynamicLinkDomain("example.page.link") // use this code and don't use https:// here
// Open links with this app on Android
.setAndroidParameters(new DynamicLink.AndroidParameters.Builder().build())
// Open links with com.example.ios on iOS
.setIosParameters(new DynamicLink.IosParameters.Builder("com.example.ios").build())
.buildDynamicLink();
Uri dynamicLinkUri = dynamicLink.getUri();
2) Option:-
String sharelinktext = "https://referearnpro.page.link/?"+
"link=https://www.blueappsoftware.com/"+
"&apn="+ getPackageName()+
"&st="+"My Refer Link"+
"&sd="+"Reward Coins 20"+
"&si="+"https://www.blueappsoftware.com/logo-1.png";
Then Call ShortDynamicLink Object
Refer Link will be look like this :
https://referearnpro.page.link?apn=blueappsoftware.referearnpro&link=https%3A%2F%2Fwww.blueappsoftware.com%2F
You can check complete example here
a custom method to send invites, also according to the best practice in Android Developers
fun inviteToDownloadApp(context: Context) {
val intent = Intent(Intent.ACTION_SEND)
intent.type = "text/plain"
intent.putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.app_name))
intent.putExtra(Intent.EXTRA_TEXT, context.getString(R.string.invite_to_download_app))
context.startActivity(Intent.createChooser(intent, context.getString(R.string.invite_to_download_app)))
}

Android - Send Telegram message to a specific number

I'm trying to send a Telegram message to a specific number from within my Android app. Right now my code launches Telegram app, and then the user has to select the destinatary. What I want to do is to send the message to the specified number, without having the user select the contact. My code is as follows:
/**
* Intent to send a telegram message
* #param msg
*/
void intentMessageTelegram(String msg)
{
final String appName = "org.telegram.messenger";
final boolean isAppInstalled = isAppAvailable(mUIActivity.getApplicationContext(), appName);
if (isAppInstalled)
{
Intent myIntent = new Intent(Intent.ACTION_SEND);
myIntent.setType("text/plain");
myIntent.setPackage(appName);
myIntent.putExtra(Intent.EXTRA_TEXT, msg);//
mUIActivity.startActivity(Intent.createChooser(myIntent, "Share with"));
}
else
{
Toast.makeText(mUIActivity, "Telegram not Installed", Toast.LENGTH_SHORT).show();
}
}
You can't send to special number, But You can do this by USERID
try {
Intent telegramIntent = new Intent(Intent.ACTION_VIEW);
telegramIntent.setData(Uri.parse("http://telegram.me/USERID"));
startActivity(telegramIntent);
} catch (Exception e) {
// show error message
}
This code will show user an alert for choosing applications that support telegram uri's like Telegram itself and Mobogram!
Tip: don't set package name. some people install telegram alternatives like mobogram.
The Telegram Android App does not have a way to send messages directly to telegram users, so if you use the share intent, you'll get what telegram / any other app wants to do with the message shared. In this case, open the contact list to send this message to him.
If you want to send messages directly to Telegram users you should use the Telegram API
https://core.telegram.org/api#getting-started
once you have configured your API key in your app, you could send messages, read them or even get the telegram contacts with these methods
https://core.telegram.org/methods
This one worked for me:
try {
Intent telegram = new Intent(Intent.ACTION_VIEW, Uri.parse("https://t.me/USER_NAME"));
telegram.setPackage("org.telegram.messenger");
startActivity(telegram);
}catch (Exception e)
{
Toast.makeText(getContext(), "Telegram app is not installed", Toast.LENGTH_LONG).show();
}
Tip: You can get USER_NAME by click on you telegram profile option you will get option of username in Account session --> if username is none create unique username and put here its work for me.
This one worked for me:
//check if application is installed first before running this code.
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://telegram.me/+UT_USER_ID_HERE"));
final String appName = "org.telegram.messenger";
i.setPackage(appName);
this.startActivity(i);
try the intent like this
tg://resolve?domain=YOUR_USER_ID
it's more direct then https://t.me
I'm using this for send message on background :
this cod is api telegram for use send message by url token bot
1 - use WebView on xml like this :
<WebView
android:id="#+id/webView_sendToTelegram"
android:layout_width="0dp"
android:layout_height="0dp"/>
2 - on java use this cod:
public static void SendMessageToBotTelegram(String chatID, String text, String botToken,WebView webView) {
webView.loadUrl(MessageFormat.format("https://api.telegram.org/bot{0}/sendMessage?chat_id={1}&text={2}", botToken, chatID, text));
}
chatID : your telegram id #RawDataBot for get id
text : text your message
botToken : your bot for get message if you don't have bot using #BotFather for crate bot
webView : your id WebView on xml

How can I delete a pre-existing image from storage before re-downloading using DownloadManager?

I am writing code for an Android app using Eclipse that is supposed to download an image from a URL (which is generated by the app, elsewhere in the code, using GPS information), then attach the newly downloaded image to an e-mail to be sent. I am able to, in general, accomplish this without much issue.
My problem is this: I only want one image downloaded by the app to be present in the device's external storage at any given time. Deleting the image after the email intent does not work, because because the app doesn't always call onStop or onDestroy when switching to another app to send the email. Time-sensitive deleting of the image will not work either, because I cannot assume that the user will send only one email from the app per hour. I want to give the user the freedom of sending as many of these emails (with one newly downloaded image, each) as they wish.
My current method (which works MOST of the time) is this: in the downloadFile method, simply check for the file's existence (I call it sensorMap.png), then delete it if it exists, before downloading a new one. This SHOULD ensure that there may be only one sensorMap.png image in external storage at any given time (EDIT: it does do this), and that when it comes time to attach the image to the email intent, there will be exactly one image ready to go. Instead, I see that sometimes a second sensorMap image is sometimes being downloaded into storage (i.e. "sensorMap-1.png"), OR the image cannot be attached to the email due to a "File size: 0 bytes" error, OR the image cannot be attached due to a "File does not exist" error. I am unsure what the difference between the latter two problems is. EDIT: Upon manually examining the contents of the directory I created, it seems that, as intended, I end up with only one image titled "sensorMap.png" at a time; it remains in the directory after the app closes, as expected. However, I still occasionally get the "File size: 0 bytes" message or the "File does not exist." message with no attached image, even though I see that the image DOES exist upon looking in directory afterwards. Other times, everything works just fine. It's rather bewildering.
In addition, there is an issue of the button which sends the email becoming unresponsive occasionally. Most of the time, it prompts the user to select an email client, as intended, but occasionally the button will LOOK as if clicked, but do nothing. When this happens, the logcat does not sense that the button was even clicked (I inserted a println statement to test it).
I am unsure of why my delete-before-download is not working flawlessly; the basic idea, at least, appears to be logically sound. Here is the code pertaining to my issue:
Code used to download file (in MainCountActivity.java):
//Function to download image given URL. Will use to attach image file to email.
public void downloadFile(String uRl) {
//delete existing file first so that only one sensorMap image exists in memory
//at any given time.
File file = new File(Environment.getExternalStorageDirectory()+"/SensorLocationImages");
File checkFile = new File(Environment.getExternalStorageDirectory()+"/SensorLocationImages/sensorMap.png");
if(checkFile.exists())
{
//debugging:
System.out.println("About to delete file!");
//deleteFiles(Environment.getExternalStorageDirectory()+"/SensorLocationImages");
checkFile.delete();
}
DownloadManager mgr = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = Uri.parse(uRl);
DownloadManager.Request request = new DownloadManager.Request(
downloadUri);
request.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false).setTitle("Sensor Location Map")
.setDescription("Pinpointed is the location from which the log file was sent.")
.setDestinationInExternalPublicDir("/SensorLocationImages", "sensorMap.png");
mgr.enqueue(request);
}
public Activity getActivity() //I wasn't sure if this would work, but it did. Or at least appears to.
{ return this; }
Method to send email (in MainCountActivity.java):
public void sendEmail(String toAddress, String ccAddress, String bccAddress, String subject, String body, String attachmentMimeType) throws Exception{
try {
Intent emailIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
emailIntent.setType(attachmentMimeType); //new
String sToAddress[] = { toAddress };
String sCCAddress[] = { ccAddress};
String sBCCAddress[] = { bccAddress };
emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
emailIntent.putExtra(Intent.EXTRA_EMAIL, sToAddress);
emailIntent.putExtra(android.content.Intent.EXTRA_CC, sCCAddress);
emailIntent.putExtra(android.content.Intent.EXTRA_BCC, sBCCAddress);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_TEXT, body);
//get URI of logfile
File tempFile = new File(Environment.getExternalStorageDirectory () + MainCountActivity.dirPath);
Uri uri = Uri.fromFile(tempFile);
//create URI arraylist and add first URI
ArrayList<Uri> uris = new ArrayList<Uri>();
uris.add(uri);
//get URI of map image and add to arraylist
//make sure it is there to attach
File file = new File(Environment.getExternalStorageDirectory()+"/SensorLocationImages");
do {
downloadFile(getMapLink());
//createDirectoryAndSaveFile(getBitmapFromURL(getMapLink()), "sensorMap.png");
} while (!file.exists());
uris.add(Uri.fromFile(new File(Environment
.getExternalStorageDirectory()
+ "/SensorLocationImages/sensorMap.png")));
//+ "/sdcard/SensorLocationImages/sensorMap.png")));
emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
startActivity(emailIntent);
}
catch(Exception ex) {
ex.printStackTrace();
throw ex;
}
}
OnClick method, for my occasional button issue (In MaincountActivity.java):
public void onClick(View v){
switch(v.getId())
{
case R.id.textView1:
{
break;
}
case R.id.Reset:
{
//allowCounting will let the program know when to let it to count or not, depending if Start or Stop button are pressed.
logCount=0;
mCounter.setText("Total: 0");
mToggle.setChecked(false);
break;
}
/* case R.id.toggleButton:
{
break;
}*/
case R.id.SendEmail:
{
//for debugging purposes:
System.out.println("Email button being clicked!");
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
Toast.makeText(this, "GPS is enabled in your device", Toast.LENGTH_SHORT).show();
try {
sendEmail("","","","Sensor Log Info",getEmailBody(),"multipart/mixed");
} catch (Exception e) {
e.printStackTrace();
}
}
else
{
showGPSAlertForEmail();
}
break;
}
}
Basically, I really want to know why my delete-then-download method has not worked every time. Logcat errors have provided no insight. Thank you for your time.

Save Uri as a file android

So in my app it is receiving an image from another application
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
if (Intent.ACTION_SEND.equals(action) && type != null) {
handleSendImage(intent); // Handle single image being sent
public void handleSendImage(Intent a)
{
Uri pic = (Uri) a.getParcelableExtra(Intent.EXTRA_STREAM);
}
From here I want to save the Uri as an image in my image gallery.
I know how to save a file in the gallery I am just not sure how I get the Uri in the correct format to save it. I know it contains the image because picView.setImageURI(pic); causes the picture to appear in my activity. I just want to be able to save that image into the gallery. Any ideas on how I would do that? I thought that I could convert the ImageView to a bitmap and go from there but that seems really inefficient to me and there has to be a better way to do it. Since I know you can create Uris from Files but can you create a File from a Uri?

Categories