onResultActivity is called immediately after startActivyForResult - android

In my main activity i have this code:
noConnectionButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(new Intent(Settings.ACTION_WIRELESS_SETTINGS), SET_CONNECTION);
}
});
in the onCreate method. Then:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == SET_CONNECTION){
checkConnection();
}
}
So what I want to do is to start the settings activity in a way that the user can switch on wireless or data connection.
My problem is that the onActivityResult is called prematurely!!! so I want it to be called only after the user backs to my activity.
any suggestion??
here the manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="it.polimi.metalnews"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="13"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="it.polimi.metalnews.MainActivity"
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="it.polimi.metalnews.HomeActivity"
android:label="#string/title_activity_home" >
</activity>
<activity
android:name="it.polimi.metalnews.NewsActivity"
android:label="#string/title_activity_news" >
</activity>
<activity
android:name="it.polimi.metalnews.AlbumActivity"
android:label="#string/title_activity_album" >
</activity>
<activity
android:name="it.polimi.metalnews.ContestActivity"
android:label="#string/title_activity_contest" >
</activity>
</application>

follow this process:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
// Check which request we're responding to
if (requestCode == PICK_CONTACT_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// The user picked a contact.
// The Intent's data Uri identifies which contact was selected.
// Do something with the contact here (bigger example below)
}
}
}
use below link for further detail:
http://developer.android.com/training/basics/intents/result.html

In onActivity result first check if the result is came from the action is OK or not by comparing your result code to RESULT_OK like:
if (resultCode == RESULT_OK) {
// You successfully got back then do what ever you want.
//Then you can check you particular data according to your request.
}
Because there is no reason for going deep if the result is not ok. Every system service will result in RESULT_OK or RESULT_CANCEL if canceled by user.
I don't think there is anything wrong with intent declaration but i read this kind of article link it explains your problem in a better manner
It is due to the Activity is SingleTask and whenever it is called it reports the result.

Related

React Native intents interaction (onActivityResults running before an activity starts)

I need help or guidance in resolving the issue that I have regarding React Native interacting with other native applications via intents. I know that React Native supports deeplinking out of the box but does not cater for intents, which means that one needs to create an android native module (https://reactnative.dev/docs/native-modules-android). I created a native module that calls 3rd party applications via intents and passing data using startActivityForResults and created onActivityResult that is supposed to handle data returned from 3rd party applications after closing. However, the onActivityResult executes prematurely before external applications open.
Starting the activity using startActivityForResults:
#ReactMethod
public void launchApp(String stringArgument, ReadableMap args, Promise promise) throws JSONException{
try {
final JSONObject options = convertMapToJson(args);
Bundle extras = new Bundle();;
int LAUNCH_REQUEST = 0;
if (options.has("extras")) {
extras = createExtras(options.getJSONArray("extras"));
Log.d(TAG,"Extras found");
Log.d(TAG, options.getString("extras"));
} else {
extras = new Bundle();
Log.d(TAG,"No extras");
}
if (options.has("launchRequestCode")) {
LAUNCH_REQUEST = options.getInt("launchRequestCode");
}
Intent packageIntent = this.reactContext.getPackageManager().getLaunchIntentForPackage(stringArgument);
if(packageIntent != null){
packageIntent.putExtras(extras);
//callback.invoke("Starting activity for: "+stringArgument);
Activity activity = getReactApplicationContext().getCurrentActivity();
//this.reactContext.startActivityForResult(packageIntent, LAUNCH_REQUEST, extras);
activity.startActivityForResult(packageIntent, LAUNCH_REQUEST);
return;
//mPromise.put(LAUNCH_REQUEST, promise);
}
else{
Log.d(TAG, stringArgument+" package not found");
//callback.invoke("Package not found: "+stringArgument);
}
} catch (JSONException e) {
//TODO: handle exception
Log.d(TAG, e.toString());
}
// TODO: Implement some actually useful functionality
}
Expecting the data back using onActivityResults
ActivityEventListener mActivityEventListener = new ActivityEventListener(){
#Override
public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
//super.onActivityResult(requestCode, resCode, data);
Log.d(TAG,"On activity result");
if (mPromise != null && resultCode == activity.RESULT_OK) {
WritableMap result = new WritableNativeMap();
result.putInt("resultCode", resultCode);
result.putMap("data", Arguments.makeNativeMap(data.getExtras()));
mPromise.resolve(result);
}
else{
Log.d(TAG,"Promise and intent data are empty");
//mPromise.reject("Unable to get promise or intent data is empty");
}
if(resultCode == activity.RESULT_CANCELED ){
Log.d(TAG,"Result cancelled or no result or crashed with code");
}
}
#Override
public void onNewIntent(Intent intent){
Log.d(TAG,"New Intent");
}
};
Android Manifest file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.navapp">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name=".MainApplication"
android:label="#string/app_name"
android:icon="#mipmap/ic_launcher"
android:roundIcon="#mipmap/ic_launcher_round"
android:allowBackup="false"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
</application>
</manifest>
By using Android Studio Logcat to debug, I found out that the onActivityResults executes immediately before the external app opens up.
Logcat screenshot
Thanks to this explanation here, I was able to drill down to what was causing the issue. In my React Native application, I used the package name of the external application instead of the action name to open it.
Manifest File of the external app:
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:launchMode="singleTask"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="com.bld.pushnotification.Main"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
I also modified the my code for launching the app:
#ReactMethod
public void launchApp(String stringArgument, ReadableMap args, Promise promise) throws JSONException{
try {
final JSONObject options = convertMapToJson(args);
Bundle extras = new Bundle();;
int LAUNCH_REQUEST = 0;
if (options.has("extras")) {
extras = createExtras(options.getJSONArray("extras"));
Log.d(TAG,"Extras found");
Log.d(TAG, options.getString("extras"));
} else {
extras = new Bundle();
Log.d(TAG,"No extras");
}
if (options.has("launchRequestCode")) {
LAUNCH_REQUEST = options.getInt("launchRequestCode");
}
Intent packageIntent = new Intent(stringArgument);
Activity activity = getReactApplicationContext().getCurrentActivity();
activity.startActivityForResult(packageIntent, LAUNCH_REQUEST);
} catch (JSONException e) {
//TODO: handle exception
Log.d(TAG, e.toString());
}
}

android studio intent inside intent crash

So I have two activities, let's call them A and B, activity A have a text input and a button, which call to activity B with an intent method:
and I have activity B which have also intent to the camera application:
ImageView photo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.b);
TextView textView = findViewById(R.id.textView);
Button buttonCapture = findViewById(R.id.buttonCapture);
photo = findViewById(R.id.photo);
buttonCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent1, 0);
}
});
}
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bitmap = (Bitmap) (data != null ? requireNonNull(data.getExtras()).get("data") : null);
photo.setImageBitmap(bitmap);
}
and when I launch this in a simulator, I get the first A activity fine, click on the button, it open activity B, I press the button again, and it returns me to activity A or crash(random?)
my manifest file:
package="com.example.user.app">
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".A">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".B">
</activity>
</application>
with the exception:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.app, PID: 18441
java.lang.SecurityException: Permission Denial: starting Intent { act=android.media.action.IMAGE_CAPTURE cmp=com.android.camera2/com.android.camera.CaptureActivity } from ProcessRecord{296747c 18441:com.example.user.app/u0a88} (pid=18441, uid=10088) with revoked permission android.permission.CAMERA
ok, I see...
Starting Android 6 (API 23), if your app has CAMERA permission declared in the manifest, it needs that CAMERA permission to be GRANTED in order to access ACTION_IMAGE_CAPTURE etc... too (which normally do not require the CAMERA permission on their own). If not, then it automatically raises a SecurityException.
do like below!!!
1- If you only need ACTION_IMAGE_CAPTURE etc..
Remove the CAMERA permission from manifest and you would be fine
2- If you need CAMERA permission too
Check for CAMERA permission at runtime and only start the intent when the permission is available
1) it maybe happens when you don't declare your B activity in manifests!!!
2)remove final before defining EditText and try again!!!
if you send your logs, I can help you better...

Watch Face Complication chooser never showed

I'm trying to implement complication support for my watch. Here's my AndroidManifest.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.wearapp">
<uses-feature android:name="android.hardware.type.watch"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="com.google.android.wearable.permission.RECEIVE_COMPLICATION_DATA"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#android:style/Theme.DeviceDefault">
<!-- Watch Face -->
<service
android:name=".ComplicationSimpleWatchFaceService"
android:enabled="true"
android:label="Fancy Watch"
android:permission="android.permission.BIND_WALLPAPER">
<meta-data
android:name="android.service.wallpaper"
android:resource="#xml/watch_face"/>
<meta-data
android:name="com.google.android.wearable.watchface.preview"
android:resource="#drawable/preview_complication_simple"/>
<meta-data
android:name="com.google.android.wearable.watchface.preview_circular"
android:resource="#drawable/preview_complication_simple"/>
<meta-data
android:name="com.google.android.wearable.watchface.wearableConfigurationAction"
android:value="com.example.wearapp.CONFIG_COMPLICATION_SIMPLE"/>
<intent-filter>
<action android:name="android.service.wallpaper.WallpaperService"/>
<category android:name="com.google.android.wearable.watchface.category.WATCH_FACE"/>
</intent-filter>
</service>
<activity android:name="android.support.wearable.complications.ComplicationHelperActivity"/>
<activity
android:name=".ComplicationSimpleConfigActivity"
android:label="Fancy Watch">
<intent-filter>
<action android:name="com.example.wearapp.CONFIG_COMPLICATION_SIMPLE"/>
<category android:name="com.google.android.wearable.watchface.category.WEARABLE_CONFIGURATION"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
</application>
</manifest>
I have a watch face service and a config activity. When I use ComplicationHelperActivity to createProviderChooserHelperIntent from the config activity I always get result cancelled in the onActivityResult. Here's how I start chooser activity and listen for the result
#Override
public void onClick(WearableListView.ViewHolder viewHolder) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "onClick()");
}
Integer tag = (Integer) viewHolder.itemView.getTag();
ComplicationItem complicationItem = mAdapter.getItem(tag);
startActivityForResult(ComplicationHelperActivity.createProviderChooserHelperIntent(
getApplicationContext(),
complicationItem.watchFace,
complicationItem.complicationId,
complicationItem.supportedTypes),
PROVIDER_CHOOSER_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PROVIDER_CHOOSER_REQUEST_CODE
&& resultCode == RESULT_OK) {
ComplicationProviderInfo complicationProviderInfo =
data.getParcelableExtra(ProviderChooserIntent.EXTRA_PROVIDER_INFO);
Log.d(TAG, "Selected Provider: " + complicationProviderInfo);
finish();
}
}
It seems like I'm missing complication support and that's why can't choose any provider. But to test this I copied ComplicationSimpleWatchFaceService from the WatchFace sample and still don't have any result. Here's complication code from the watch face.
private static final int LEFT_DIAL_COMPLICATION = 0;
private static final int RIGHT_DIAL_COMPLICATION = 1;
public static final int[] COMPLICATION_IDS = {LEFT_DIAL_COMPLICATION, RIGHT_DIAL_COMPLICATION};
public static final int[][] COMPLICATION_SUPPORTED_TYPES = {
{ComplicationData.TYPE_SHORT_TEXT},
{ComplicationData.TYPE_SHORT_TEXT}
};
private void initializeComplication() {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "initializeComplications()");
}
mActiveComplicationDataSparseArray = new SparseArray<>(COMPLICATION_IDS.length);
mComplicationPaint = new Paint();
mComplicationPaint.setColor(Color.WHITE);
mComplicationPaint.setTextSize(COMPLICATION_TEXT_SIZE);
mComplicationPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
mComplicationPaint.setAntiAlias(true);
setActiveComplications(COMPLICATION_IDS);
}
Make sure that you have called the ComplicationHelperActivity.createProviderChooserHelperIntent method, to obtain an intent and to start the provider chooser.
Sample code (make sure to call the getActivity() method for it to launch):
startActivityForResult(
ComplicationHelperActivity.createProviderChooserHelperIntent(
getActivity(),
watchFace,
complicationId,
ComplicationData.TYPE_LARGE_IMAGE),
PROVIDER_CHOOSER_REQUEST_CODE);
The intent can be used with either startActivity or startActivityForResult to launch the chooser.
You can followed this tutorial and see if you missed some configurations.

Activity not starting when the icon is clicked

I've began working on a simple Android project recently, but it looks like I just cannot get it to work. I have a main Activity (It has #style/Invisible parameter) which checks if my service is running and starts it if it's not. Also, before the check takes place it starts another activity for result. The activity is expected to return the user's username and password to allow the app to login to the system. The problem is that when I install the app on my phone it works fine, but next time I open the app nothing happens. I have to reinstall it.
Here's the main Activity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
Intent intent = new Intent(this, LoginGrabber.class);
startActivityForResult(intent, 100);
if(isMyServiceRunning()==false)
{
startService(new Intent(getApplicationContext(), MyService.class));
Log.i("com.connect","startService");
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == 100){
if(resultCode == RESULT_OK){
String username = data.getStringExtra("Username");
String password = data.getStringExtra("Password");
//TODO Send to server
Toast.makeText(this, "Username: " + username + " Password: " + password, Toast.LENGTH_LONG);
}
}
}
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (MyService.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
LoginGrabber Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_grabber);
}
public void onSendData(View view){
Intent intent = new Intent();
intent.putExtra("Username", ((TextView) findViewById(R.id.email)).getText());
intent.putExtra("Password", ((TextView) findViewById(R.id.password)).getText());
setResult(RESULT_OK, intent);
finish();
}
Here's the Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.app.test"
android:versionCode="2"
android:versionName="2.0">
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="18" />
<supports-screens
android:largeScreens="true"
android:resizeable="true"
android:xlargeScreens="true" />
<uses-permission
android:name="android.permission.INTERNET"
android:required="true" />
<application
android:icon="#drawable/launcher"
android:label="#string/app_name"
android:theme="#style/Invisible">
<activity
android:name="com.connect.Main"
android:excludeFromRecents="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
<service
android:name="com.connect.MyService"
android:enabled="true"
android:exported="true" />
<activity
android:theme="#style/AppTheme"
android:name="com.connect.LoginGrabber"
android:label="#string/title_activity_login_grabber" />
</application>
</manifest>
What am I doing wrong?
Thanks for your help!
OK! I found the problem! The problem was that my application was crashing as soon as the service was started because I was testing the app without internet and without handling errors that were thrown when there was no internet available.
Just had to turn WiFi on, that's it!

Android | Google PlacePicker API. OnActivityResult code not executed [Really weird behaviour]

I've a Fragment (support.v4) in a ViewPager with the which calls PlacePicker UI and then updated on a TextView. My code is as follows,
public void openPlacePicker() {
try {
PlacePicker.IntentBuilder intentBuilder = new PlacePicker.IntentBuilder();
Intent intent = intentBuilder.build(getContext());
// Start the Intent by requesting a result, identified by a request code.
startActivityForResult(intent, PLACE_PICKER);
} catch (GooglePlayServicesRepairableException e) {
GooglePlayServicesUtil
.getErrorDialog(e.getConnectionStatusCode(), getActivity(), 0);
} catch (GooglePlayServicesNotAvailableException e) {
Toast.makeText(getContext(), "Google Play Services is not available.",
Toast.LENGTH_LONG)
.show();
}
}
And the OnActivityResult is,
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i(TAG, "Request Code:" + requestCode);//This is printed
if(requestCode == PLACE_PICKER){
Log.d(TAG,"Reached in if()"); //Never printed
}
switch (requestCode) { //Never reached
case PLACE_PICKER:
if (resultCode == Activity.RESULT_OK) {
final Place place = PlacePicker.getPlace(data, getContext());
final CharSequence name = place.getName();
//EventBus.getDefault().post(new NotifyEvent(NotifyEvent.NotifyType.PLACE_PICKED, (String) name));
}
}
}
So the problem is that, the conditional statements never gets executed. The Log before if() is printed. But the Log inside the if() is not printed.
Weird thing is the android-place-picker sample from GitHub is working fine.
I have tried the following:
Clean Project
Clear Data and re-install on device
IDE clear cache and restart
Any ideas?
--EDIT--
Manifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.apps.maps">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="com.apps.maps.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<permission android:name="com.apps.maps.permission.MAPS_RECEIVE" android:protectionLevel="signature" />
<application android:name=".MyApplication" android:allowBackup="true" android:icon="#mipmap/ic_launcher" android:label="#string/app_name" android:supportsRtl="true" android:theme="#style/AppTheme">
<meta-data android:name="com.google.android.geo.API_KEY" android:value="#string/google_maps_key" />
<activity android:name=".activity.MainActivity" android:label="#string/title_activity_maps">
</activity>
</application>
</manifest>
I know this is an older thread but it has helped me to resolve a similar issue to the original problem. Raman Bhavsar's 10/10/15 comment was the right question to ask. I had forgotten to enable the Places API in the Google Developer Console, and once I did I was able to hit my breakpoint in the onActivityResult method.

Categories

Resources