I am creating a App, which should save reference documents, saved on the device.
I am receiving the content URI for these documents in the following way:
private void selectDocument() {
Intent chooseFile;
chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
chooseFile.addCategory(Intent.CATEGORY_OPENABLE);
chooseFile.setType("*/*");
if (chooseFile.resolveActivity(getPackageManager()) != null)
startActivityForResult(chooseFile, ACTIVITY_CHOOSE_FILE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (resultCode != RESULT_OK) return;
if (requestCode == ACTIVITY_CHOOSE_FILE) {
try {
binding.txtLink.setText(URLDecoder.decode(data.getDataString(),"UTF-8"));
binding.btnLink.setTag(false);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
after displaying the url to the user, he should be able to open the document.
And i am not really sure how to do that, since I only get the contentURI.
What i am currently trying is this:
private void openDocument() {
String file = binding.txtLink.getText().toString();
if (file.isEmpty()) {
return;
}
Intent intent;
String extension = file.substring(file.lastIndexOf(".") + 1);
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(file));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Snackbar.make(binding.root, "Keine Anwendung zum öffnen der Datei installiert", Snackbar.LENGTH_LONG).show();
}
}
This already opens the correct App, but they can't find the files.
What would i need to do, to enable this behavior?
Or do i have to copy the files to my app directory and open them from there?
Related
I have an updated app in my device storage. I have to install that upper version app from my existing lower version app in a button click. (Like the way dora tv users update their app)
I wrote this code.But it's showing - "There was a problem parsing the package".
There is no error in logcat & no exception. What i need to do now?
App Install error
#RequiresApi(api = Build.VERSION_CODES.M)
private void requestPermission() {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_PERMISSION);
}
private void havePermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
&& !getPackageManager().canRequestPackageInstalls()) {
Intent unknownAppSourceIntent = new Intent()
.setAction(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES)
.setData(Uri.parse(String.format("package:%s", getPackageName())));
startActivityForResult(unknownAppSourceIntent, Constants.APP_INSTALL_REQUEST);
//unknownAppSourceDialog.launch(unknownAppSourceIntent);
} else {
apkInstall();
}
}
private void apkInstall() {
String path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS).getPath() + File.separator + "test.apk";
Log.d("filePath", path);
File file = new File(path);
if (file.exists() && !file.isDirectory()) {
// do something
Log.d("fileExist", file.getName());
}
Intent intent;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri apkUri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", file);
intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
intent.setData(apkUri);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
} else {
Uri apkUri = Uri.fromFile(file);
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
try {
startActivityForResult(intent, Constants.APP_INSTALL_REQUEST);
} catch (Exception e) {
e.printStackTrace();
BizUiUtils.showToast(this, "Error in installing App, please try again");
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Constants.APP_INSTALL_REQUEST) {
apkInstall();
}
}
I have make payments through PayPal native android mobile sdk. Below is the success response
{"response":{"state":"approved","id":"PAY-someID","create_time":"2017-06-21T18:01:33Z","intent":"sale"},"client":{"platform":"Android","paypal_sdk_version":"2.15.3","product_name":"PayPal-Android-SDK","environment":"sandbox"},"response_type":"payment"}
But when back-end wants to verify with the payment id i.e PAY-someID, it is throwing error json like below every time
[debug] application - verifyPayment mitemreqCppverifpmtrequest(PAY-someID)
[debug] application - verifpmtrequest case mendpointt https://api.sandbox.paypal.com/v1/payments/payment/PAY-someID
[debug] application - tx.get.body{"name":"INVALID_RESOURCE_ID","message":"Requested resource ID was not found.","information_link":"https://developer.paypal.com/webapps/developer/docs/api/#INVALID_RESOURCE_ID","debug_id":"someID"}
Below is the android code
private static final String CONFIG_ENVIRONMENT = PayPalConfiguration.ENVIRONMENT_SANDBOX;
private static PayPalConfiguration config = new PayPalConfiguration()
.environment(CONFIG_ENVIRONMENT)
.clientId(CONFIG_CLIENT_ID)
// The following are only used in PayPalFuturePaymentActivity.
.merchantName("Example Merchant")
.merchantPrivacyPolicyUri(Uri.parse("https://www.example.com/privacy"))
.merchantUserAgreementUri(Uri.parse("https://www.example.com/legal"));
PayPalPayment thingToBuy = getThingToBuy(PayPalPayment.PAYMENT_INTENT_SALE);
Intent intent = new Intent(SampleActivity.this, PaymentActivity.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
startActivityForResult(intent, REQUEST_CODE_PAYMENT);
return new PayPalPayment(new BigDecimal("0.01"), "USD", "sample item",
paymentIntent);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PAYMENT) {
if (resultCode == Activity.RESULT_OK) {
PaymentConfirmation confirm =
data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirm != null) {
try {
Log.i(TAG, confirm.toJSONObject().toString(4));
}
}
}
The problem is similar to the below
https://github.com/paypal/PayPal-Android-SDK/issues/330
No idea how to solve this.
Try this one this is working code of my Google PlayStore application.
PayPalConfiguration config = new PayPalConfiguration().environment(PayPalConfiguration.ENVIRONMENT_SANDBOX).clientId("Your id");
Intent intent = new Intent(context, PayPalService.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
startService(intent);
PayPalPayment payment = new PayPalPayment(new BigDecimal(charge), "USD", eventName, PayPalPayment.PAYMENT_INTENT_SALE);
Intent intent = new Intent(activity, PaymentActivity.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, payment);
startActivityForResult(intent, 1089);
Don't Forget to stop service in OnDestroy().
#Override
protected void onDestroy() {
stopService(new Intent(this, PayPalService.class));
super.onDestroy();
}
Also stop service inside OnActivityResult When you perform all your task.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && requestCode == 1089) {
PaymentConfirmation confirm = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirm != null)
{
try
{
// Your code after successful response.
} catch (JSONException e) {
Log.error(getClass().getName(), e);
}
}
stopService(new Intent(this, PayPalService.class));
} else if (resultCode == Activity.RESULT_CANCELED) {
//
} else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
//
}
}
I am trying to add in my App a function to use the camera to store photos in my device.
At the beginning i use the camera like this:
mButtonCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count++;
String file = dir+prova+".jpg";
File newFile = new File(file);
try {
newFile.createNewFile();
}catch (IOException e){}
Uri outputFileUri = Uri.fromFile(newFile);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,outputFileUri);
Log.v("CameraDemo", "Pic savedNO");
startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
}
});
And then for the OnActivityResult:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
Log.v("CameraDemo", "Pic saved");
Log.v("Salva Foto", dir+prova+".jpg");
myDBHandler.addPhoto(prova,dir+prova+".jpg");
}
}
Until here evrything is ok but when I try to retrieve the photo using this:
InputStream URLcontent = null;
try {
URLcontent = (InputStream) new URL(fotoSI).getContent();
} catch (IOException e) {
e.printStackTrace();
}
Drawable image = Drawable.createFromStream(URLcontent, fotoSI);
mImageCamera.setImageDrawable(image);
It doesn´t return any photo that is what the Log says me:
java.net.MalformedURLException: Protocol not found: /storage/emulated/0/Pictures/
I am trying everything but without results.
This the code I am using to take picture, display it, then send it in an email:
private void takePicture() {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File photo = new File(Environment.getExternalStorageDirectory(),
getIntent().getStringExtra("counter"));
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(intent, 0);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 0:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ContentResolver cr = getContentResolver();
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
savePicture(getIntent().getStringExtra("counter"), bitmap,
getApplicationContext());
setImage();
Toast.makeText(this, selectedImage.toString(), Toast.LENGTH_LONG).show();
} catch (Exception e) {
}
}
}
}
How I send the email:
final Intent emailIntent = new Intent(
android.content.Intent.ACTION_SEND);
String fileName = null;
try {
fileName = URLEncoder.encode(getIntent().getStringExtra("counter"), "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String path = Environment.getExternalStorageDirectory()+"/"+fileName.trim().toString();
Uri uri = Uri.parse("file://"+path);
emailIntent.setType("image/png");
emailIntent.putExtra(android.content.Intent.EXTRA_STREAM, uri);
/* Send it off to the Activity-Chooser */
startActivity(Intent
.createChooser(emailIntent, "Send Email..."));
Notice, my file name should be getIntent().getStringExtra("counter");
When I do this, my email sends a text file rather than an image file. I have no clue why it does this...
I suspect this has happened to more than one person, but the problem was this:
I had to add +".jpg" to the end of the filename, and now it works. This may have been a simple solution but it surely was a distressful problem!
Hope this post still helps those who encounter this issue in the future.
I am working on speech recognition and need some sample programs.
Can anyone guide me?
Let me cut and paste a bit to show you what code you will need.
EDIT: you can also download a handy abstract class from this project.
You will need this intent (parameterize as you see fit):
public Intent getRecognizeIntent(String promptToUse, int maxResultsToReturn)
{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, maxResultsToReturn);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, promptToUse);
return intent;
}
Then you need to send your intent to the speech recognition activity like so,
public void gatherSpeech(String prompt)
{
Intent recognizeIntent = getRecognizeIntent(prompt);
try
{
startActivityForResult(recognizeIntent, SpeechGatherer.VOICE_RECOGNITION_REQUEST_CODE);
}
catch (ActivityNotFoundException actNotFound)
{
Log.w(D_LOG, "did not find the speech activity, not doing it");
}
}
Then you will need to have your activity handle the speech result:
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
Log.d("Speech", "GOT SPEECH RESULT " + resultCode + " req: "
+ requestCode);
if (requestCode == SpeechGatherer.VOICE_RECOGNITION_REQUEST_CODE)
{
if (resultCode == RESULT_OK)
{
ArrayList<String> matches = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
Log.d(D_LOG, "matches: ");
for (String match : matches)
{
Log.d(D_LOG, match);
}
}
}
}
For more info see:
http://developer.android.com/resources/articles/speech-input.html
http://developer.android.com/reference/android/speech/RecognizerIntent.html
http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/VoiceRecognition.html
First need to Showing google speech input dialog like so
/**
* Showing google speech input dialog
* */
private void promptSpeechInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
getString(R.string.speech_prompt));
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
getString(R.string.speech_not_supported),
Toast.LENGTH_SHORT).show();
}
}
then need to receiving speech input like so.
/**
* Receiving speech input
* */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtSpeechInput.setText(result.get(0));
}
break;
}
}
}
and need to set REQ_CODE_SPEECH_INPUT
private final int REQ_CODE_SPEECH_INPUT = 100;