Android interview questions [beginner]
Is a Fragment always part of an Activity layout?
Fragment is not required to be a part of the activity layout; you may also use a fragment without its own UI as an invisible worker for the activity.
What ANR means?
"Application Not Responding" (ANR) dialog is the worst thing that can happen to your app's responsiveness. Generally, the system displays an ANR if an application cannot respond to user input. For example, if an application blocks on some I/O operation (frequently a network access) on the UI thread so the system can't process incoming user input events. Or perhaps the app spends too much time building an elaborate in-memory structure or computing the next move in a game on the UI thread.
Which are the most used already defined Fragment subclass?
- DialogFragment: A fragment that displays a dialog window, floating on top of its activity's window. This fragment contains a Dialog object, which it displays as appropriate based on the fragment's state. - ListFragment: A fragment that displays a list of items by binding to a data source such as an array or Cursor, and exposes event handlers when the user selects an item. ListFragment hosts a ListView object that can be bound to different data sources, typically either an array or a Cursor holding query results. - PreferenceFragment: Shows a hierarchy of Preference objects as lists. These preferences will automatically save to SharedPreferences as the user interacts with them.
What the IntentService class does?
- It creates a default worker thread that executes all of the intents that are delivered to onStartCommand(), separate from your application's main thread. - Creates a work queue that passes one intent at a time to your onHandleIntent() implementation, so you never have to worry about multi-threading. - Stops the service after all of the start requests are handled, so you never have to call stopSelf(). - Provides a default implementation of onBind() that returns null. - Provides a default implementation of onStartCommand() that sends the intent to the work queue and then to your onHandleIntent() implementation.
What are the 3 types of Service?
- Scheduled: when an API such as the JobScheduler launches the service. - Started: when an application component (such as an activity) calls startService(). After it's started, a service can run in the background indefinitely, even if the component that started it is destroyed. -Bound: when an application component binds to it by calling bindService(). A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once
Explain the Activity lifecycle
- The _entire_ lifetime of an activity happens between the first call to onCreate(Bundle) through to a single final call to onDestroy(). An activity will do all setup of "global" state in onCreate(), and release all remaining resources in onDestroy(). For example, if it has a thread running in the background to download data from the network, it may create that thread in onCreate() and then stop the thread in onDestroy(). - The _visible_ lifetime of an activity happens between a call to onStart() until a corresponding call to onStop(). During this time the user can see the activity on-screen, though it may not be in the foreground and interacting with the user. Between these two methods you can maintain resources that are needed to show the activity to the user. For example, you can register a BroadcastReceiver in onStart() to monitor for changes that impact your UI, and unregister it in onStop() when the user no longer sees what you are displaying. The onStart() and onStop() methods can be called multiple times, as the activity becomes visible and hidden to the user. - The _foreground_ lifetime of an activity happens between a call to onResume() until a corresponding call to onPause(). During this time the activity is in front of all other activities and interacting with the user. An activity can frequently go between the resumed and paused states -- for example when the device goes to sleep, when an activity result is delivered, when a new intent is delivered -- so the code in these methods should be fairly lightweight.
How to avoid memory leak when AsyncTask maintains a reference to an Activity?
- Use service for long running background operations. - Use WeakReference/AsyncTask pattern: the WeakReference allows the Activity to be garbage collected if destroyed, so you don't have a memory leak when AsyncTask tries to invoke the Activity to return result. You have to check for null to avoid NPE. Activity activity = weakActivity.get(); if (activity != null) { // do your stuff with activity here }
What is a Fragment in Android?
A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities).
What is a Handler in Android?
A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue. There are two main uses for a Handler: -to schedule messages and runnables to be executed as some point in the future - to enqueue an action to be performed on a different thread than your own.
Can Fragments run outside an Activity?
A fragment must always be embedded in an activity and the fragment's lifecycle is directly affected by the host activity's lifecycle. For example, when the activity is paused, so are all fragments in it, and when the activity is destroyed, so are all fragments. However, while an activity is running (it is in the resumed lifecycle state), you can manipulate each fragment independently, such as add or remove them. When you perform such a fragment transaction, you can also add it to a back stack that's managed by the activity—each back stack entry in the activity is a record of the fragment transaction that occurred. The back stack allows the user to reverse a fragment transaction (navigate backwards), by pressing the Back button.
In which thread runs a Service?
A service runs in the same process as the application in which it is declared and in the main thread of that application by default. If your service performs intensive or blocking operations while the user interacts with an activity from the same application, the service slows down activity performance. To avoid impacting application performance, start a new thread inside the service.
What is an Intent?
An intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a background Service. An Intent provides a facility for performing late runtime binding between the code in different applications. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. It is basically a passive data structure holding an abstract description of an action to be performed.
What is the difference between implicit and explicit Intent?
Android Explicit intent specifies the component to be invoked from activity. In other words, we can call another activity in android by explicit intent. Implicit Intent doesn't specify the component. In such case, intent provides information of available components provided by the system that is to be invoked.
What are the method to access the UI thread from a working (not main) thread?
Android offers several ways to access the UI thread from other threads. - Activity.runOnUiThread(Runnable): Runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately. If the current thread is not the UI thread, the action is posted to the event queue of the UI thread. - View.post(Runnable): Causes the Runnable to be added to the message queue. The runnable will be run on the user interface thread. - View.postDelayed(Runnable, long): Causes the Runnable to be added to the message queue, to be run after the specified amount of time elapses. The runnable will be run on the user interface thread. To handle more complex interactions with a worker thread, you might consider using a Handler in your worker thread, to process messages delivered from the UI thread. Perhaps the best solution, is to extend the AsyncTask class, which simplifies the execution of worker thread tasks that need to interact with the UI.
What are the Android storage options?
Android provides several options for you to save persistent application data. The solution you choose depends on your specific needs, such as whether the data should be private to your application or accessible to other applications (and the user) and how much space your data requires. Your data storage options are the following: - Shared Preferences: Store private primitive data in key-value pairs. - Internal Storage: Store private data on the device memory. - External Storage: Store public data on the shared external storage. - SQLite Databases: Store structured data in a private database. - Network Connection: Store data on the web with your own network server.
What is a Service?
Application component that can perform long-running operations in the background, and it does not provide a user interface
What is an AsyncTask?
AsyncTask enables proper and easy use of the UI thread. This class allows you to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers. AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask.
What is an IntentService?
Base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.
Is it possible to set different processes for Android components of the same application? Is it possible to run components of two different applications in the same process?
By default, all components of the same application run in the same process and most applications should not change this. However, if you find that you need to control which process a certain component belongs to, you can do so in the manifest file. The manifest entry for each type of component element supports an 'android:process' attribute that can specify a process in which that component should run. You can set this attribute so that each component runs in its own process or so that some components share a process while others do not. You can also set 'android:process' so that components of different applications run in the same process.
In which process and thread do Android components run?
By default, all components of the same application run in the same process and thread (called the "main" thread). If an application component starts and there already exists a process for that application (because another component from the application exists), then the component is started within that process and uses the same thread of execution. However, you can arrange for different components in your application to run in separate processes, and you can create additional threads for any process.
Can be a single Fragment used in more than one Activity?
Each fragment defines its own layout and its own behavior with its own lifecycle callbacks, you can include one fragment in multiple activities, so you should design for reuse and avoid directly manipulating one fragment from another fragment. This is especially important because a modular fragment allows you to change your fragment combinations for different screen sizes. When designing your application to support both tablets and handsets, you can reuse your fragments in different layout configurations to optimize the user experience based on the available screen space
Is the Android UI toolkit thread-safe?
No! The Andoid UI toolkit is not thread-safe. So, you must not manipulate your UI from a worker thread—you must do all manipulation to your user interface from the UI thread. Thus, there are simply two rules to Android's single thread model: - Do not block the UI thread - Do not access the Android UI toolkit from outside the UI thread
Is an AsyncTask tied to the life cycle of the Activity that contains it?
No, Is not! For example, if you start an AsyncTask inside an Activity and the user rotates the device, the Activity will be destroyed (and a new Activity instance will be created) but the AsyncTask will not die but instead goes on living until it completes. Then, when the AsyncTask does complete, rather than updating the UI of the new Activity, it updates the former instance of the Activity (i.e., the one in which it was created but that is not displayed anymore!). This can lead to an Exception (of the type java.lang.IllegalArgumentException: View not attached to window manager if you use, for instance, findViewById to retrieve a view inside the Activity). There's also the potential for this to result in a memory leak since the AsyncTask maintains a reference to the Activity, which prevents the Activity from being garbage collected as long as the AsyncTask remains alive.
Make an example of a started Service
Suppose an activity needs to save some data to an online database. The activity can start a companion service and deliver it the data to save by passing an intent to startService(). The service receives the intent in onStartCommand(), connects to the Internet, and performs the database transaction. When the transaction is complete, the service stops itself and is destroyed.
When a Service is killed?
The Android system force-stops a service only when memory is low and it must recover system resources for the activity that has user focus. If the service is bound to an activity that has user focus, it's less likely to be killed; if the service is declared to run in the foreground, it's rarely killed. If the service is started and is long-running, the system lowers its position in the list of background tasks over time, and the service becomes highly susceptible to killing—if your service is started, you must design it to gracefully handle restarts by the system. If the system kills your service, it restarts it as soon as resources become available.
What is the "main thread" , called also "UI thread" in Android?
When an application is launched, the system creates a thread of execution for the application, called "main." This thread is very important because it is in charge of dispatching events to the appropriate user interface widgets, including drawing events. It is also the thread in which your application interacts with components from the Android UI toolkit. The system does not create a separate thread for each instance of a component. All components that run in the same process are instantiated in the UI thread, and system calls to each component are dispatched from that thread. Consequently, methods that respond to system callbacks always run in the UI thread of the process.
How can a Fragment be defined in an Activity layout?
You can insert a fragment into your activity layout by declaring the fragment in the activity's layout file, as a <fragment> element, or from your application code by adding it to an existing 'ViewGroup'.