what will happen is i will use Application context on dialog? - android

Assume i has activity A and B and external class C.
class C contains code to create dialog but requires contex.
class B is like this one
activity A is in focus(active).
Activity A call C to create dialog.
In first case, A send's it's ActivityContext to C.
In second case, C get application activity from B.
Are those two cases leads to same result? E.G dialog will pop up on a screen (on a screen of activity A)

Yes,
In android there's only 1 "Context" per application, is what documentation calls as Application Context, is where pretty much every single component related to your activity lives, so it doesn't matter what activity context reference you are using, in the end is the same since all the activities live within it, and taking on count that this app context follows the singleton design pattern be sure that is the very same instance object within the virtual machine...
Regards!

Related

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.

can I use activiy one time(register activity) and switch the main launcher to different activity?

can I use activiy one time(register activity) and switch the main launcher after using to different activity?
another question if I may,
If I create parameter x in one of the activities in my application, can I use this parameter in other activities?...If yes, how I can do that?
thanks :)
You cannot dynamically change the launcher activity once it has to be only 1 activity that is defined in the manifest file.
I would recommend having something like a landing or splash activity which checks a shared preference variable, to decide which activity to launch, for example either a login activity or another activity.
You should not access a variable in an activty from another activity, you should store these in data holding classes. however if you want to do it, for a good reason, simply make it static.
You cannot adjust the manifest after running your application. What you can do is have your default launcher activity write to SharedPreferences once it has been run once. Inside of that activity check to see if that preference has been set and if it has just finish that activity and launch your new activity, the user will not see anything if you do this in the onCreate of the launcher activity.
As for passing params between activities you should use intent extras. For example to pass a string use putExtra(String key, String value), and to get that parameter inside of the new activity use getStringExtra("Key").
For global variables accessable from different activities you can also extend Application class and then access it via getApplicationContext().
1. One time activity launch
You can't change the main launcher. It's a static information. What you could do is following:
// in the beginning of onCreate
// first launch could be loaded from shared preferences
// see 2. for more
if (!firstLaunch) {
// start another activity
finish();
return;
}
2. Use data in another activity
One way is to persist the data and load it somewhere else. You will find all information you need in the Data Storage article.
If your data is primitive you could try to pass it by intent to another activity. See Using integer from one class in another Android.
If it is complex you could try to implement an own Application class and use helper methods to access global data. See Android: Accessing resources without an Activity or Context reference.
Be careful with that, please read the Avoiding Memory Leaks article then.

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.

Invoke a dialog from another activity

I have Activity A which defines a dialog using AlertBuilder.create etc. This Activity invokes the dialog using showDialog(dialogID). dialogID is declared and recognized in all classes/activities. Everything works perfectly in Activity A.
My question is when trying to invoke this same dialog -- showDialog(dialogID) -- from another Activity (Activity B) the application crashes. Can anyone help?
How to invoke a dialog from multiple activities?
Thanks in advance.
Andy
My question is when trying to invoke
this same dialog --
showDialog(dialogID) -- from another
Activity (Activity B) the application
crashes.
How do you invoke the dialog from Activity B? Just to let you know, you do not instiante activities (so no new ActivityA().showDialog(id).
What you can do is
Create a class that extends AlertDialog.Builder and accept a Context parameter in the constructor. You can customize the text, buttons and other things.
From your activity, in your onCreateDialog, you can just instantiate your class and call create() on it. And your class will be accessible from any activities.
I don't think you can accomplish what you want without hooking up a similar entry point in your new activity.
showDialog(int id)
The id is unique within the activity that launches it. So if two activties A and B both call showDialog(1); That will do something different in each unless someone has coded the same code path for them in their onDialogCreate() and onPrepareDialog methods. So in your onDialogCreate of the original activity, that code will have to exist in both activities. You can sometimes get way with creating a new Dialog type that does all the initialization internally based on a given context and just call show() on it. The problem with this solution usually arises when the context is no longer valid and you need to dismiss or show it. Basically though when using showDialog() it's on a per activity basis.
I don't think that's possible.
Dialog built in Activity A, belongs to Activity A.
No matter if you store its ID in a global data space. It won't be available to be used in Activity B.
You'll have to create another Dialog in Activity B

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