I found a tutorial online for creating a QR Code Scanner App for Android. It works great but the output of the scan is a toast notification as you can see in the code:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode == Activity.RESULT_OK) {
val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
if (result != null) {
if (result.contents == null) {
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show()
} else {
Toast.makeText(this, "Scanned: " + result.contents, Toast.LENGTH_LONG).show()
}
} else {
super.onActivityResult(requestCode, resultCode, data)
}
}
}
}
What i would like to do is for the scanned code to launch the url inside the app itself. As I want the pages to be hosted in the app itself, what i've done was create an actvity with the webview that loads the internal html page.
I took the scanner code and changed the positive outcome to open the webview activity :
startActivity(Intent(this, PagInfoActivity::class.java))
Which works fine. Anytime a QR Code is detected the app automatically loads the desired activity. I know this is not ideal, as the QR Code link itself is not being used to open the page, but what I was trying to do was to use that scan result on the webview load. I've created QRCodes with text strings instead of URLs so that i could inject them in the loadURL of the webview like this:
WebView.loadUrl("file:///android_asset/*QRCODE string*.html");
Is it possible to call result.contents from the MainActivity?
There are multiple ways you can achieve this. First option can be Explicit Intents
For Example,
You need to pass it as an extra:
Intent i = new Intent(this, PagInfoActivity.class);
i.putExtra("result", result.contents);
startActivity(i);
Then extract it from your PagInfoActivity like this:
Intent intent = getIntent();
String result= intent.getExtras().getString("result");
Related
Still trying to make my screen record app. I keep on working with MediaRecorder, as I was told some time ago, so I got stuck with another problem.
I just need to initialize a MediaProjection object to make my code work, that's what I do in onActivityResult(), as it's written in this guide:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECORD_REQUEST_CODE && resultCode == RESULT_OK) {
mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data);
screenRecorder.setMediaProject(mediaProjection);
}
}
The setMediaProjection() looks like
public void setMediaProject(MediaProjection project) {
mediaProjection = project;
}
, so it shouldnt't cause any trouble.
And that's how I try to call onActivityResult():
/* start transmission */
if(screenRecorder.isRunning()) {
screenRecorder.stopRecord();
} else {
Intent captureIntent = mediaProjectionManager.createScreenCaptureIntent();
startActivityForResult(captureIntent, RECORD_REQUEST_CODE);
}
The fun and crazy thing is that when I first launched the debug, it worked! After startActivityForResult() I got to onActivityResult() and initialized mediaProjection: my phone showed me a dialog window whether I allow to capture the screen or not, so I allowed that and got a special symbol (smth like screen with displayed waves) at my status bar.
But a few moments later I found an issue when stopping the record and restarted the debug session to trace it more exactly. After that onActivityResult() is just ignored: startActivityForResult() is called, the dialog window is shown, but after allowing the record onActivityResult() is completely skipped and mediaProjection is null. The restarting and re-installing the apk with the same code didn't fix anything.
Thank you very much for any suggestions.
Your onActivityResult only does something when the result code is OK, try this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECORD_REQUEST_CODE && resultCode == RESULT_OK) {
mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data);
screenRecorder.setMediaProject(mediaProjection);
} else {
//TODO: Do something
Toast.makeText(getBaseContext(), "Result code is not RESULT_OK, ", Toast.LENGTH_LONG).show();
}
There was a very simple solution. I just initialized the record service that put null into mediaRecorder's mediaProjection, so after that I was unable to re-initialize it. Putting intent which called onActivivtyResult() into activity's onCreate() before starting the service fixed that.
I got same problem. This could bu about threading. In my project I started an activity and opening activity try to start chrome intent. Chrome is opening in debug mode but not opened real mode.
I added a delay when opening chrome
final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
#Override
public void run() {
startAuth();
}
}, 100);
UPI (Unified Payment Interface) is a payment interface for Indian banks.
In UPI transactions are links. Just like bitcoin transactions are messages
Those links are passed to UPI payment apps and the payer has to login to the app and click the pay button.
Our app has to start an intent and pass link to the UPI payment app and after payer clicks the pay button we need to call onActivityResult.
I dont know anything about android development in java.
I use python kivy for android development. I want to know what should my onActivityResult should do.
Sample code :
UPI App Deep linking using Intent - inconsistent and buggy behavior
I can use java code in python using pyjnius.
Some reference link:
https://blog.deazzle.in/enable-upi-payments-in-your-app-without-the-need-to-integrate-with-a-bank-c911019f3b2d
you have not any need to do it manually. I have developed a library for it.
Just have to do a simple process.
final EasyUpiPayment easyUpiPayment = new EasyUpiPayment.Builder()
.with(this)
.setPayeeVpa("EXAMPLE#VPA")
.setPayeeName("PAYEE_NAME")
.setTransactionId("UNIQUE_TRANSACTION_ID")
.setTransactionRefId("UNIQUE_TRANSACTION_REF_ID")
.setDescription("DESCRIPTION_OR_SMALL_NOT")
.setAmount("AMOUNT_IN_DECIMAL_XX.XX")
.build();
easyUpiPayment.startPayment();
For more info, you can visit below site.
https://github.com/PatilShreyas/EasyUpiPayment-Android
Activity A:
Intent start = new Intent(MainActivity.this, PurchaseActivity.class);
startActivityForResult(start, 1);
And add this result listener:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
//payment was successful
}else if (resultCode == RESULT_CANCELED) {
//payment was canceled
}
}
}
And Activity B:
If payment was successful:
setResult(RESULT_OK, new Intent());
finish();
or if it was canceled:
setResult(RESULT_CANCELED, new Intent());
finish();
I have AddActivity, which lets you get the URI from either a picture you can take from the camera, or an image that you can select from the gallery. Then you can go to DetailsActivity to view the image. I have it working right now until you restart the device. After you restart and try to go to DetailsActivity for that image, this is the error:
Caused by: java.lang.SecurityException: Permission Denial: opening provider com.android.providers.media.MediaDocumentsProvider from ProcessRecord{3a5e86d 2915:jeremy.com.wineofmine/u0a321} (pid=2915, uid=10321) requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs
I went to the "Open Files Using Storage Access Framework" Android Development page and read up on the Persist Permissions section. I'm having trouble applying it to my project though.
I think the main thing I don't understand is that it looks like you need to call an intent (in my case inside the DetailsActivity), but I don't even have an intent there.
Here is the intent that lets you pick the gallery image. This is in AddActivity:
Intent intentGallery = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intentGallery.addCategory(Intent.CATEGORY_OPENABLE);
intentGallery.setType("image/*");
intentGallery.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intentGallery.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivityForResult(intentGallery, SELECT_IMAGE);
In the DetailsActivity, this is where it actually crashes:
imageURI = Uri.parse(cursor.getString(cursor.getColumnIndexOrThrow(WineContract.WineEntry.COLUMN_WINE_IMAGE)));
bitmap = null;
try {
//If the cursor does not have anything in the image column, set the image to null, with a height so the textviews look decent
if (cursor.isNull(cursor.getColumnIndexOrThrow(WineContract.WineEntry.COLUMN_WINE_IMAGE))){
mFullImage.setImageBitmap(null);
mFullImage.setMaxHeight(300);
}else{
//remake the bitmap from the URI in the image column
//********This next line is where the program crashes**********
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageURI);
mFullImage.setImageBitmap(bitmap);
}
Could I get some help with figuring out how to apply this to my project?
To handle permission results overide onRequestPermissionsResult as below
#Override
public void onRequestPermissionsResult (int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case General.REQUESTPERMISSION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//reload my activity with permission granted or use the features that required the permission
} else {
Messenger.makeToast(getContext(), R.string.noPermissionMarshmallow);
}
break;
}
}
and to persist the permission implement as shown below in your onActivityResult method
#Override
public void onActivityResult (int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//if ok user selected a file
if (resultCode == RESULT_OK) {
Uri sourceTreeUri = data.getData();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
getContext().getContentResolver().takePersistableUriPermission(sourceTreeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
}
}
In onActivityResult(), call takePersistableUriPermission() on a ContentResolver, passing in the Uri that you got along with the mode flag(s) that indicate what access you want (read, write, both).
a bit late but...
We need to provide persistent Uri permission. Instead of doing it on onActivityResult as oppose to prior answers, I prefer to add it as a flag:
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).also {
it.addCategory(Intent.CATEGORY_OPENABLE)
it.type = "image/*"
it.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION)
it.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
Also, a note worth mentioning is persistent permission is available only to Intent.ACTION_OPEN_DOCUMENT and NOT Intent.ACTION_GET_CONTENT whereas the latter one is like a one-time thing.
The permission denial issue needs to be dealt with the first time you receive a URI. If you use registerForActivityResult() instead of startActivityForResult()
// Kotlin
private val pickImage = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) { result: ActivityResult ->
if (result.resultCode == Activity.RESULT_OK) {
// you will get result here in result.data
val uri = result.data?.data!!
requireActivity().contentResolver.takePersistableUriPermission(
uri,
Intent.FLAG_GRANT_READ_URI_PERMISSION
)
// Do something else with the URI. E.g, save the URI as a string in the database
}
}
I am trying to send mail from my app.The problem is after successful/unsuccessful delivery of the email it doesn't return to the activity, meaning that onActivityResult() is not being called.
Here is my code:
String[] recipients = {"soham#gmail.com"};
Intent email = new Intent(Intent.ACTION_SEND, Uri.parse("mailto:"));
// prompts email clients only
email.setType("message/rfc822");
email.putExtra(Intent.EXTRA_EMAIL, recipients);
try{
// the user can choose the email client
startActivityForResult(Intent.createChooser(email, "Choose an email client from..."), 1);
}catch(android.content.ActivityNotFoundException ex){
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == 1){
if(resultCode == RESULT_OK){
}else if (resultCode == RESULT_CANCELED){
}
}
}
I have checked this but not working for me. Can anyone tell me what am I doing wrong.
Edit
I got the problem.It will work fine in Activity.But it will not work on Fragment or FragmentActivity. All fragment is closing down forcefully.You can say my app is going on the background.How to solve this issue?Anybody got any idea.
If i uderstand your problem correctly;
In your activity's onActivityResult part you can find your fragment
YourFragment fragment = (YourFragment)getSupportFragmentManager().findFragmentById(R.id.your_framelayout_id);
And use your fragment's public method:
if(fragment != null)
{
fragment.yourPublicMethod();
}
In yourPublicMethod you can do whatever you want. I hope this helps you.
I'm having trouble getting zxing to do anything after scanning a barcode. I call the zxing using:
IntentIntegrator.initiateScan(MainActivity.this);
And my onActivityResult looks like this
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
if (format == "PRODUCT_CODE"){
//If the barcode scanned is of the correct type then pass the barcode into the search method to get the product details
Toast.makeText(getApplicationContext(),"You scanned " + contents, 3).show();
}
else{
//If the barcode is not of the correct type then display a notification
Toast.makeText(getApplicationContext(),"You didn't scan a product code", 3).show();
}
} else if (resultCode == RESULT_CANCELED) {
//If the scan is cancelled then display a notification
Toast.makeText(getApplicationContext(),"You cancelled the input", 3).show();
}
}
}
But whenever I exit zxing nothing is displayed. I tried using the example in the zxing wiki
but whenever I try to replace yourActivity with MainActivity or MainActivity.this I receive errors (I get told MainActivity cannot be resolved to a string and with MainActivity.this that The constructor IntentIntegrator(MainActivity) is undefined).
Basically I have no idea what I'm doing and why it's not working. Any help would be greatly appreciated.
The problem is exactly the same as in your other question. You can't compare strings with ==, but must use equals().