Android - Getting activity object from startActivity - android

I need to get the instance of the Activity that was created when startActivity() is called. However, startActivity() returns a void value.
I guess startActivity() doesn't wait until the Activity is created.
Is there a different way for me to get hold of the activity that was just created on the call to startActivity? Or, perhaps I can create an Activity instance myself and register it somewhere so that startActivity can find it.

Is the Activity you're trying to look at in your own app, or in another app?
If they're both your Activities, then it might be OK to do what you're trying to do, although Activities ought to remain separated. You might consider using Fragments instead, since they can "communicate" with each other through their parent Activity.
If they're not both in your app, then you can't get the other Activity instance, because by definition it's in another process. Moreover, the Android system prevents it, because it would be a big security hole.
In general, I squint a bit at attempts to get an instance of something outside of your own component, unless it's an instance of something in the system. Communication between components should be by Intent, bound Service features, or content URIs. Passing around instances leaves you open to memory leaks.

Related

Why do we need startActivityForResult() method instead of just setting Parent's public variables?

Since the child activity is created by calling the startActivity(intent) from the Parent Activity, it is guaranteed that the parent object exists while the child activity is running.
From that point of view, can I just manipulate the Parent's public variables at the child's class instead of calling startActivityForResult() after I come back?
Why do we need to use the method?
it is guaranteed that the parent object exists while the child activity is running.
No, it isn't. For starters, startActivityForResult() can be used across process boundaries, where the activity you are starting is in another app. The activity that is started cannot access the activity that started it, as they are in separate processes. Beyond that, it is possible that the process where the original activity resides will be terminated while it is in the background, as the user is in the second activity — this happens a fair bit when the second activity is a camera app, launched in response to something like an ACTION_IMAGE_CAPTURE Intent.
can I just manipulate the Parent's public variables
One activity has no access to another activity instance. The only way that would be possible is via static references to activities, which are tricky to get right without introducing memory leaks. And, again, that would only work where both activities are in the same process.
Why do we need to use the method?
You don't. There are any number of ways of writing UIs on Android. Few require the use of startActivityForResult(). For example, if these two bits of UI are that closely coupled, perhaps they should be in a single activity, where the bits of UI are separate fragments.

Android start main activity when another activity is called by broadcast

I am having an architectural problem with an Android project. I have the main activity(A) where a lot of stuff is initialized then I have 1 Activity(B) that handles some broadcasts from the system, this activity needs to access the stuff initialized by the main activity. If the app is killed and the activity (B) is called the onCreate of the Activity (A) is not called so the stuff is not initialized, how can I handle this situation properly?
That's a sign of not properly encapsulating the logic.
I don't know what your app is about, so that makes it difficult to generalize, but probably your Activity A has a lot of objects and variables related to you model, what you should do is isolate all this logic of your model in a single component, that you can initialize with a single call (or a few lines) either from activity A or B.
This logic can include opening files or sharedPreference, initializing objects, downloading data... Ideally all the logic is isolated from the user interface. The User Interface, on the other hand should be only responsible to present the data in a human readable (and hopefully enjoyable) way.
When first time your activity B is called, pass all initialization values to it from Activity A and save the in Activity B.
If app is killed and activity B is called, it have all the initialized values.
You should develop App using MVC arthitucture
Check this MVC Pattern in Android Development
This will help you batter.

How to make a core of activity on android?

I am new to Android development. After learning from many tutorials I got many Activities and many Fragments. How can I make a core engine to check what Activity is running and what Fragment is showing on a container?
Assume that I have:
Acivity01, Activity02, ... , Activity10
Fragment01, Fragment02, ... , Fragment10
I want to make a class that filters the Activity where Activity is on runtime and what Fragment is embeded to that activity.
How can I do this?
If I understand you correctly, you may want to store some references within your Application class to an Activity and to Fragment instance(-s), which are currently in foreground (by this I mean that user can instantly interact with Activity/Fragment).
As for Activity
Create some Activity field in your Application class and getter/setter methods for it (e.g., setCurrentActivity(), getCurrentActivity()). Then call setCurrentActivity() from onResume() method for each of your Activity instances. Don't forget to call setCurrentActivity, supplying null reference to ir in order to properly handle a case, when there are no foreground activities, but application is stll working.
As for Fragment
The general idea is similar to the first item, but there can be more than one Fragment instance in foreground state at time. So you need to store something like List, where you add your resumed fragments and remove paused.
You may also want to implement something similar for dialogs, for example. Then use the same strategy. Hope it will help.

Android: Access method in an activity from another activity

My launch activity starts up another activity whose launch is set to single instance. In this 2nd activity, I have a public method. I then start up a 3rd activity and that activity needs to access the public method in the 2nd activity. I don't want to use startActivity and pass it extras because I assume the onCreate will get called (or am I wrong?) and I need to avoid the 2nd activity from reinitializing itself.
When an activity is started using startActivity, is it possible to gain access to the underlying class instance itself and simply call the method?
I actually came up with a simple solution. As a matter of fact you can access the underlying class of an activity. First, you create a class that is used to hold a public static reference to activity 2. When activity 2 is created, in its onCreate method you store "this" in the static reference. Activity 2 implements an interface with the methods that you want available to any other activity or object. The static reference you hold would be of a data type of this interface. When another activity wants to call a method in this activity, it simply accesses the public static reference and calls the method. This is no hack but is intrinsic to how Java operates and is totally legitimate.
It is not a good idea.
As I can understand method from second activity is actually not connected to particular activity while you want to call it from another one. So carry the method out to other (non-activity) class (maybe static method) and use it from both activities.
It's not directly possible to gain access to activity object started using startActivity (without using some hacks). And frankly you shouldn't even trying to accomplish this.
One Activity component can cycle through several Activity java object while its alive. For example, when user rotates the screen, old object is discarded and new activity object is created. But this is still one Activity component.
From my experience, when you need to do things you described, there is something wrong with your architecture. You either should move part of activity's responsibilities to Service or to ContentProvider, or use Intents, etc. Its hard to recommend anything more specific without knowing more details.
No there is no way to pass a reference via startActivity() however you can use some sort of shared memory to keep reference to your Activity. This is probably a bad design. However passing an extra with your Intent will not cause onCreate, that is completely related to the lifecycle.

Difference between Activity Context and Application Context

This has me stumped, I was using this in Android 2.1-r8 SDK:
ProgressDialog.show(getApplicationContext(), ....);
and also in
Toast t = Toast.makeText(getApplicationContext(),....);
using getApplicationContext() crashes both ProgressDialog and Toast .... which lead me to this question:
What is the actual differences between a activity context and application context, despite sharing the wording 'Context'?
They are both instances of Context, but the application instance is tied to the lifecycle of the application, while the Activity instance is tied to the lifecycle of an Activity. Thus, they have access to different information about the application environment.
If you read the docs at getApplicationContext it notes that you should only use this if you need a context whose lifecycle is separate from the current context. This doesn't apply in either of your examples.
The Activity context presumably has some information about the current activity that is necessary to complete those calls. If you show the exact error message, might be able to point to what exactly it needs.
But in general, use the activity context unless you have a good reason not to.
I found this table super useful for deciding when to use different types of Contexts:
An application CAN start an Activity from here, but it requires that a new task be created. This may fit specific use cases, but can create non-standard back stack behaviors in your application and is generally not recommended or considered good practice.
This is legal, but inflation will be done with the default theme for the system on which you are running, not what’s defined in your application.
Allowed if the receiver is null, which is used for obtaining the current value of a sticky broadcast, on Android 4.2 and above.
This obviously is deficiency of the API design. In the first place, Activity Context and Application context are totally different objects, so the method parameters where context is used should use ApplicationContext or Activity directly, instead of using parent class Context.
In the second place, the doc should specify which context to use or not explicitly.
The reason I think is that ProgressDialog is attached to the activity that props up the ProgressDialog as the dialog cannot remain after the activity gets destroyed so it needs to be passed this(ActivityContext) that also gets destroyed with the activity whereas the ApplicationContext remains even after the activity gets destroyed.
You can see a difference between the two contexts when you launch your app directly from the home screen vs when your app is launched from another app via share intent.
Here a practical example of what "non-standard back stack behaviors", mentioned by #CommonSenseCode, means:
Suppose that you have two apps that communicate with each other, App1 and App2.
Launch App2:MainActivity from launcher. Then from MainActivity launch App2:SecondaryActivity. There, either using activity context or application context, both activities live in the same task and this is ok (given that you use all standard launch modes and intent flags). You can go back to MainActivity with a back press and in the recent apps you have only one task.
Suppose now that you are in App1 and launch App2:MainActivity with a share intent (ACTION_SEND or ACTION_SEND_MULTIPLE). Then from there try to launch App2:SecondaryActivity (always with all standard launch modes and intent flags).
What happens is:
if you launch App2:SecondaryActivity with application context on Android < 10 you cannot launch all the activities in the same task. I have tried with android 7 and 8 and the SecondaryActivity is always launched in a new task (I guess is because App2:SecondaryActivity is launched with the App2 application context but you're coming from App1 and you didn't launch the App2 application directly. Maybe under the hood android recognize that and use FLAG_ACTIVITY_NEW_TASK). This can be good or bad depending on your needs, for my application was bad.
On Android 10 the app crashes with the message
"Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?".
So to make it work on Android 10 you have to use FALG_ACTIVITY_NEW_TASK and you cannot run all activities in the same task.
As you can see the behavior is different between android versions, weird.
if you launch App2:SecondaryActivity with activity context all goes well and you can run all the activities in the same task resulting in a linear backstack navigation.
I hope I have added some useful information
I think when everything need a screen to show ( button, dialog,layout...) we have to use context activity, and everything doesn't need a screen to show or process ( toast, service telelphone,contact...) we could use a application context
Use getApplicationContext() if you need something tied to a Context that itself will have global scope.
If you use Activity, then the new Activity instance will have a reference, which has an implicit reference to the old Activity, and the old Activity cannot be garbage collected.

Categories

Resources