How to stack android

Tasks и Back Stack в Android

Итак. Каждое Android приложение, как минимум, состоит из фундаментальных объектов системы — Activity. Activity — это отдельный экран который имеет свою отдельную логику и UI. Количество Activity в приложении бывает разное, от одного до много. При переходах между различными Activity пользователь всегда может вернуться на предыдущую, закрытую Activity при нажатии кнопки back на устройстве. Подобная логика реализована с помощью стека (Activity Stack). Его организация «last in, first out» — т.е. последний вошел, первый вышел. При открытии новой Activity она становится вершиной, а предыдущая уходит в режим stop. Стек не может перемешиваться, он имеет возможность добавления на вершину новой Activity и удаление верхней текущей. Одна и та же Activity может находиться в стеке, сколько угодно раз.
Task — это набор Activity. Каждый таск содержит свой стек. В стандартной ситуации, каждое приложение имеет свой таск и свой стек. При сворачивании приложения, таск уходит в background, но не умирает. Он хранит весь свой стек и при очередном открытии приложения через менеджер или через launcher, существующий таск восстановится и продолжит свою работу.

Ниже покажу картинку, как работает стек.

Если продолжать нажимать кнопку back, то стек будет удалять Activity до того, пока не останется главная корневая. Если же на ней пользователь нажмет back, приложение закроется и таск умрет. Кстати, я говорил о том, что когда мы сворачиваем наше приложение и запускам например новое, то наш таск просто уходит в background и будет ждать момента, пока мы его вызовем. На самом деле есть одно «но». Если мы будем иметь много задач в background или же просто сильно нагружать свое устройство, не мала вероятность того, что таск умрет из за нехватки системных ресурсов. Это не война конечно, но то что мы потеряем все наши текущие данные и наш стек очистится — это точно. Кстати для избежания потери данных в таком случаи, вам стоит почитать про SavingActivityState.

Маленький итог

Управление тасками

Существует два пути для изменения стандартной организации тасков. Мы можем устанавливать специальные атрибуты в манифесте для каждой Activity. Также мы можем устанавливать специальные флаги для Intent, который запускает новую Activity с помощью startActivity(). Заметьте, что иногда атрибуты в манифесте и флаги в Intent могут противоречить друг другу. В этом случаи флаги Intent будут более приоритетны.

Атрибут launchMode

Для каждой Activity в манифесте можно указать атрибут launchMode. Он имеет несколько значений:

  • standard — (по умолчанию) при запуске Activity создается новый экземпляр в стеке. Activity может размещаться в стеке несколько раз
  • singleTop — Activity может распологаться в стеке несколько раз. Новая запись в стеке создается только в том случаи, если данная Activity не расположена в вершине стека. Если она на данный момент является вершиной, то у нее сработает onNewIntent() метод, но она не будет пересоздана
  • singleTask — создает новый таск и устанавливает Activity корнeвой для него, но только в случаи, если экземпляра данной Activity нет ни в одном другом таске. Если Activity уже расположена в каком либо таске, то откроется именно тот экземпляр и вызовется метод onNewIntent(). Она в свое время становится главной, и все верхние экземпляры удаляются, если они есть. Только один экземпляр такой Activity может существовать
  • singleInstance — тоже что и singleTask, но для данной Activity всегда будет создаваться отдельный таск и она будет в ней корневой. Данный флаг указывает, что Activity будет одним и единственным членом своего таска

На самом деле не важно, в каком таске открыта новая Activity. При нажатии кнопки back мы все равно вернемся на предыдущий таск и предыдущие Activity. Единственный момент, который нужно учитывать — это параметр singleTask. Если при открытии такой Activity мы достанем ее из другого background таска, то мы полностью переключаемся на него и на его стек. на картинке ниже это продемонстрировано.

Флаги

Как и говорил, мы можем устанавливать специальный флаги для Intent, который запускает новую Activity. Флаги более приоритетны, чем launchMode. Существует несколько флагов:

  • FLAG_ACTIVITY_NEW_TASK — запускает Activity в новом таске. Если уже существует таск с экземпляром данной Activity, то этот таск становится активным, и срабатываем метод onNewIntent().
    Флаг аналогичен параметру singleTop описанному выше
  • FLAG_ACTIVITY_SINGLE_TOP — если Activity запускает сама себя, т.е. она находится в вершине стека, то вместо создания нового экземпляра в стеке вызывается метод onNewIntent().
    Флаг аналогичен параметру singleTop описанному выше
  • FLAG_ACTIVITY_CLEAR_TOP — если экземпляр данной Activity уже существует в стеке данного таска, то все Activity, находящиеся поверх нее разрушаются и этот экземпляр становится вершиной стека. Также вызовется onNewIntent()
Читайте также:  Легкий скриншот для андроид

Affinity

Стандартно все Activity нашего приложения работают в одном таске. По желанию мы можем изменять такое поведение и указывать, чтобы в одном приложении Activity работали в разных тасках, или Activity разных приложений работали в одном. Для этого мы можем в манифесте для каждой Activity указывать название таска параметром taskAffinity. Это строковое значение, которое не должно совпадать с названием package, т.к. стандартный таск приложения называется именно как наш пакет. В общем случаи данный параметр указывает, что Activity будет гарантированно открываться в своём отдельном таске. Данный параметр актуален, если мы указываем флаг FLAG_ACTIVITY_NEW_TASK или устанавливаем для Activity атрибут allowTaskReparenting=«true». Этот атрибут указывает, что Activity может перемещаться между тасками, который её запустил и таском, который указан в taskAffinity, если один из них становится активным.

Чистка стека

Если таск долгое время находится в background, то система сама чистит его стек, оставляя только корневую Activity. Данное поведение обусловлено тем, что пользователь может забыть, что он делал в приложении до этого и скорее всего зашел в него снова уже с другой целью. Данная логика также может быть изменена с помощью нескольких атрибутов в манифесте.

  • alwaysRetainTaskState — если флаг установлен в true для корневой Activity, то стек не будет чиститься и полностью восстановится даже после длительного времени
  • clearTaskOnLaunch — если установить флаг в true для корневой Activity, то стек будет чиститься моментально, как только пользователь покинет таск. Полная противоположность alwaysRetainTaskState
  • finishOnTaskLaunch — работает аналогично clearTaskOnLaunch, но может устанавливаться на любую Activity и удалять из стека именно её

Это всё для данного топика. Статья не импровизированная, а по сути является вольным переводом официальной документации. Рекомендую собрать легкий пример и поэксперементировать с флагами и атрибутами. Некоторые моменты, лично для меня были, неожиданно интересными. любые ошибки и недоработки учту в лс. Спасибо.

Источник

Best Tech Stack for Mobile App Development in 2021

Today making a good mobile application means satisfying a lot of user’s preferences. It is important to provide great work quickly, with a high-level of security, and an attractive interface. To cover all these points we need to choose a good technology stack for mobile applications. It allows us to reduce spending on app development, saves time, offers new prospects and makes future project improvement easier and more flexible. So what is a technology stack for mobile development and how to make the right choice? What are the differences between the creation of Android and iOS apps? Is it possible to make a cross-platform mobile application? Let’s make a quick review of these questions and highlight the main points which will help us to set the right goals.

What Is Mobile Development Stack?

Creating a new app is somehow similar to building a house: you need to have a good foundation in order to provide a good, solid product. In our case, we must pick the best mobile app technology stack, which refers to the union of language, platform, framework, and other tools used for the development of the application.

Mainly we are focusing on such mobile stack categories as:

  • Front-end, also known as client-side development. It refers to the development of the interface which is going to interact with end-users;
  • Back-end, a data access layer, which is connected with databases, scripting, website architecture, and server-side development in general;
  • Development that refers us to the tools which provide libraries and interfaces to build the application;
  • Supporting, the main idea of which is providing security, high functionality, and future long-term improvement.

But this list can be modified, depending on the client’s needs and the platform that the app is going to be made for.

Why Is It Important to Make the Proper Decision?

That leads us on to another related question: why is it important to choose the right mobile app stack? There are several variants of them and inappropriate choices can lead to a deviation from the original idea or even using the wrong application architecture. This issue can cause an increased final cost, lasting error recovery, and an over-running deadline.

Technology Stack for iOS apps in 2021

Android and iOS are structurally different from one another. Due to this nuance, they need their own style of technology stacks. Now let us speak in more detail using an example of actual iOS development environments:

  • Programming languages.Two major languages are commonly used for iOS apps development. They are Objective-C and Swift.

Objective-C is an Apple-supported language that is used for building iOS applications. It offers object-oriented potential and a dynamic runtime environment. But because of its complexity, more developers prefer to use Swift. According to a Stack Overflow survey 68% percent of Оbjective-С developers are not interested in continuing to use this language.

Читайте также:  Телевизор яндекс платформа или андроид

Swift is a relatively new language. There are no string identifiers, leading to fewer mistakes. The amount of code required here is much less and it’s easier to understand, edit and debug. Swift preferable language to use in 2021 beacause of it’s speed, readbility and simplicity.

iOS development tools. There are a few popular toolsets like Xcode and Appcode.

Xcode IDE is powered by Apple and it grants access to all the essential features required to build a native iOS mobile app. This tool provides developers all necessary functions for user interface design, coding, and testing.

Appcode is another integrated development environment, but powered by a third-party. It has a flexible setting system, which allows optimum productivity.

UI Frameworks. For building user interfaces, developers commonly use UIKit and SwiftUI.

UIKit is the basic framework for constructing and managing graphical components in iOS applications.

SwiftUI is quite similar to UIKit and they can connect to each other. But because of the later introduction of SwiftUI, it supports only the latest versions of iOS. By applying this framework, you may possibly lock-out users running older versions of iOS.

Technology Stack for Android Apps in 2021

To build a native app for the Android OS we can apply the following Android app stack:

There are two popular languages for developing Android apps. Today Java is considered to be the most popular language for making Android apps. It gives one of the best options to build Android applications, as they are based on Android APIs and a huge variety of built-in Java libraries. In this way, Java helps to quickly and efficiently develop applications for the above-mentioned OS.

Kotlin is essentially lightweight and less verbose than Java. It is not an academic language that was invented in the scientific community for specific tasks. It was created by developers specifically for developing Android applications. At the same time, it is fully compatible with Java Virtual Machine and allows us to use both frameworks for developing the app.

  • Android development tools

Android Studio and Android Developer Tools (ADT) are great tools to develop Android apps. Android Studio is the official development platform powered by Google. It contains code editing and debugging tools, provides a user-friendly intuitive interface and all the necessary means to create high-quality apps. In this tool, we can find a great variety of visual layouts and drag-and-drop features.

Apart from the basic coding and debugging tools, ADT provides developer specific coding and test automation support, a graphical UI builder, and other specific features. It is a stable and well-supported tool designed to provide a powerful, integrated environment in which to build high-quality apps.

Android provides pre-built Android UI software. It allows developers to easily build user interfaces. Jetpack Compose is another modern UI kit for building a native Android user interface. It simplifies and accelerates UI development. This framework requires less code, introducing powerful tools, and intuitive Kotlin APIs.

Ready to build your app?

Contact LANARS to find the proper team and estimate your idea

Technology Stack for Cross-Platform Apps

If a new project is aiming to support both Android and iOS, the best option is to turn to cross-platform app development. This approach guarantees the same interface and UX for the two main operating systems. One development team and one set of code will bring the application as close as possible to a single UI and UX format across all platforms. This way of developing apps allows devs to use a single code base for both operating systems.

Here we are providing the most pertinent stacks that are commonly used.

Flutter

Flutter is a Google-powered tool for cross-platform development. It’s based on the Dart programming language and with its built-in widgets provides smooth and quick performance. But keep in mind that this tool is quite new and may not support some required functions.

React Native

React Native is a framework based on JavaScript or TypeScript for creating mobile applications. This tool exploits the same UI building blocks which are used in Android and iOS. It provides quick and simple error detection, high functionality, and a simple interface.

Xamarin

Xamarin is usually accomplished with the C# language. This framework provides direct access to the native APIs of both operating systems and allows the use of an open-source and complete toolkit. Unlike the other frameworks, this one has limited free functionality and some specific pay-for-use features.

Technology Stack for Hybrid App Development

Hybrid app development is commonly used for building applications on HTML5, CSS, and JavaScript. These programs function like websites and they behave something in between regular apps and rendered-in browser web pages. For this type of development, the usual approach is to use such stacks as Cordova/PhoneGap and Ionic. Let us try to explore the pros and cons of each variant.

Читайте также:  Самсунг а31 андроид или смартфон

Cordova/PhoneGap

Cordova/PhoneGap is an open-source framework that runs HTML and JS-based applications, that can work with hardware features including accelerometer, location, GPS (location), speakers, and other devices. The framework is also supported by a fairly powerful server-side, which means that mobile apps developed with Cordova function faster. It provides its users with a plugin system that omits the limitations of the browser and can access all mobile device capabilities.

Ionic

Ionic is ideal for building hybrid mobile apps using web technologies, including CSS and HTML5. It is a great tool with unique features and services for creating primarily interactive applications. Ionic has a whole library of components and tools optimized for mobile devices. Ionic’s cross-platform capability allows developers to spend less time building applications.

How To Choose The right Mobile Technology Stack

Now we have a better picture of possible mobile development technologies, their features, and benefits, let us try to figure out what stack best suits the requirement set. While choosing it, we need to outline project goals and essential features of the future project. This will help the development team to make the best product that will cover all necessary demands.

General app requirements. There are hundreds of different apps that cover different spheres and needs. While creating the general app idea, concretely set all objectives, choose the right target platform and figure out the key features of the future application.

The main Goals of the upcoming App. When choosing the best tech stack for mobile app development, setting the mobile app goals plays a crucial role. The technology stack can vary when a high-latency-based app is compared with a low-latency application. Also, if the app demands heavy load processing, this points towards a better and stronger tech stack as compared to apps with streamlined and precise interactions.

The best platform for mobile app development. The notion of “the best platform” is quite irrelevant in application development. While planning to create a new product it is necessary to keep in mind such features as its functionality, user demographic, and what key expectations & needs should be covered, based on how people use a specific service.

Type of the future project. When you know the main advantages of hybrid, native, and web apps, choose the best type which is going to satisfy your requests. Depending on which sphere the app is going to be used in, the correct choice of project type can improve user experience and lead to great success for the product.

Budget and timelines. Different functionalities can influence the project type, its cost, and required time for the final result. Think about all the requirements and reject any excessive features. This will speed up program development and reduce unnecessary spending.

Data safety and general security. Today this question is highly discussed. Everyone wants to know that their data is safe and even the smallest leak will break a user’s trust and as a result, damage the reputation of the company. This is the reason why choosing the best tech stack is a crucial point that precludes the product’s favorable result.

From our personal experience, following modern trends and trying to join the wave of temporarily popular programs is not a good idea. In the future perspective, such a product will take much more effort to support it and as a result, can turn into a big failure. By researching the market’s needs and predicting upcoming tendencies, this strategy guarantees longer relevance of the program that means higher client’s interest and long-term prosperity.

Mobile Development Stack At LANARS

Based on our experience in developing mobile applications, we can advise you on which dev stack as the best variant for your upcoming project.

Bottom Line

The global expansion of smartphones and the growing popularity of mobile applications has attracted the attention of developers. Entering new grounds where, without much effort, we can easily make a financially successful product creates encouraging perspectives. Choosing the correct technology stack is one of the main points in the creation of a successful project, with prospects for further growth and development. There are no good or bad stacks, but choosing which one is right for you takes skill and expertise..

Ready to build your app?

Contact LANARS to find the proper team and estimate your idea

Источник

Оцените статью