PDF intent in android - java

while developing an android app , I am getting error "sorry we were unable to find the document at the original source" while using the following code : please advise
#Override
public boolean shouldOverrideUrlLoading( WebView view, String url ) {
if (url.contains(".pdf")){
Toast.makeText(view.getContext(), "chand", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(url), "application/pdf");
view.getContext().startActivity(intent);
//String googleDocs = "http://docs.google.com/gview?embedded=true&url=";
//view.loadUrl(googleDocs + url);
//Toast.makeText(view.getContext(), "chand", Toast.LENGTH_LONG).show();
//String pdfurl = "http://docs.google.com/gview?embedded=true&url=" + url;
//Log.i(TAG, "Opening PDF: " + url);
//view.getSettings().setJavaScriptEnabled(true);
//view.loadUrl(pdfurl);
}
return false;
}

To use that intent you need to download the PDF to the device onto the sdcard then give the uri to the pdf on the sd card in the intent.

Related

How to play recorded video in another Activity by passing in intent in android studio?

I am recording a video and passing its path into VideoView Activity. But the video can't be opened. Can anyone please help?
RecordActivity - video path function-:
public static String getVideoFilePath() {
return getAndroidMoviesFolder().getAbsolutePath() + "/" + new SimpleDateFormat("yyyyMM_dd-HHmmss").format(new Date()) + "rangeela.mp4";
}
Its returning ->
file:///storage/emulated/0/DCIM/202209_02-231740rangeela.mp4
File mediaFile = new File(getVideoFilePath());
Uri uri= Uri.fromFile(mediaFile);
Intent intent=new Intent(this,VideoEditorActivity.class);
intent.putExtra("uri",uri.toString());
startActivity(intent);
VideoViewActivity
Bundle bundle=getIntent().getExtras();
if(bundle!=null){
Uri uri=Uri.parse(bundle.getString("uri"));
Log.e("video path = ", String.valueOf(uri));
binding.videoView.setVideoURI(uri);
binding.videoView.start();
}
But I am getting an error
Can't play this video
How to pass the recorded video in intent and play in another activity?
Try this
String path = getAndroidMoviesFolder().getAbsolutePath() + "/" + new SimpleDateFormat("yyyyMM_dd-HHmmss").format(new Date()) + "rangeela.mp4";
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(this,VideoEditorActivity.class);
intent.putExtra("video",path);
}
});
VideoViewActivity
VideoView view = findViewById(R.id.videoview);
String path = getIntent().getStringExtra("video");
view.setVideoPath(path);
view.start();

"market://details?id=" + appPackageName opens the app not the playstore page

i asked a question on how should i open the playstore page using an app link on my app. i got an answer to use "market://details?id=" + appPackageName to open the play store app but instead of opening the playstore page its re opening my app. whats the fix?
enter code here
protected void Updateclick(View view) {
String appPackageName="io.kodular.samithuaz.smartQ";
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
}
Try this.You need to specify proper store URI for the different stores.
take reference link
protected void Updateclick(View view) {
final String appPackageName = getPackageName();
try {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id=" + appPackageName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
}
}
what i was using was an image click that why it didnt worked. when i used a button click it worked.

How to upload images gotten from camera using Android Upload Service

I have been able to make users upload photos to server taken from their gallery, but when a user uses camera to capture live and upload, I get this error unsupported scheme: file::///storage/...
I am using android upload service library
implementation "net.gotev:uploadservice:3.5.2"
I searched and discovered that file:// scheme is not allowed to be attached with Intent.
1. Selecting image from camera on button click
capture_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
FileProvider.getUriForFile(UploadActivity2.this, BuildConfig.APPLICATION_ID + ".provider",
createImageFile()));
startActivityForResult(intent, 0);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
2. Getting the image captured
if (resultCode == Activity.RESULT_OK)
switch (requestCode){
case 0:
try {
Uri cameraPath = FileProvider.getUriForFile(UploadActivity2.this,
BuildConfig.APPLICATION_ID + ".provider", createImageFile());
String stringUri = cameraPath.toString();
selectedImages.add(stringUri);
}catch (IOException ex) {
ex.printStackTrace();
Glide.with(this)
.load(cameraFilePath)
.into(display_image);
break;
}
}
As you see, I am using file provider to get Uri and storing the uri in a variable called selectedimages so I can pass it through an intent to another activity where the upload occurs
createImageFile method
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.UK).format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
//This is the directory in which the file will be created. This is the default location of Camera photos
File storageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM), "Camera");
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for using again
cameraFilePath = "file://" + image.getAbsolutePath();
return image;
}
3. Passing intent PATH, to uploadActivity
next_upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(UploadActivity2.this, UploadActivity3.class);
intent.putStringArrayListExtra("PATH", selectedImages);
startActivity(intent);
}
});
5. UploadAcvity where the upload happens
public void upload() {
ArrayList<String> selectedImages = getIntent().getStringArrayListExtra("PATH");
try {
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
new MultipartUploadRequest(this, uploadId, EndPoints.UPLOAD_URL)
.addFileToUpload(selectedImages.get(0), "image") //Adding file
.addParameter("caption", captionx) //Adding text parameter to the request
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(0)
.startUpload(); //Starting the upload
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}
Using this.
a. The image is not displaying in point 2 using Glide.with(this)
.load(cameraFilePath)
.into(display_image);
b. The image uploads but it is an empty file of 0 bytes.
But when I change the value of the variable of selectedImages in point 2 from selectedImages.add(stringUri); to selectedImages.add(cameraFilePath);
b. After clicking upload, I get error unsupported scheme: file::///storage/
Found the answer.
1. In the createImageFile method. I had to get the coontent:// url from the captured file using -
File newFile = new File(storageDir, image.getName());
contentUrl = FileProvider.getUriForFile(UploadActivity2.this,
BuildConfig.APPLICATION_ID + ".provider", newFile);
stringContentUrl = contentUrl.toString();
2. Then I passed the stringContentUrl into selected images String while getting the image captured.
selectedImages.add(stringContentUrl);
3. Passed it through an intent Extra and called it in the uploadActivity as seen in point 3 and 4 in the question.

How can I send message to specific contact through WhatsApp from my android app?

I am developing an android app and I need to send a message to specific contact from WhatsApp.
I tried this code:
Uri mUri = Uri.parse("smsto:+999999999");
Intent mIntent = new Intent(Intent.ACTION_SENDTO, mUri);
mIntent.setPackage("com.whatsapp");
mIntent.putExtra("sms_body", "The text goes here");
mIntent.putExtra("chat",true);
startActivity(mIntent);
The problem is that the parameter "sms_body" is not received on WhatsApp, though the contact is selected.
There is a way. Make sure that the contact you are providing must be passed as a string in intent without the prefix "+". Country code should be appended as a prefix to the phone number .
e.g.: '+918547264285' should be passed as '918547264285' . Here '91' in beginning is country code .
Note :Replace the 'YOUR_PHONE_NUMBER' with contact to which you want to send the message.
Here is the snippet :
Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.setComponent(new ComponentName("com.whatsapp","com.whatsapp.Conversation"));
sendIntent.putExtra("jid", PhoneNumberUtils.stripSeparators("YOUR_PHONE_NUMBER")+"#s.whatsapp.net");
startActivity(sendIntent);
Update:
The aforementioned hack cannot be used to add any particular message, so here is the new approach. Pass the user mobile in international format here without any brackets, dashes or plus sign. Example: If the user is of India and his mobile number is 94xxxxxxxx , then international format will be 9194xxxxxxxx. Don't miss appending country code as a prefix in mobile number.
private fun sendMsg(mobile: String, msg: String){
try {
val packageManager = requireContext().packageManager
val i = Intent(Intent.ACTION_VIEW)
val url =
"https://wa.me/$mobile" + "?text=" + URLEncoder.encode(msg, "utf-8")
i.setPackage("com.whatsapp")
i.data = Uri.parse(url)
if (i.resolveActivity(packageManager) != null) {
requireContext().startActivity(i)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
Note: This approach works only with contacts added in user's Whatsapp
account.
This new method, send message to a specific contact via whatsapp in Android. For more information look here
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_VIEW);
String url = "https://api.whatsapp.com/send?phone=" + number + "&text=" + path;
sendIntent.setData(Uri.parse(url));
activity.startActivity(sendIntent);here
I found the right way to do this and is just simple after you read this article: http://howdygeeks.com/send-whatsapp-message-unsaved-number-android/
phone and message are both String.
Source code:
try {
PackageManager packageManager = context.getPackageManager();
Intent i = new Intent(Intent.ACTION_VIEW);
String url = "https://api.whatsapp.com/send?phone="+ phone +"&text=" + URLEncoder.encode(message, "UTF-8");
i.setPackage("com.whatsapp");
i.setData(Uri.parse(url));
if (i.resolveActivity(packageManager) != null) {
context.startActivity(i);
}
} catch (Exception e){
e.printStackTrace();
}
Enjoy!
Great hack Rishabh, thanks a lot, I was looking for this solution since last 3 years.
As per the Rishabh Maurya's answer above, I have implemented this code which is working fine for both text and image sharing on WhatsApp. I have published this in my android app, so if you want to see it live try my app Bill Book
Note that in both the cases it opens a whatsapp conversation (if toNumber exists in users whatsapp contact list), but user have to click send button to complete the action. That means it helps in skipping contact selection step.
For text messages
String toNumber = "+91 98765 43210"; // contains spaces.
toNumber = toNumber.replace("+", "").replace(" ", "");
Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.putExtra("jid", toNumber + "#s.whatsapp.net");
sendIntent.putExtra(Intent.EXTRA_TEXT, message);
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setPackage("com.whatsapp");
sendIntent.setType("text/plain");
startActivity(sendIntent);
For sharing images
String toNumber = "+91 98765 43210"; // contains spaces.
toNumber = toNumber.replace("+", "").replace(" ", "");
Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(imageFile));
sendIntent.putExtra("jid", toNumber + "#s.whatsapp.net");
sendIntent.putExtra(Intent.EXTRA_TEXT, message);
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setPackage("com.whatsapp");
sendIntent.setType("image/png");
context.startActivity(sendIntent);
Enjoy WhatsApping!
We can share/send message to whats app. Below is Sample code to send text message on Whats-app
Single user
private void shareToOneWhatsAppUser(String message) {
/**
* NOTE:
* Message is shared with only one user at a time. and to navigate back to main application user need to click back button
*/
Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
whatsappIntent.setType("text/plain");
whatsappIntent.setPackage("com.whatsapp");
whatsappIntent.putExtra(Intent.EXTRA_TEXT, message);
//Directly send to specific mobile number...
String smsNumber = "919900990099";//Number without with country code and without '+' prifix
whatsappIntent.putExtra("jid", smsNumber + "#s.whatsapp.net"); //phone number without "+" prefix
if (whatsappIntent.resolveActivity(getPackageManager()) == null) {
Toast.makeText(MainActivity.this, "Whatsapp not installed.", Toast.LENGTH_SHORT).show();
return;
}
startActivity(whatsappIntent);
}
Multiple user
private void shareToMultipleWhatsAppUser(String message) {
/**
* NOTE:
*
* If want to send same message to multiple users then have to select the user to whom you want to share the message & then click send.
* User navigate back to main Application once he/she select all desired persons and click send button.
* No need to click Back Button!
*/
Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
whatsappIntent.setType("text/plain");
whatsappIntent.setPackage("com.whatsapp");
whatsappIntent.putExtra(Intent.EXTRA_TEXT, message);
if (whatsappIntent.resolveActivity(getPackageManager()) == null) {
Toast.makeText(MainActivity.this, "Whatsapp not installed.", Toast.LENGTH_SHORT).show();
return;
}
startActivity(whatsappIntent);
}
One more way to achieve the same
private void shareDirecctToSingleWhatsAppUser(String message) {
/**
* NOTE:
* Message is shared with only one user at a time. and to navigate back to main application user need to click back button
*/
//Directly send to specific mobile number...
String smsNumber = "919900000000";//Intended user`s mobile number with country code & with out '+'
PackageManager packageManager = getPackageManager();
Intent i = new Intent(Intent.ACTION_VIEW);
try {
String url = "https://api.whatsapp.com/send?phone="+ smsNumber +"&text=" + URLEncoder.encode("Test Message!", "UTF-8");
i.setPackage("com.whatsapp");
i.setData(Uri.parse(url));
if (i.resolveActivity(packageManager) != null) {
startActivity(i);
}
} catch (Exception e){
e.printStackTrace();
}
}
you can use this code:
Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setPackage("com.whatsapp");
sendIntent.setType("text/plain");
sendIntent.putExtra("jid", "9194******22" + "#s.whatsapp.net");// here 91 is country code
sendIntent.putExtra(Intent.EXTRA_TEXT, "Demo test message");
startActivity(sendIntent);
This is the best way to send Message through Whatsapp to specific number or unsaved number
private void openWhatsApp() {
String smsNumber = "252634651588";
boolean isWhatsappInstalled = whatsappInstalledOrNot("com.whatsapp");
if (isWhatsappInstalled) {
Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.setComponent(new ComponentName("com.whatsapp", "com.whatsapp.Conversation"));
sendIntent.putExtra("jid", PhoneNumberUtils.stripSeparators(smsNumber) + "#s.whatsapp.net");//phone number without "+" prefix
startActivity(sendIntent);
} else {
Uri uri = Uri.parse("market://details?id=com.whatsapp");
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
Toast.makeText(getContext(), "WhatsApp not Installed",
Toast.LENGTH_SHORT).show();
startActivity(goToMarket);
}
}
private boolean whatsappInstalledOrNot(String uri) {
PackageManager pm = Objects.requireNonNull(getContext()).getPackageManager();
boolean app_installed = false;
try {
pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
app_installed = true;
} catch (PackageManager.NameNotFoundException e) {
app_installed = false;
}
return app_installed;
}
This is what works for me.
The parameter 'body' gets not red by the whatsapp app, use 'Intent.EXTRA_TEXT' instead.
By setting the 'phoneNumber' you specify the contact to open in whatsapp.
Intent sendIntent = new Intent(Intent.ACTION_SENDTO,
Uri.parse("smsto:" + "" + phoneNumber + "?body=" + encodedMessage));
sendIntent.putExtra(Intent.EXTRA_TEXT, message);
sendIntent.setPackage("com.whatsapp");
startActivity(sendIntent);
Uri mUri = Uri.parse("smsto:+90000900000");
Intent mIntent = new Intent(Intent.ACTION_SENDTO, mUri);
mIntent.setPackage("com.whatsapp");
mIntent.putExtra("chat",true);
startActivity(Intent.createChooser(mIntent, "Share with"));
Works great to send message to specific contact on WhatsApp from my android app
Try this code
Uri uri = Uri.parse("smsto:" + "+6281122xxx");
Intent i = new Intent(Intent.ACTION_SENDTO, uri);
i.putExtra(Intent.EXTRA_TEXT, getResources().getString(R.string.default_message_wa));
i.setPackage("com.whatsapp");
startActivity(Intent.createChooser(i, ""));
You can't put string directly on putExtra like this
i.putExtra(Intent.EXTRA_TEXT, "YOUR TEXT");
Change your code and get string from resource like this
i.putExtra(Intent.EXTRA_TEXT, getResources().getString(R.string.default_message_wa));
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_VIEW);
String url ="https://wa.me/your number";
sendIntent.setData(Uri.parse(url));
startActivity(sendIntent);
Here's my way to do it (more here):
First, if you want to be sure you can send the message, you can check if the person has a WhatsApp account on the address book:
#RequiresPermission(permission.READ_CONTACTS)
public String getContactMimeTypeDataId(#NonNull Context context, String contactId, #NonNull String mimeType) {
if (TextUtils.isEmpty(mimeType) || !PermissionUtil.hasPermissions(context, Manifest.permission.READ_CONTACTS))
return null;
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(ContactsContract.Data.CONTENT_URI, new String[]{Data._ID}, Data.MIMETYPE + "= ? AND "
+ ContactsContract.Data.CONTACT_ID + "= ?", new String[]{mimeType, contactId}, null);
if (cursor == null)
return null;
if (!cursor.moveToFirst()) {
cursor.close();
return null;
}
String result = cursor.getString(cursor.getColumnIndex(Data._ID));
cursor.close();
return result;
}
and if all seem well, you open it as if it's from the web:
final String contactMimeTypeDataId = getContactMimeTypeDataId(context, contactId, "vnd.android.cursor.item/vnd.com.whatsapp.profile");
if (contactMimeTypeDataId != null) {
final String whatsAppPhoneNumber = PhoneNumberHelper.normalizePhone(phoneNumber);
String url = "https://api.whatsapp.com/send?phone="+ whatsAppPhoneNumber ;
intent = new Intent(Intent.ACTION_VIEW,Uri.parse(url));
intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET | Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
.setPackage("com.whatsapp");
startActivity(intent);
}
You can also check if WhatsApp is even installed before of all of this (or remove the setPackage and check if any app can handle the Intent) :
final PackageManager packageManager = context.getPackageManager();
final ApplicationInfo applicationInfo = packageManager.getApplicationInfo("com.whatsapp", 0);
if (applicationInfo == null)
return;
EDIT: about preparing the Intent with the Uri, I think this way is better:
#JvmStatic
fun prepareWhatsAppMessageIntent(normalizedPhoneNumber: String?, message: String? = null): Intent {
// example url: "https://api.whatsapp.com/send?phone=normalizedPhoneNumber&text=abc"
val builder = Uri.Builder().scheme("https").authority("api.whatsapp.com").path("send")
normalizedPhoneNumber?.let { builder.appendQueryParameter("phone", it) }
message?.let { builder.appendQueryParameter("text", it) }
return Intent(Intent.ACTION_VIEW, builder.build())
}
or alternative (based on here):
fun prepareWhatsAppMessageIntent(normalizedPhoneNumber: String?, message: String? = null): Intent {
// example url: "https://wa.me/normalizedPhoneNumber&text=abc"
val builder = Uri.Builder().scheme("https").authority("wa.me")
normalizedPhoneNumber?.let { builder.appendPath(it) }
message?.let { builder.appendQueryParameter("text", it) }
return Intent(Intent.ACTION_VIEW, builder.build())
}
Try using Intent.EXTRA_TEXT instead of sms_body as your extra key. Per WhatsApp's documentation, this is what you have to use.
An example from their website:
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);
Their example uses Intent.ACTION_SEND instead of Intent.ACTION_SENDTO, so I'm not sure if WhatsApp even supports sending directly to a contact via the intent system. Some quick testing should let you determine that.

QR Code Decoder, address issue of variables

How would I be able to call a string from one activity to another?
My code isn't working, I am trying to achieve a program that can browse
the images on the SD card of my phone and return the address of the image.
I am developing a QR Code decoder based on the zxing library.
private void onFileClick(Option o)
{
//Toast.makeText(this, "File Clicked: "+o.getName(), Toast.LENGTH_SHORT).show();
Toast.makeText(this, "File Clicked: "+o.getPath(), Toast.LENGTH_SHORT).show();
QRDecoder qr = null;
str = o.getPath();
qr.setFile(str);
Intent intent = new Intent(this, QRDecoder.class);
Log.d("filter", str);
Log.d("filter", qr.my_url);
startActivity(intent);
}
before calling startActivity
intent.putExtra("path", str);
in onCreate of the QRDecoder
String path = getIntent().getStringExtra("path");

Categories

Resources