How to make sure the MainActivity will be created only once - android

I have a react native project. And there is a service running in the background.
When the app is not running, the service is still alive, and it may want to start the MainActivity in some time. I’m using the following code to start MainActivity(I tried noFlag/addFlag/setFlag):
Intent Intent = new Intent(context, MainActivity.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
// intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(key, value);
context.startActivity(intent);
The AndroidManifest.xml is declared like:
<activity
android:name=".MainActivity"
android:launchMode="singleTask”>
</activity>
Each time the MainActivity will be created twice. In the first time we can get the extra value, but the second time it will be empty.
How can I make sure the MainActivity will only be created once?
Thanks.

Just found the problem. My method breakpoint on startActivity worked.
The third party sdk cannot find property receiver, so it send a startActivity call with intent flag FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK, which overrode my singleTask in AndroidManefest.xml.

As you most probably have known, the problem lies with you calling the startActivity twice. I think it would be lovely if you could show the code that calls the startActivity.
I have just now tested that as long as you have singleTask or singleTop as your launchmode, OnCreate wont be called twice. As you can read from here : https://developer.android.com/guide/components/activities/tasks-and-back-stack
the function that would be called is onNewintent and if the putExtra is empty, it indeed can create a NPE
I hope that helps you, Good luck

Related

OnActivityResult getting called twice in Android

I used this code to launch an activity:
Intent intent = new Intent(this, OneTimeActivity.class);
intent.putExtra(Constants.HOST_KEY, host);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivityForResult(intent, 1000);
And for some reason my OnActivityResult() is called twice. Once when I first call startActivityForResult and once when the result actually ends. What's also weird is that the Intent data is always null, and the resultCode is always 0
Why is this happening? Shouldn't I only get a callback from OnActivityResult() once and also once? Shouldn't I get the result code I specify in setResult()?
Well after about 2 hours of debugging it seems
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
Was the problem. Once I removed that everything worked as expected, which I guess makes sense. I can't clear the back stack and expect results to get returned correctly to the back stack I just cleared.
In addition to etherton's answer, also check whether your activity is declared as singleTask or not.
Open AndroidManifest.xml and check for android:launchMode="singleTask" for your called activity. Remove this line and it will work as expected.
Note: If you really want your activity as singleTask then you have to handle your callbacks on your own.

How to find out the reason why Activity doesn't start

I got log cat message from startAnotherActivity() method
private void startAnotherActivity() {
Log.i(TAG, "Entered startAnotherActivity()");
Intent intent = new Intent();
intent.setAction(ANOTHER_ACTIVITY);
intent.addCategory("android.intent.category.DEFAULT");
startActivity(intent);
}
Another activity doesn't start, no other messages in log cat.
How can I resolve this issue?
UPDATE#1:
Sorry, I forgot to mention that AnotherActivity is an Activity in the other application, and therefore ANOTHER_ACTIVITY == 'some.other.app.domain.ANOTHER_ACTIVITY'
Shouldn't Dalvik complain if it cannot find specified activity?
One possible reason may be not declaring other activity in the manifest. You can do this like the following:
<activity android:name="your.package.your.activity">
</activity>
And then you can start the activity by doing the following:
Intent intent = new Intent(CurrentActivity.this, NewActivity.class);
startActivity(intent);
Hope this helps.
Since it's an activity in another application, you may need to set the component (fully qualified package name and fully qualified activity name).
See here: How to start activity in another application?
Or here:
Launch an application from another application on Android
Finally I found out my mistake.
In the project there are two similar messages in two activities, so I thought that runs one, but that was another.
Thank you for your assistance!

Start multilple activity from broadcastReceiver

I want to start multiple activities from my broadcast receiver. I have two classes i.e ReadContacts and CallDetails. I want to start them one by one. like first calldetails activity should be started and then next. I have tried below code and it works fine.
Intent calldetails = new Intent();
calldetails.setClassName("com.simplereader", "com.simplereader.Calldetails");
calldetails.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(calldetails);
then I tried below code to start other activity
Intent readcontacts = new Intent();
readcontacts.setClassName("com.simplereader", "com.simplereader.ReadContacts");
calldetails.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
context.startActivity(readcontacts);
But its not working and application crashes.
You must have the Intent Flag Intent.FLAG_ACTIVITY_NEW_TASK to start an Activity from outside of an Activity context so you need to add that flag to your second Intent.
I don't know if this is your only problem but if that doesn't fix it then post your logcat so we can see the error.
Intent readcontacts = new Intent();
readcontacts.setClassName("com.simplereader", "com.simplereader.ReadContacts");
calldetails.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // you need this flag
context.startActivity(readcontacts);
FLAG_ACTIVITY_MULTIPLE_TASK Do not use this flag unless you are implementing your own top-level application launcher.
From the android developer documentation for intent.
You could probably just launch both activities with the new task flag.
I think you are making mistake in this line
calldetails.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
If you want to start readcontacts activity it shoul be
readcontacts.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
instead of
calldetails.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
I think this is the reason.

More than one instance of activity due to intent

For an App I am developing, I override the back button to make it act like the home button so that the state of the main activity is preserved even when the app is exited. Now, I also send a notification to the user from time to time using a service. When this notification is pressed I want to open the main activity again. I noticed though that this creates a second instance of the app, which creates major problems. I am trying to make the main activity go to the front again, without calling oncreate again like so:
Intent to launch main activity again:
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
This doesn't work though. I still end up with two instances of my main activity. Does anybody know how to fix this?
By the way, I already have android:launchMode="singleInstance" in my manifest.
There's a way to force the OS to create only one instance of an activity and thats using the tag launchMode in the Manifest as shown below:
<activity android:name="YourActivity"
android:launchMode="singleInstance"/>
Hope this Helps...
Regards
Try adding this flag to the intent .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP), works for me.

How to bring an Activity to foreground (or create if not existing)?

I am intercepting sms messages with some information in them. Then in my SmsListener I'm creating notification to show in statusbar.
Then, when user clicks on a notification I want
Bring MainActivity to foreground (If such activity does not exist yet it should be created)
Pass to it data from the sms
Perform some ui changes basing on this data in this MainActivity
My activity is defined as
<activity
android:name=".MainActivity"
android:screenOrientation="sensor"
android:label="#string/app_name"
android:launchMode="singleTask"/>
Activity is launched as
Intent i = new Intent();
i.setClass(context, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
Also in my activity I have overridden method onNewActivity
#Override
public void onNewIntent(Intent intent){
super.onNewIntent(intent);
// I have data from broadcast in intent variable passed to this activity
processDataFromBroadcast(intent);
}
It works fine if the MainActivity already exists but if MainActivity does not exist it is started however onNewIntent was not called
Then I tried to invoke processDataFromBroadcast from onCreate: processDataFromBroadcast(getIntent()).
First time data is passed correctly from my broadcast to the activity.
However if MainActivity is sent to background and then again brought to foreground either onCreate or onNewIntent is called and processDataFromBroadcast is executed again with intent sent by broadcast and thus my MainActivity is updated with data from broadcast every-time the app is bringing to foreground - the latter is unwanted, how can I make my activity to forget this intent after first handling.
Here is sample application.
For an activity to launch only one instance of itself, have a look at the <activity> manifest element, and particularly android:launchMode. You want to configure it with either singleTask or singleInstance.
To pass data to your activity, you add data to the Intent you use to open it. To pass data with the intent, use the putExtra() methods of the intent before sending it off, and getExtra() methods to retrieve them in your receiving activity.
I'm assuming that you know roughly how intents work, but if not you could learn more about intents by taking a look at this Android developers article.
in case your problem is still unresolved, as I was just running into the same issue, here's how I solved it:
I am putting a timestamp as intentId as an extra upon the intent during it's creation. the first time, I am handling the intent in onCreate() or onNewIntent() I am reading the intentId and store it as the last intent handled. so the next time onCreate() or onNewIntet() is invoked I can check the intentId and if it equals the id of the last intent handled, I ignore it! It don't know if this helps in your case, maybe you can adopt it.
To keep intentId independent from activity lifecycles you could persist it in the userdefaults.
I agree that one would expect calling setIntent(new Intent()) in onNewIntent should do the trick.
It it late to answer, but it might be helpful to others looking for the solution.
Just add below lines of code :
Intent mIntent = new Intent(this, SplashActivity.class);
mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // You need this if starting the activity from a service
mIntent.setAction(Intent.ACTION_MAIN);
mIntent.addCategory(Intent.CATEGORY_LAUNCHER);
Where SplashActivity is the name of initial application that is the first screen of your application.
Hope it helps. :)

Categories

Resources