When i started my Android project i had a misunderstanding that every screen that's shown in the application must be a new activity. Now i am finished with the project , i have checked it on my emulator as well as on a couple of android phones. So far i am not witnessing any problems, but recently i read somewhere that too many activities in the application are a pretty bad idea.
Currently my application has around 15-20 activities.Ideally i heard it should be around 5-6. Do i need to re-structure my code or just finishing every activity after it has done it's part is enough?
While creating complex applications you definite need to create many activities. So it depends on your application how many activities you need. No of activities in a project do not affect the performance.
The effect is produced by the number of activities in the stack of your android. So it is better to keep 5-6 activities in the stack(Finish activities if they are not needed any more).
So create as many Activities as your application demands but keep smaller no of Activities open at a time.
If your project has many activities but some activity is not important,it means that you do not need any activity after another activity start.
In manifest file set : android:noHistory="true"
Example:
Activity1 -> Activity2 -> Activity3 -> Activity4..................-> Activity20
In manifest file:
activity android:name=".Activity1" android:label="#string/app_name" android:noHistory="true"
if u call again Activity1 using Intent than set finish() before startActivity()
I think this can help you
The Android system tries to maintain an application process for as long as possible, but eventually needs to remove old processes to reclaim memory for new or more important processes. This applies to Activitys that are running in the background... old Activitys are managed for you and are destroyed when the system needs to reclaim memory for new processes.
That being said, I think there are two things you should consider:
User experience. Does your app really require 15-20 Activitys? Can you cut down the number of screens somehow? Less Activitys is usually better, since it requires less interaction when the user is navigating the application.
Code design. While each Activity will have its own separate class, this does not restrict you from making smart design-decisions when implementing your application. For example, you might try grouping similar Activitys by having them extend an abstract class. As Android projects grow in size, they become more difficult to manage. Sharing code amongst similar classes in this manner will ensure that you can make simple changes to the core of your application without too much trouble.
[EDIT] - As of Google IO 2018, Google recommends using a single activity with many fragments. Something to consider.
It ultimately depends on what you're doing. There are some times when you can not modify the view enough to make a difference. Ideally, 5-6 activities is great, but some cases thats not just not doable. I've done a mobile app with around 40 different classes, and about 18 activities. It just HAD to be done that way based on how the app was to interact with the user. If you can merge 2 or 3 activities into one, thats great. It'll help with file size and optimization as well, but if you can't- Don't fret on it too much.
I would say 15 different screens = 15 different activities. I think one of the reasons some are able to reduce the number of activities is because of the introduction of fragments. Although one will argue why use fragments if individual activities works. I guess it depends on the developers preference.
It's better to use fragments than activities. We can use multiple fragments in single activity so we should always consider using fragments. I've seen complex applications with 5-6 activities and 150+ fragments.
Related
I've noticed that several sources encourage developers to only use a single activity in their projects. When would it be appropriate to have more than 1 activity in a project? Is there a limit to the number of composables an activity can have? 1 concern I have is for a large project requiring multiple screens, this can lead to heaps of code which eventually will become time consuming and difficult to scroll through and find.
It is not a particularly bad practice to make your app multi-activity-embedded, but the thing is -- In most of the cases, you do not need it. The users do not know what an activity is, since they simply look at the app in terms of the screens that the app offers. Therein lies the explanation. A single Composable can represent an entire screen super-easily, it's barely an inconvenience.
HENCE, the entire idea and need of multiple activities gets destroyed. Single activity apps are more efficient too, since there's only one activity so you do not have to explicitly handle the data-flow between various activities. This means a single ViewModel, minimal coupling, high code-readability, and easy data-flow.
This is the same reason that fragments are discouraged too. They often involve multiple viewModels which complicates things. When a Composable can accomplish everything on its own, it automatically becomes the best choice for developers to use to build screens. I would highly recommend, no matter the size of your project, that you stick to a single activity.
I can understand your viewpoint as well, and I have something to help.
The Navigation Codelab clearly and simply explains the Navigation System in Compose, which is a framework that basically allows you to create multiple screen-representing (or other) Composables, and then navigate to and from them from anywhere IN THE OS! It is actually super-easy to use, barely an inconvenience.
I was wondering if instead of having to create a new class for each activity is it possible to create mulitiple activities within one class?
So define various layout xml for various activities within one class, instead of having to create new classes for each activity.
Thanks
No, you should put each activity in seperate class. Take a look at this question. Someone is wondering just the same thing as you.
Ricky,
Yes, you may have multiple "Activities" defined inside a single class. But there are a lot of obstacles and issues with doing so. Before I answer this question, two things must be understood:
What you are asking goes against the Android guidelines for development, and those guidelines are enforced in as many ways as they can be during the compilation process, so nothing I say here is insured to work across any or all API versions of the Android SDK.
Different development environments do their own checks and compile in slightly different ways. I will be speaking from the Eclipse side of development.
Techniques listed here are for education, but introduce a lot of issues. For self education and theory, it is a wonderful practice to explore. However, the goal of this answer is to educate you as to why the guideline should be followed rather than sidestepped.
Requirements for an Activity
The first thing to understand is that Android has specific points that must be met for an Activity to be run. It must: a) be declared in the manifest; b) have an intent-filter describing how it is to be used; c) be a public class; d) be a top-level class.
Multiple Activities, Same Parent Class
This means that you may create an Activity inside of another class (an inner Activity, so to speak), but it must be declared static and public. This limits your Activity in a huge number of ways. Calls to methods or members that are instance-related (not static) to the parent class are not possible. So you lose a lot of time and code hacking around this.
Second, it affects your Android XML declaration for your Activity. This is where the real trouble comes in, because while it can be done, it is very specific and there is not any supporting documentation to make that happen. But that's okay, you wanted to know if you could make ONE class for your Activities.
Multiple Activities, Same Class
Well, Android determines which Activity to run based on its Intent. You could declare the same class multiple times, but with different Names and Intent-filters. If this is the case, then you would have to determine what to do based on the Intent and the extras included. This would be done in your onCreate() method.
Doing things in this manner would mean that you would have to code for two Activities in every place that you would normally deal with one. This would make it much harder to track down bugs to support your product. It would also make every routine operation take longer as you would have to decide which method to perform. For instance, if you overrode onDraw(), you would have to know which Activity you were drawing. Its ultimately just a big schmorgasborg (sp? does anyone know how to spell that word?) of "what do I do?!"
The Real Question
Why would you want to do this anyway?
1. If the answer is to save yourself time navigating your own project, believe me... That won't really happen. Your code will be harder to read, interpret and debug.
If the answer is that you want to save file space, I would reconsider your project's priorities.
If the answer is that you want to share functionality, consider extending Activity and then extending your new sub class. How do you think they made the ListActivity or TabActivity to begin with?
If you want to save state, you can place state in SharedPreferences or your Application object (if you have extended it).
As you can see, no matter your needs, there are many other ways to go about it in a way that doesn't cause you or anyone else a hassle.
Hope this helps,
FuzzicalLogic
This is actually a very simple thing: I need to know if there is any of MY activities in the history stack? I'm not talking about other apps, just my own app. And I don't even need to know what are they or how many of them, I just need to know IF THERE IS ANY? Is there a way to achieve this? (ActivityManager.getRunningTasks().topActivity() is not for this purpose.)
(I'm implementing a backward/forward feature, as seen in many browsers. At first I tried to manage my own history stack and not use Android's at all. So I used noHistory=true for all activities in the manifest. This leads to the problem that the app's behavior is weird when it comes to the interacting with other apps or the Launcher. Now I tried to utilize Android's history stack for Backward operation, but my own stack for Foreward. But then it hits an unexpcted problem. .... Not just that, there is this security consideration in the app so that I can't let the user go back to any activity if the file has been locked up. I have to have total control over the stack.
Having been bothered by Android's activity life-cycle model and the history stack for several days. Extremely inflexible. How can they assume that all applications all activities in the world behave in the way they imagined in the lab!!!??? Seeing lots of people asking questions on the Internet in this area, and it seems to me everybody hit a dead end and then try to find some work-around, or compromise, or might as well change the spec. Android has been around for 3 years now, but they still didn't do anything to make it more flexible. I guess it must be a very fundamental thing in the design since Day One so that they know about the problem, but they can't do anything about it. Call it a wrong design.)
(And this non-blocking, non-synchronize dialog/message boxes. I don't know how they come up with this design. Whenever you want the user to confirm something, you have to break the program flow into several parts. This undoubtedly makes the program difficult to write and impossbile to maintain! If you have a series of questions one dependent on another, you might as well limplement a state machine.)
If you use Fragments in SDK level 11 and higher (so Honeycomb and certain Gingerbread levels), you can explicitly manage the stack. For regular Activities, you really don't have access to the stack, so you're out of luck there. You could possibly implement a personal stack using an application-level stack: storing the Intents you're using to launch Activities so you can move forward and then returning another Intent with the configuration data for each Activity (when each Activity finish()es you pass this state in the onActivityResult call back).
It would be very messy though.
Since you create and finish the activities, you should be aware of what is on the stack at runtime. Generally, you can control the stack pretty well. Take a look at the ApiDemo revolving around manipulating the stack.
hey people,
I have almost finished writing my first android app. It is a note taking app with add, edit view screens etc...
Initially I was handling moving between screens in a single activity by creating new layout objects such as tables etc... and displaying them.
However after some more reading I have changed my method of moving between screens by using different activities for different screens. However each activity that is called as an intent retrieves a large number of variables from the main activity via setExtra and passes back a large number of variables as well.
Now I want my app to be as efficient as possible and I personally think that handling it all in one activity is less memory hungry and processor intensive although this has the negative of meaning variables are always present (and consuming memory) unlink in a separate activity where they are killed on finish().
But you guys are more knowledgeable then me so what do you think is the best way to do it?
If you launch a new activity for the new screens then you will add that activity to the stack. That way a user can press back and get back to the previous activity. Just changing the layout removes this functionality. I doubt very much you'll have performance issues either way.
Best practice would be to start a new activity, best performance might be to use your current approach.
All your activities will reside and run from the same process. So there is no reason you need to pass around a pile of variables. You could (for example) stick them in a singleton which represents your context. When one activity hands over to another it fills in the singleton and the next one picks up its data from there.
Of course if you ever intend an external activity to interact with your ones you may have to rethink this approach, but I think you'd be fine to keep your views as separate activities. Even if memory is ever so slightly higher, I think it's better to do things correctly and only worry about optimization if and only when it becomes obvious you need it.
This pattern is similar to the pattern Main Servlet (the Front Controller) that is used for developing web applications.
The main idea of this pattern: we have one Activity that manages multiple views and this activity is responsible for representing current content. Not all views need functional of activity (e.g. life-cycle methods) so the main question is: if I can go without activity why do I have to use it?
I have found the following disadvantages of using this pattern:
Official source doesn't recommend to Overload a Single Activity Screen
but they don't explain why.
We cannot use TabActivity, ListActivity, MapActivity. But there are some tricks to go without them.
If different screens have different menu it's a problem to make that without activities.
It is necessary to keep history by ourselves. But it's not so difficult to develop.
I have found the following advantages of using this pattern:
It's faster to change the content of current activity than to start another activity
We are free to manage history as we want
If we have only one activity-context it's simpler to find and solve problems with memory leaks
What do you think about this pattern ? Could you provide any other advantages/disadvantages ?
We cannot use TabActivity, ListAcivity, MapActivity. But there are some tricks to go without them.
You have to use MapActivity if you want to use MapView. You have to use PreferenceActivity if you want to use preference XML.
It is necessary to keep history by ourselves. But it's not so difficult to develop.
The difficulty in managing your own history will depend greatly on what the history needs to be. Implementing history for a simple wizard will be fairly easy. However, that is a particularly simple scenario. There is a fair amount of history management code in Android that you would have to rewrite for arbitrary other cases.
You also forgot:
#5. You will be prone to leak memory, because you will forget to clean up stuff, and Android will not clean up stuff (since it assumes that you will be using many small activities, the way they recommend).
#6. Your state management for configuration changes (rotation, dock, SIM change, locale change, multiple displays, font scale) will be more complicated because now you also have to figure out what extra stuff (e.g., history) need to be part of the state, and you have deal with all of them at once rather than activity-at-a-time.
#7. Having multiple entry points for your application becomes more challenging (e.g., multiple icons in launcher, app widget linking to some activity other than the main one, responding to etc.).
It's faster to change the content of current activity than to start another activity
For most modern Android devices, the speed difference will not be significant to most users, IMHO.
If we have only one activity-context it's simpler to find and solve problems with memory leaks
Except that you still have more than "one activity-context". Remember: your activity, large or small, is still destroyed and recreated on configuration changes.
What do you think about this pattern ?
Coase's "nature of the firm" theory says that businesses expand until the transaction costs for doing things internally become higher than the transaction costs for having other firms do the same things.
Murphy's "nature of the activity" theory says that the activity expands until the transaction costs of doing things internally become higher than the transaction costs for having other activities do the same things. Android developers will tend towards a "user transaction" model for activities -- things that are tightly coupled (e.g., steps in a wizard) will tend to be handled in single activity, and things that have little relationship (e.g., browse vs. search vs. settings vs. help vs. about) will tend to be handled in distinct activities.
This will be horrible to maintain if new functionality is added later on.
I'm also not convinced it will be so much faster that the user could notice.
Having components as smaller pieces that are easier to change or swap out is definitely the way to go.