Activity & Intent Interview question and Answer

1) What are the four essential states of an activity?


  • Active – if the activity is at the foreground
  • Paused – if the activity is at the background and still visible
  • Stopped – if the activity is not visible and therefore is hidden or obscured by another activity
  • Destroyed – when the activity process is killed or completed terminated
2) What is a visible activity?
A visible activity is one that sits behind a foreground dialog. It is actually visible to the user, but not necessarily being in the foreground itself.

3) When is the best time to kill a foreground activity?
The foreground activity, being the most important among the other states, is only killed or terminated as a last resort, especially if it is already consuming too much memory. When a memory paging state has been reach by a foreground activity, then it is killed so that the user interface can retain its responsiveness to the user.

4) What are the four essential states of an activity?
Ans. Active, Paused, Stopped and Destroyed

5) Can you create an activity in Android without a user interface?
Ans. Yes, it can be created without any user interface and these activities are treated as abstract activitie
How many activities are in focus at any time?
A) Just one

How to kill an activity?
i. finish()
ii.finishActivity(int requestcode)

Create an Android Activity with component like Email and Password. You need to write to code for auto fill data in field of Email and password. How you will do that.
In your scenario, we have to design a login screen in the application where the login activity is having two control an email and a password. An email we want to display autofill data based on the user email address. We will use AutoCompleteTextView in our layout to display email and password data.
What we can do here in our Java activity we can create an object of Account Manager and we load the user accounts through the AccountManager.
As some accounts may not have an email address linked to them, we filter them and keep only the ones who match an email regex. We also use a Set to remove the duplicates. Now we just have an array of Strings as the data source and we just bind via an ArrayAdapter the list of an email address.  Now we can display data of email and password in autocomplete text view. One we need to remember before running this code we need to add below permission in our manifest file.
android.permission.GET_ACCOUNTS
The layout file will look like this:
<AutoCompleteTextView
    android:id="@+id/autoCompleteTextView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:ems="10"
    android:text="Enter Email Address" />
And. Activity, java file will be like this:
private ArrayAdapter<String> getEmailAdapter(Context context) {
    Account[] accounts = AccountManager.get(context).getAccounts();
    String[] addresse= new String[accounts.length];
    for (int i = 0; i < accounts.length; i++) { 
        addresses[i] = accounts[i].name;
    }
    return new ArrayAdapter<String>(context, android.R.layout.simple_dropdown_item_1line, addresses);
-------------------------------------------------------------------------
Lifecycle:
-------------------------------------------------------------------------
1) Explain Lifecycle of an Activity
  • OnCreate(): This is when the view is up first created. This is normally where we create views, get data from bundles etc.
  • OnStart(): Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.
  • OnResume(): Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it.
  • OnPause(): Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed.
  • OnStop(): Called when you are no longer visible to the user.
  • OnDestroy(): Called when the activity is finishing
  • OnRestart(): Called after your activity has been stopped, prior to it being started again
2) What’s the difference between onCreate() and onStart()?
  • The onCreate() method is called once during the Activity lifecycle, either when the application starts, or when the Activity has been destroyed and then recreated, for example during a configuration change.
  • The onStart() method is called whenever the Activity becomes visible to the user, typically after onCreate() or onRestart().
3) Scenario in which only onDestroy is called for an activity without onPause() and onStop()?
If finish() is called in the OnCreate method of an activity, the system will invoke onDestroy() method directly.

4) Why would you do the setContentView() in onCreate() of Activity class?
As onCreate() of an Activity is called only once, this is the point where most initialisation should go. It is inefficient to set the content in onResume() or onStart() (which are called multiple times) as the setContentView() is a heavy operation.

5) When the application is in the foreground and you get a call, in what stage your application will get into?

Answer: OnPause

6) Difference between onStop() and destroy() methods in activity lifecycle?
Answer:
Onstop() -It will temporarily call the destroy instance of activity to provide space for other applications.
OnDestroy()- Application will finish and shut down the activity.

7) In Activity life-cycle, what is the first and last callback method will be guaranteed invoked by the system?
The first method is called 'onCreate()', which fires when the system first creates the activity. On activity creation, the activity enters the Created state.
The last method is guaranteed called ‘onPause()’. The system calls this method as the first indication that the user is leaving your activity (though it does not always mean the activity is being destroyed), but you should save you work/variables/state here. Other methods e.g. onStop, onDestroy may be called or not depends on the system

When an activity is in stopped state, is it still in memory or not?
when onStop() is called, then activity is still in memory and all its states and variables are intact.

What livecycle methods are part of the visible lifecycle?
onStart(), onResume(), onPause(), onStop()
Background: During this time the user can see the Activity. However, the Activity may not be in the foreground and interacting with the user.

What lifecycle methods are part of the foreground lifecycle?
onResume(), onPause()
Background: The Activity is in front of all others Activities during this time. The user can interact with the Activity.

What are the four essential states of an Activity?
  • Active: if the Activity is active (it can receive user input) and visible
  • Paused: if the Activity is visible but not active
  • Stopped: if the Activity is not visible
  • Destroyed: when the activity process is killed
When does the system directly call “onDestroy()” after it called “onCreate(Bundle)”? (without calling onStart(), onResume(), onStop(), onPause())
By calling finish() within the onCreate(Bundle) method, the system does not call any further lifecycle methods except onDestroy().

Activity A starts Activity B. Which lifecycle methods are called and in what order?
  1. Activity A’s onPause() method is called.
  1. Activity B’s onCreate(), onStart(), and onResume() methods are called in sequence. Activity B is in foreground now.
  1. Activity A’s onStop() method is called. Activity A is no longer visible on screen.
Important: Please notice the overlap in the Activity transition. Activity A is not completely stopped before Activity B is created.

Can you describe two scenarios in which your Activity gets destroyed due to normal app behaviour?
  1. When the user presses the Back button
  1. Calling the Activity.finish() method
Background: In both cases the Activity instance is gone forever. The Activity is no longer needed.
Also a configuration change during runtime (such as screen orientation, keyboard availability, language,…) triggers an Activity re-creation: The current instance is destroyed (onDestroy() is called) and a new instance is created (onCreate() is called). It is important to store the Activity state during this re-creation process (via Bundle).

Can you describe a scenario in which your Activity gets destroyed due to a system behaviour?
The Android system may destroy the process(!) containing your Activity to recover memory.
Background: This happens if the Activity is in the Stopped state and hasn’t been used in a long time, or if the current foreground Activity requires more memory. The system is storing the instance state in a Bundle object. The saved state is used to restore the previous state.
Important: Android is killing the whole process and not only the Activity instance.
How does the system store the Activity state?
The system calls the onSaveInstance() method and stores the instance state in a collection of key-value pairs.
Important: You always have to call the superclass implementation of onSaveInstanceState(). The default implementation saves the state of the view hierarchy. This requires that each view has an unique ID (android:id).
Example:
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putInt(MY_VAR_KEY, myVarValue);
// Always call the superclass method
super.onSaveInstanceState(savedInstanceState);
}

How can an Activity recover its previous state?
Either by using the Bundle instance that the system passes to onCreate(Bundle) or by implementing the onRestoreInstanceState(Bundle) method.
Example:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Always do a null check first!
if (savedInstanceState != null) {
// Restore value from instance state
myVarValue = savedInstanceState.getInt(MY_VAR_KEY);
} else {
// First initialization - Nothing to restore!
}
}
Otherwise use onRestoreInstanceState(Bundle):
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass method
super.onRestoreInstanceState(savedInstanceState);
// Restore values from instance state
myVarValue = savedInstanceState.getInt(MY_VAR_KEY);
}

Will calling finish() on an Activity calls all the usual activity life cycle method?
Yes, except if you are calling it from onCreate, in which case onDestroy() will be immediately called without any of the rest of the activity lifecycle (onStart(), onResume(), onPause(), etc) executing.

Describe a scenario where an Activity enters pause state but not stop state?
When a semi-transparent activity opens making the previous activity partially visible.
Reference
http://developer.android.com/training/basics/activity-lifecycle/pausing.html

What kind of actions are suggested to perform on onPause callback of an Activity implementation?
  • Stop animations or other ongoing actions that could consume CPU
  • Possibly commit unsaved changes
  • Release system resources such as broadcast receivers, handles to camera, sensors, etc.
Reference
http://developer.android.com/training/basics/activity-lifecycle/pausing.html

Describe a scenario where onRestart will be called for an Activity implementation?
User launches a new activity B from activity A. And then the user presses back button on activity B.

Here onStop will be called for activity A when user launched activity B. Once user presses back button on activity B, onRestart, onStart and onResume callback are called for activity A.
The onRestart() method, however, is called only when the activity resumes from the stopped state.
Reference
http://developer.android.com/training/basics/activity-lifecycle/stopping.html

Describe some of the scenario where an activity could possibly be destroyed?
  • User presses back button
  • finish() method is called for the Activity
  • The Activity is inactive for long time
  • Foreground Activity requires more resources so the system must shut down background processes to recover memory
Reference
http://developer.android.com/training/basics/activity-lifecycle/recreating.html

What are the activity lifecycle methods that trigger when the user clicks the home button?

OnPauseOnStop

What are the activity lifecycle methods that trigger when the user clicks the back button and then again brings back the app to the foreground?

//When click back button
OnPause
OnStop//When bring back the app to foreground
OnRestart
onStartOnResume

What are the activity lifecycle methods that trigger when the user clicks the back button?

OnPauseOnStopOnDestroy

What are the activity lifecycle methods that trigger when user navigate from ActivityA to ActivityB?

A — onPauseB — onCreateB — onStartB — onResumeA — onStop

What happens if the user clicks the back button in ActivityB?

B — onPauseA — onRestartA — onStartA — onResumeB — onStopB — onDestroy

Aaaa

-------------------------------------------------------------------------
Intent:
-------------------------------------------------------------------------
1) Mention two ways to clear the back stack of Activities when a new Activity is called using intent

The first approach is to use a FLAG_ACTIVITY_CLEAR_TOP flag. The second way is by using FLAG_ACTIVITY_CLEAR_TASK and FLAG_ACTIVITY_NEW_TASK in conjunction.
2) What’s the difference between FLAG_ACTIVITY_CLEAR_TASK and FLAG_ACTIVITY_CLEAR_TOP?
FLAG_ACTIVITY_CLEAR_TASK is used to clear all the activities from the task including any existing instances of the class invoked. The Activity launched by intent becomes the new root of the otherwise empty task list. This flag has to be used in conjunction with FLAG_ ACTIVITY_NEW_TASK.
FLAG_ACTIVITY_CLEAR_TOP on the other hand, if set and if an old instance of this Activity exists in the task list then barring that all the other activities are removed and that old activity becomes the root of the task list. Else if there’s no instance of that activity then a new instance of it is made the root of the task list. Using FLAG_ACTIVITY_NEW_TASK in conjunction is a good practice, though not necessary.
3) What is an intent?
Intents are messages that can be used to pass information to the various components of android. For instance, launch an activity, open a webview etc. Two types of intents-
  • Implicit: Implicit intent is when you call system default intent like send email, send SMS, dial number.
  • Explicit: Explicit intent is when you call an application activity from another activity of the same application.
4) What is a Sticky Intent?
Sticky Intents allows communication between a function and a service. sendStickyBroadcast() performs a sendBroadcast(Intent) known as sticky, i.e. the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of registerReceiver(BroadcastReceiver, IntentFilter). For example, if you take an intent for ACTION_BATTERY_CHANGED to get battery change events: When you call registerReceiver() for that action — even with a null BroadcastReceiver — you get the Intent that was last Broadcast for that action. Hence, you can use this to find the state of the battery without necessarily registering for all future state changes in the battery.
A Sticky Intent is a broadcast from sendStickyBroadcast() method such that the intent floats around even after the broadcast, allowing others to collect data from it.
5) What is a Pending Intent?
If you want someone to perform any Intent operation at future point of time on behalf of you, then we will use Pending Intent.
WHAT IS A PENDINGINTENT?
A PendingIntent is similar to an Intent . It is given to a foreign or third party application
and providesthem for permission to execute a particular piece of code in an application.
It is used very often which classes such
as NotificationManager , AlarmManager or AppWidgetManager
6) What are the three common use cases of an Intent?
Ans. 
  • to start an activity
  • to start a service
  • to deliver a broadcast
7) What is an Action?
Description of the intent. For instance, ACTION_CALL — used to perform calls
8) What are intent Filters?
Specifies the type of intent that the activity/service can respond to.
Which types of flags are used to run an application on Android?
Following are two types of flags to run an application in Android:
  • FLAG_ACTIVITY_NEW_TASK – If it’s already running in a task, then that task is brought to the foreground else the activity creates a new task.
  • FLAG_ACTIVITY_SINGLE_TOP – If the activity is currently at the top of the stack then the activity will not be launched.
  • FLAG_ACTIVITY_CLEAR_TOP – If the activity is already running in the current task, then this activity is brought to the top of the stack and all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.
-------------------------------------------------------------------------
Data Sending
-------------------------------------------------------------------------
1) How will you pass data to sub-activities?
  • We can use Bundles to pass data to sub-activities.
  • There are like HashMaps that and take trivial data types. These Bundles transport information from one Activity to another
1
2
3
Bundle b=new Bundle();
b.putString("Email","abc@xyz.com");
i.putExtras(b); // where I is inten

2) In Android application how you will transfer Object like complex POJO code from one Activity to another? Hint: What is the difference between Serializable and Parcelable?
When you need to send Object from one activity to another activity, we are using two techniques: 1. Serialization and 2. Parcelable. In other case passing data from one activity to another activity, we are using Intent. Parcelable is a faster approach compared to Serialization because it is using Android SDK.
There are some reasons also:
  • Serialization is a marker interface as it converts an object into a stream using the Java reflection API. Due to this, it ends up creating a number of garbage objects during the stream conversation process.
  • Parcelable is in the Android SDK; serialization, on the other hand, is available in Java. So Android developers prefer Parcelable over the Serialization technique
3) I have two activities: main activity as Activity A and child activity as Activity B. When I press a button Next in the ActivityA, it will call the ActivityB. Suppose I have to send data back to Activity A from Activity. How I will do that?
In, we can send information from one activity to another and vice-versa using startActivityForResult() method. The android startActivityForResult method requires a result from the second activity. For that, we need to override the onActivityResult method that is invoked automatically when the second activity returns a result.
public void startActivityForResult (Intent intent, int requestCode)
Now we will see how to send data from Activity B back to Activity A?
  • In Activity A we will call explicit Intent in Next Button click, this will call Intent and it will call ActivityB.
intentActivityD = new Intent(…);
   intentActivityD;
   startActivityForResult(intentActivityD, SOME_REQUEST_CODE)
In Activity B we will send someResultCode to Activity  A, which will handle it with the onActivityResult and send it back again with setResult(…) finish();
goBackToActivityA(){
   setResult(someResultCode);
   finish();
}
  • Once it received result from Activity B it will call method onActivityResult. Which will then know by the flag that the activity B no longer exists, hence the activity that should handle it is Activity A, which means the resultCode will finally arrive in the onActivityResultCode of Activity A.
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
       // check if the requestCode is the wanted one and if the result is what we are expecting
       if (requestCode == REQUEST_FORM && resultCode == RESULT_OK) {
           val name = data?.getStringExtra(FormActivity.INPUT_NAME)
           addItemToList(name) // do something with the value
       }
   }

How to get result from an Activity?
Call startActivityForResult() with a request code
Implement onActivityResult(int requestCode, int resultCode, Intent data) on your activity
A result code specified by the second activity. This is either RESULT_OK if the operation was successful or RESULT_CANCELED if the user backed out or the operation failed for some reason

Activity results handled by the onActivityResult() method are differentiated from one another using which code?
A) Result Code
What is difference between Serializable and Parcelable ? Which is best approach in Android ?
A) Serializable is a standard Java interface. You simply mark a class Serializable by implementing the interface, and Java will automatically serialize it in certain situations.
Parcelable is an Android specific interface where you implement the serialization yourself. It was created to be far more efficient than Serializable, and to get around some problems with the default Java serialization scheme.

How we pass data to sub-activities?
Answer: We use HashMaps like structure such as Bundles to carry trivial data from one activity to its sub-activities.
What is the difference between Serializable and Parcelable?
  • Serializable is a Java marker interface. A class that implements this interface allows the serialization of an object from this type in certain situations.
  • Parcelable is an Android specific interface where you have to implement the serialization by yourself. The parcelable process is much faster than Serializable (= no need for reflection). Parcelable is always the default choice in Android.
Background: Serialization is the process of converting an object instance into a series of bytes, so that the object can be easily saved to persistent storage or transmited across a communication channel (e.g. network)

WHAT DOES THE INTERFACE SERIALIZABLE DOES IN JAVA?
Serialization is the process of translating an object into binary information so it can be
stored in a database or be sent through a network request without loosing information.
To make an object Serializable in Java, we need to implement the interface
java.io.Serializable
A
x

Comments

Popular posts from this blog

Jetpack Compose based Android interview and questions

Null safety based Kotlin interview questions and answers

What are Support Libraries ?