- Урок 21. Создание и вызов Activity
- Android Activity
- Activity State and Callback Methods
- Activity Callback Methods
- Create Activity
- onCreate()
- onPause()
- Start Activity
- Finish Activity
- onFinish()
- Difference between onPause(), onStop() and onDestroy()
- Example of Android Activity
- activity_main.xml
- activity_sub.xml
- MainActivity.java
- ActivityStatus.java
- SubActivity.java
- Output
- Download Android Activity Source Code
- Popular Articles
Урок 21. Создание и вызов Activity
Мы подобрались к очень интересной теме. На всех предыдущих уроках мы создавали приложения, которые содержали только один экран (Activity). Но если вы пользуетесь смартфоном с Android, то вы замечали, что экранов в приложении обычно больше. Если рассмотреть, например, почтовое приложение, то в нем есть следующие экраны: список аккаунтов, список писем, просмотр письма, создание письма, настройки и т.д. Пришла и нам пора научиться создавать многоэкранные приложения.
Application/Library name: TwoActivity
Module name: p0211twoactivity
Package name: ru.startandroid.p0211twoactivity
Откроем activity_main.xml и создадим такой экран:
На экране одна кнопка, по нажатию которой будем вызывать второй экран.
Открываем MainActivity.java и пишем код:
package ru.startandroid.develop.p0211twoactivity; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends AppCompatActivity implements OnClickListener < Button btnActTwo; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnActTwo = (Button) findViewById(R.id.btnActTwo); btnActTwo.setOnClickListener(this); >@Override public void onClick(View v) < switch (v.getId()) < case R.id.btnActTwo: // TODO Call second activity break; default: break; >> >
Мы определили кнопку btnActTwo и присвоили ей Activity в качестве обработчика. Реализация метода onClick для кнопки пока заполнена частично — определяем, какая кнопка была нажата. Чуть позже здесь мы будем вызывать второй экран. Но сначала этот второй экран надо создать.
Если помните, при создании проекта у нас по умолчанию создается Activity.
От нас требуется только указать имя этого Activity – обычно мы пишем здесь MainActivity. Давайте разбираться, что при этом происходит.
Мы уже знаем, что создается одноименный класс MainActivity.java – который отвечает за поведение Activity. Но, кроме этого, Activity «регистрируется» в системе с помощью манифест-файла — AndroidManifest.xml.
Давайте откроем этот файл:
Нас интересует тег application. В нем мы видим тег activity с атрибутом name = MainActivity. В activity находится тег intent-filter с определенными параметрами. Пока мы не знаем что это и зачем, сейчас нам это не нужно. Забегая вперед, скажу, что android.intent.action.MAIN показывает системе, что Activity является основной и будет первой отображаться при запуске приложения. А android.intent.category.LAUNCHER означает, что приложение будет отображено в общем списке приложений Android.
Т.е. этот манифест-файл — это что-то типа конфигурации. В нем мы можем указать различные параметры отображения и запуска Activity или целого приложения. Если в этом файле не будет информации об Activity, которое вы хотите запустить в приложении, то вы получите ошибку.
Android Studio при создании модуля создала MainActivity и поместила в манифест данные о нем. Если мы надумаем сами создать новое Activity, то студия также предоставит нам визард, который автоматически добавит создаваемое Activity в манифест.
Давайте создадим новое Activity
Жмем правой кнопкой на package ru.startandroid.p0211twoactivity в папке проекта и выбираем New -> Activity -> Empty Activity
В появившемся окне вводим имя класса – ActivityTwo, и layout – activity_two.
package ru.startandroid.p0211twoactivity; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class ActivityTwo extends AppCompatActivity < @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_two); >>
В setContentView сразу указан layout-файл activty_two.
Откройте activty_two.xml и заполните следующим кодом:
Экран будет отображать TextView с текстом «This is Activity Two».
Сохраните все. Класс ActivityTwo готов, при отображении он выведет на экран то, что мы настроили в layout-файле two.xml.
Давайте снова заглянем в файл манифеста
Появился тег activity с атрибутом name = .ActivityTwo. Этот тег совершенно пустой, без каких либо параметров и настроек. Но даже пустой, он необходим здесь.
Нам осталось вернуться в MainActivity.java и довершить реализацию метода onClick (нажатие кнопки), а именно — прописать вызов ActivityTwo. Открываем MainActivity.java и добавляем строки:
case R.id.btnActTwo: Intent intent = new Intent(this, ActivityTwo.class); startActivity(intent); break;
(добавляете только строки 2 и 3)
Обновите импорт, сохраните все и можем всю эту конструкцию запускать. При запуске появляется MainActivity
Нажимаем на кнопку и переходим на ActivityTwo
Код вызова Activity пока не объясняю и теорией не гружу, урок и так получился сложным. Получилось много текста и скриншотов, но на самом деле процедура минутная. Поначалу, возможно, будет непонятно, но постепенно втянемся. Создадим штук 5-6 новых Activity в разных проектах и тема уляжется в голове.
Пока попробуйте несколько раз пройти мысленно эту цепочку действий и усвоить, что для создания Activity необходимо создать класс (который наследует android.app.Activity) и создать соответствующую запись в манифест-файле.
— разбираемся в коде урока 21
— теория по Intent и Intent Filter (не пропустите, тема очень важная)
— немного о Context
Присоединяйтесь к нам в Telegram:
— в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.
— в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Compose, Kotlin, RxJava, Dagger, Тестирование, Performance
— ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня
Android Activity
Activity is an Android component that is created as a virtual box. User interface has to be designed on top of this box to allow user to interact with this activity. This is exactly like the HTML’s box method where each HTML tag is considered as a box. Users interact with an android app using screens provided by activity.
An Android app can have multiple activities and one among them will be designated as main activity. If an android app has more than one activity, only one of them can be in active state at a time. These states of the activity are maintained by a stack called back stack. Currently running activity will be on top of the stack. When a new Activity starts the older activity is pushed down the stack and the current activity becomes the top element in the stack which is given user access.
Activity State and Callback Methods
Each activity is interlinked by calling other activities. These subsequent calls form activity life cycle which will be handled by activity manager by interacting. An android activity life cycle consists of three states namely,
Activity Callback Methods
When an activity transitions from one state to another, system calls the given callback methods. Following are the available callback methods,
- onCreate()
- onStart()
- onPause()
- onResume()
- onStop()
- onRestart()
- onDestroy()
Create Activity
To create an Android activity, a class needs to be written extending the Activity class and by writing the callback methods corresponding to create, stop, resume or destroy operations. These methods (listed above) will be called based on the various stages of the activity among the life cycle process.
Example Activity which has only two callback methods,
public class MainActivity extends Activity < @Override public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); objStatus.updateStatusList("MainActivity","Created"); >@Override protected void onPause() < super.onPause(); objStatus.updateStatusList("MainActivity","Paused"); >>
onCreate()
onCreate() method is the primary callback method which is called when an activity is created. For example, operations like initialization and layout projection will take place.
On projecting layout, View is an important term which is a class that occupies the activity box. Each activity has several views that are coming from viewGroup. There are some built in viewGroup such as form widgets and layout. User can also create their set of views covered by viewGroup. Views are shown using setContentView() method.
onPause()
When an activity goes out of focus, onPause() method is invoked by andoird system. Pause is the preparation stage before running another activity. This is the place where the existing state of the activity should be persisted.
An Android activity should be declared in the Android manifest file.
For example, the activity is declared as below in the manifest file,
In this android:name property represents the class name of the activity. is used to declare the action and category of the activity. By default, the action will be MAIN and category will be LAUNCHER as shown in the code.
Start Activity
startActivity() method is used to start another activity. This is done by creating an Intent,
Intent objIntent = new Intent(MainActivity.this, SubActivity.class); //or Intent objIntent = new Intent(Intent.ACTION_MAIN);
After instantiating indent, startActivity() is used to start an activity with this instance.
Finish Activity
To finish an activity finish() method should be called. This is applicable for the currently active activity. Example,
But, if we want to close a specific activity, then an Intent should be created and passed on to this method as below,
Intent objIntent = new Intent(this, MainActivity.class);
finishActivity(objIntent);
onFinish()
And the corresponding callback method for this state of operation is onFinish(),
public class MainActivity extends Activity < @Override public void onFinish() < … MainActivity.this.finish(); … >>
Difference between onPause(), onStop() and onDestroy()
onPause() is called when an activity is about to lose focus. onStop() is called when the activity is has already lost the focus and it is no longer in the screen. But onPause() is called when the activity is still in the screen, once the method execution is completed then the activity loses focus. So, onPause() is logically before onStop().
From onPause() it is possible to call onResume() but it is not possible once onStop() is called. Once onStop() is called then onRestart() can be called.
onDestroy() is last in the order after onStop(). onDestory() is called just before an activity is destroyed and after that it is gone it is not possible to resurrect this. Simply destroyed and buried!
Example of Android Activity
Now let us see an example of android activity. We will have two activities and see how each of them changes state and how their callback functions are called. The activities are MainActivity and SubActivity. activity_main layout includes a TextView and a Button widget. This is created by drag and drop frome the graphical layout in Eclipse and by setting appropriate properties for them. You may refer our previous article on get user input to know about creating these elements in UI.
activity_main.xml
activity_sub.xml
After designing the layout, we need to develop activity. We create a MainActivity class by extending from Activity class. Inside the MainActivity class the call back functions like onCreate(), onPause() will be created to save the current state of each phase during the life cycle.
MainActivity.java
package com.javapapers.androidactivity; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.View; import android.widget.TextView; public class MainActivity extends Activity < TextView objText; ActivityStatus objStatus = new ActivityStatus(); String StatusList; @Override public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); objStatus.updateStatusList("MainActivity","Created"); >@Override protected void onStart() < super.onStart(); objStatus.updateStatusList("MainActivity","Started"); >@Override protected void onRestart() < super.onRestart(); objStatus.updateStatusList("MainActivity","Restarted"); >@Override protected void onResume() < super.onResume(); objStatus.updateStatusList("MainActivity","Resumed"); StatusList = objStatus.getStatusList(); objText = (TextView)findViewById(R.id.textView1); objText.setText(StatusList); >@Override protected void onPause() < super.onPause(); objStatus.updateStatusList("MainActivity","Paused"); >@Override protected void onStop() < super.onStop(); objStatus.updateStatusList("MainActivity","Stoped"); >@Override protected void onDestroy() < super.onDestroy(); objStatus.updateStatusList("MainActivity","Destroyed"); >public void startSubActivity(View view) < Intent objIntent = new Intent(MainActivity.this, SubActivity.class); startActivity(objIntent); >>
To save state we need to define the updateStatusList() with two parameters, that is, Activity Name and Activity Status. This method will be invoked in each state of the activity using,
objStatus.updateStatusList(“MainActivity”,”Created”);
The getStatusList() will be used to get the status of all activities inside our application. This method will be invoked inside onResume(), after updating the resumed state.
The updateStatusList() and getStatusList() are used for save/get purposes. The following class holds those functions.
ActivityStatus.java
package com.javapapers.androidactivity; import java.util.ArrayList; import java.util.List; public class ActivityStatus < private static ListactivityStatusAry = new ArrayList(); public void updateStatusList(String activityName, String activityStatus) < for(int i=0;i> activityStatusAry.add(activityName + " " + activityStatus); > public String getStatusList() < String statusOutput=""; for(int i=0;i return statusOutput; > >
After all the callback functions, startSubActivity() method will handle the start event. Intent initialization refers to start SubActivity from current activity. Then startActivity() is used to start the SubActivity with the reference of the Intent instance.
SubActivity.java
package com.javapapers.androidactivity; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.View; import android.widget.TextView; public class SubActivity extends Activity < TextView objText; ActivityStatus objStatus = new ActivityStatus(); String StatusList; @Override public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_sub); objStatus.updateStatusList("SubActivity","Created"); >@Override protected void onStart() < super.onStart(); objStatus.updateStatusList("SubActivity","Started"); >@Override protected void onRestart() < super.onRestart(); objStatus.updateStatusList("SubActivity","Restarted"); >@Override protected void onResume() < super.onResume(); objStatus.updateStatusList("SubActivity","Resumed"); StatusList = objStatus.getStatusList(); objText = (TextView)findViewById(R.id.textView1); objText.setText(StatusList); >@Override protected void onPause() < super.onPause(); objStatus.updateStatusList("SubActivity","Paused"); >@Override protected void onStop() < super.onStop(); objStatus.updateStatusList("SubActivity","Stoped"); >@Override protected void onDestroy() < super.onDestroy(); objStatus.updateStatusList("SubActivity","Destroyed"); >public void startActivityMain(View view) < Intent objIntent = new Intent(SubActivity.this, MainActivity.class); startActivity(objIntent); >>
Output