get data onActivityResult from another application - java

I have two application A and B.
Application A
the following code I launch B Application for get Result from A application activity ..
String packageName = "com.cm.applicationb";
PackageManager manager = context.getPackageManager();
Intent i = manager.getLaunchIntentForPackage(packageName);
i.addCategory(Intent.CATEGORY_LAUNCHER);
i.putExtra("grand_total", "2500");
i.setAction(packageName);
startActivityForResult(i, REQUEST_DATA);
From Application A call onActivityResutl
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==REQUEST_DATA)
if (resultCode == Activity.RESULT_OK) {
me=data.getStringExtra("Obj");
}
Toast.makeText(getApplicationContext(),me,Toast.LENGTH_LONG).show();
}
B Application setResult Data
Intent i=new Intent();
i.putExtra("Obj", "object");
setResult(Activity.RESULT_OK, i);
finish();
Ever retrun null data and resultcode from onActivityResult. How we can solve it? It is impossible get data onAcitivityResult from another applicaion setREsult. Anyone please help me for us. Thank you so much.

Remove finish() and call like this in B:
#Override
public void onBackPressed() {
Intent data = new Intent();
Bundle bundle = new Bundle();
bundle.putString("Obj", "Obj_Data");
data.putExtras(bundle);
setResult(Activity.RESULT_OK, data);
super.onBackPressed(); // this calls finish(); internally.
}

just add this line to your manifest.xml
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
for more detail, check this links that explain about how to receive data from other application

Related

"No Activity found to handle Intent" error when trying to save picture to external storage in Android Java

I am trying to save a picture to external storage from a MediaStore.ACTION_IMAGE_CAPTURE intent.
I keep getting this error:
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.media.action.IMAGE_CAPTURE dat=content://ca.kevincook.trackmytrip.fileprovider/DCIM/default_image.jpg flg=0x3 clip={text/uri-list U:content://ca.kevincook.trackmytrip.fileprovider/DCIM/default_image.jpg} (has extras) }
Here is my code:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File imagePath = new File(getContext().getExternalFilesDir(Environment.DIRECTORY_DCIM), "");
File newFile = new File(imagePath, "default_image.jpg");
Uri contentUri = FileProvider.getUriForFile(getContext(), "ca.kevincook.trackmytrip.fileprovider", newFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
intent.setData(contentUri);
getContext().grantUriPermission("ca.kevincook.trackmytrip", contentUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
getContext().grantUriPermission("ca.kevincook.trackmytrip", contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivityForResult(intent, 0);
onActivityResult method:
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0)
{
if (resultCode == Activity.RESULT_OK)
{
Uri uri = data.getData();
GalleryAdapter.addImage(BitmapFactory.decodeFile(uri.toString()));
}
}
SaveImagePopup("Enter Picture Name");
}
Activity declaration in manifest file:
<activity android:name=".MapsActivity" android:label="#string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.IMAGE_CAPTURE" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Permissions in manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-feature android:name = "android.hardware.camera"
android:required="true"/>
provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_public_path" path="." />
</paths>
I copied the code exactly from the android developer website:
https://developer.android.com/reference/androidx/core/content/FileProvider
I used getContext() because I'm running it from a fragment. I also tried getActivity() in its place, but that didn't work.
Have you added the file provided in the manifest? If not Use it in this way
<provider
android:name=".fileprovider"
android:authorities="com.xxxx.xxxx.xxxx" //Your package name
android:enabled="true"
android:exported="false" />
and can handle in on the activity result
The code in onActivityResult will be like this,
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CAMERA && resultCode == RESULT_OK) {
File out = new File(getFilesDir(), "newImage.jpg");
if (!out.exists()) {
Toast.makeText(getBaseContext(), "Error while capturing image", Toast.LENGTH_LONG).show();
return;
}
Bitmap mBitmap = BitmapFactory.decodeFile(compressedImage.getAbsolutePath());
ivShowImage.setImageBitmap(mBitmap);
}
}

Speed up the startup of BroadcastReceiver at reboot

I've an app where the user can call custom lock screen to lock his/her mobile, that is an activity called LockScreen.class.
One this screen is loaded, i.e. the deviced is locked, a SharedPreferences called IsLocked is assigned to be true.
once the user do what he need with tthe lock screen this islocked became false, and the mobile is back to normal.
Every hing is working fine as expected.
The problem is, if for some reason the mobile had been rebooted while the lock screen is active, it is not running back upon a reboot.
So, I created a BootReciever as below, this works fine BUT after having the reboot process completed, and the user can do many things before it is loaded, my question is how can I make it loaded faster? so that the mobile screen is locked again with the custom activity before giving the chance for the user to do anything with the mobile?
public class BootReciever extends BroadcastReceiver
{
SharedPreferences mPrefs;
final String IsLockedPref = "IsLocked";
#Override
public void onReceive(Context context, Intent intent) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Boolean islocked = mPrefs.getBoolean(IsLockedPref, false);
Intent i;
if (islocked)
i = new Intent(context, LockScreen.class);
else
i = new Intent(context, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
part of the manifiest file is:
<receiver android:name=".BootReciever"
android:enabled="true"
android:exported="true">
<intent-filter >
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
UPDATE
I tried to get use of this by granting Device Admin by adding the below, but nothing improved:
In the main Activity:
private static final int ADMIN_INTENT = 15;
private static final String description = "Some Description About Your Admin";
private DevicePolicyManager mDevicePolicyManager;
private ComponentName mComponentName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDevicePolicyManager = (DevicePolicyManager)getSystemService(
this.DEVICE_POLICY_SERVICE);
mComponentName = new ComponentName(this, AdminReceiver.class);
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mComponentName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,description);
startActivityForResult(intent, ADMIN_INTENT);
.
.
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ADMIN_INTENT) {
if (resultCode == RESULT_OK) {
Toast.makeText(getApplicationContext(), "Registered As Admin", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "Failed to register as Admin", Toast.LENGTH_SHORT).show();
}
}
}
and created empty receiver to extend the DeviceAdminReceiver as:
public class AdminReceiver extends DeviceAdminReceiver {
}
and added the below to the manifiest:
<receiver
android:name="AdminReceiver"
android:permission="android.permission.BIND_DEVICE_ADMIN">
<meta-data
android:name="android.app.device_admin"
android:resource="#xml/admin"/>
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
</intent-filter>
</receiver>
One thing you can do from your side is to set a priority to your intent-filter. From documentation
It controls the order in which broadcast receivers are executed to receive broadcast messages. Those with higher priority values are called before those with lower values.
<intent-filter
android:priority="100">
...
</intent-filter>
The value must be an integer, such as "100". Higher numbers have a higher priority. The default value is 0. The value must be greater than -1000 and less than 1000.

startActivityForResult() returns RESULT_CANCELED

I have 2 Activity classes and 1 Non-Activity class which calls startActivityForResult() from Context passed in constructor. This is how it looks: FirstActivity -> NonActivity -> SecondActivity -> FirstActivity. In SecondActivity there is ArrayList of custom objects that needs to be passed to FirstActivity as a result. There is a problem. When onActivityResult() is called resultCode is RESULT_CANCELED, but not RESULT_OK even if setResult(RESULT_OK, intent) is called. Here is my code:
NonActivity
public void showActivity() {
Intent intent = new Intent(request, ActivityKorak.class);
intent.putExtra("data", fields);
request.startActivityForResult(intent, 1);
}
SecondActivity
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent();
intent.putExtra("data", fields);
setResult(Activity.RESULT_OK, intent);
finish();
}
FirstActivity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
super.onActivityResult(requestCode, resultCode, intent);
if(resultCode != Activity.RESULT_CANCELED){
if(requestCode == 1) {
Bundle extras = intent.getExtras();
ArrayList<CustomInput> fields = (ArrayList<CustomInput>) extras.getSerializable("data");
}
}
}
You must simply remove
super.onBackPressed();
in the onBackPressed Method
What is happening is that "super.onBackPressed()" is setting the result code to "RESULT_CANCELED" and finishing your activity.
In my case, the problem was fixed by adding the SHA-1 and SHA-256 certificate fingerprints given in Android Studio (click on Gradle on the right side of the AS window, then run configurations and signingReport) to your Firebase project settings->General->SDK setup and configuration.

How to implement QR code scanner in Fragment in portrait mode in android?

I am developing an application,In this application I have to implement QR code scanner, I can achieve this thing easily in activity with the help of Zxing library but the thing is that the scanner should be in fragment and the Fragment added in ViewPager and I also want customise the view of scanner.
Use this Library for QR code scanner it is the Modification of ZXING Scanner project for easy Android QR-Code detection.QR Code Scanner
For Android Studio Users
repositories {
maven {
url "https://jitpack.io"
}
}
compile 'com.journeyapps:zxing-android-embedded:3.2.0#aar'
compile 'com.google.zxing:core:3.2.1'
First of all, you need to to trigger an intent by virtue of which camera gets open (Scanner).
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
Then , If trigerred within a Fragment then write, else you will get your request code wrong.
getActivity().startActivityForResult(intent, 0);
If From Activity
startActivityForResult(intent, 0);
Then, it must be an Activity where you need your results captured by the scanner, I have captured and thus displayed in a Toast.
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");
Toast.makeText(this,contents,Toast.LENGTH_LONG).show();
// Handle successful scan
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel
}
}
}
Finally, Index it in manifest File, Use of intent filters enables it to recognise its source and function
<activity android:name="com.journeyapps.barcodescanner.CaptureActivity"
android:clearTaskOnLaunch="true"
android:stateNotNeeded="true">
<intent-filter>
<action android:name="com.google.zxing.client.android.SCAN"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>

scan qrcode closing app instead of providing result

I'm using the zxing library to provide qrcodes and scanning to an application however I'm stuck on an issue. When attempting to scan, I've tried several methods. The recommended:
IntentIntegrator integrator = new IntentIntegrator(this);
integrator.initiateScan();
or the Intent method:
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
this.startActivityForResult(intent, 0);
Both appear to work fine as the Scan app or choose the app to handle the intent dialog appears. However, after scanning, the app immediately closes. No errors and no results. Just bye-bye.
method to catch the result, note the Log.d immediately after super() is never displayed.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(LOG_TAG, "resultcode = " + resultCode);
switch (requestCode) {
case IntentIntegrator.REQUEST_CODE:
IntentResult scanResult = IntentIntegrator.parseActivityResult(
requestCode, resultCode, data);
if (scanResult == null) {
return;
}
final String result = scanResult.getContents(); // Your result
if (result != null) {
Log.d(LOG_TAG, "Your result is: " + result);
}
break;
default:
}
}
I've seen references in some tutorials explaining how to implement zxing make entries in the AndroidManifest.xml. Seen below:
<activity android:name="com.google.zxing.client.android.CaptureActivity"
android:screenOrientation="landscape"
android:configChanges="orientation|keyboardHidden"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen"
android:windowSoftInputMode="stateAlwaysHidden">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
<intent-filter>
<action android:name="com.google.zxing.client.android.SCAN"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
I'm just not having any luck so far and the lack of logs isn't helping point me in any direction.
I'm using Android Studio and have gradle setup for the libs in dependencies:
compile files('libs/core-3.1.1.jar')
compile files('libs/android-integration-3.1.1.jar')
Help is really appreciated.
The problem is not with zxing, but rather with the way you start it. The second parameter of the startActivityForResult method is a requestCode (documentation). You would then check that requestCode on onActivityResult to handle the response. Also, do not call super first in onActivityResult.
For example:
startActivityForResult(intent, 123);
will cause Android to call onActivityResult with request code 123
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 123 && resultCode == RESULT_OK) {
//do some stuff...
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
Try this
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanResult != null) {
// handle scan result
}
// else continue with any other code you need in the method
...
}
try to implement this, hope it might work.
in onCrearte() -- call the doScan() method.
//OnClick of Scan button.
Button btn_scan = (Button) findViewById(R.id.stbcheck_btn_scan);
btn_scan.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
doScan();
}
});
doScan():
//Bar code Scanning Option and API Integration
public void doScan() {
IntentIntegrator.initiateScan(this);
}
onActivityResult():
public void onActivityResult(int request, int result, Intent i) {
IntentResult scan=IntentIntegrator.parseActivityResult(request, result, i);
if (scan!=null) {
//format.setText(scan.getFormatName());
//Set the returned content from Scanner to edit text
et_stbNo.setText(scan.getContents());
}
}
NOTE: You must call these onSavedInstanceState() and onRestoreInstanceState() methods, as your activity is destroyed and recreated again while changing the orientation.
#Override
public void onSaveInstanceState(Bundle state) {
//state.putString("format", format.getText().toString());
state.putString("contents", et_stbNo.getText().toString());
}
#Override
public void onRestoreInstanceState(Bundle state) {
//format.setText(state.getString("format"));
et_stbNo.setText(state.getString("contents"));
}
Hope it helps:
Use below code it is working for my code.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null)
{
if (result.getContents() == null)
{
}
else
{
}
}
else
{
// This is important, otherwise the result will not be passed to the fragment
super.onActivityResult(requestCode, resultCode, data);
}
}

Categories