Toptal.Com 20 Essential Android Interview Questions Flashcards
What is the SensorEvent class?
Provides raw sensor data, including information regarding accuracy
What is the SensorManager class?
Provides methods for registering sensor event listeners and calibrating sensors
What is the Sensor class?
Provides methods to identify which capabilities are available for a specific sensor
What are the 4 Java classes related to the use of sensors on Android?
1) Sensor2) SensorManager3) SensorEvent4) SensorEventListener
What is a ContentProvider?
Manages access to a structured set of data.It encapsulates the data and provides mechanisms for defining data security.
What is a ContentProvider typically used for?
It is a standard interface that connects data in one process with code running in another process.Quora: It is used to share data between multiple applications.
Under what conditions could the code sample below crash your application? Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, textMessage); sendIntent.setType(HTTP.PLAIN_TEXT_TYPE); startActivity(sendIntent);
If there are no applications registered that can handle your intent.
How would you modify the code below to avoid the app from crashing if there is no other application registered to handle the intent? Intent i = new Intent(); i.setAction(Intent.ACTION_SEND); i.putExtra(Intent.EXTRA_TEXT, textMessage); i.setType(HTTP.PLAIN_TEXT_TYPE); startActivity(i);
Add check to see if there is an existing registered application to handle the specified action.// Verify that there are applications registered to handle this intent// (resolveActivity returns null if none are registered) if (i.resolveActivity(getPackageManager()) != null) { startActivity(i); }
What are the different types of intents? Briefly explain what they are used for?
Implicit: an operation from one activity to an inbuilt android activityExplicit: an operation that opens one activity from another activity inside same application
Define Intent
An abstract description of an 'operation' to be performed.Used for 'message passing' and 'navigation' between activities.
How is data typically expressed when using Implicit Intents?
Data is typically expressed as a Uriwhich can represent an image in the gallery or person in the contact database.
Give 7 examples of activities that can be used with Implicit Intents.
1) Call2) Call Log3) Dialpad4) Contact5) Browser6) Gallery7) Camera
Give 4 examples of problems that occur with poor activity life cycle management.
1) Crash on switch or call2) Valuable resource consumption3) Progress loss4) Crash/Loss on rotate
What is the difference between onPause() and onStop()?
In onPause() the app may still be partially visible, where in onStop() the application is no longer visible.
Describe a scenario where onPause() and onStop() would not be invoked.
When finish() is called inside onCreate()
Should onDestroy() be relied upon to destroy resources?
Although onDestroy() is the last callback in the lifecycle of an activity, it is worth mentioning that this callback may not always be called and should not be relied upon to destroy resources. It is better have the resources created in onStart() and onResume(), and have them destroyed in onStop() and onPause(), respectively.
When is onDestroy() called?
1) The finish() method is called (Always)2) When the device is rotated (Always)3) When the system runs low on resources and the application is not in the foreground (Sometimes)
When can Android kill your application?
After onPause() for Android OS version 3.0 and greater. After onStop() for older applications.
When is the onSaveInstanceState() method called in the Android Lifecycle?
Always before onStop()Depending on the device and OS version, sometimes it's called before onPause() and sometimes it's called after onPause().
When is the onRestoreInstanceState() method called in the Android Lifecycle?
Always after onStart() sometimes after onResume();
Describe in detail saving and restoring an EditText value.
@Overrideprotected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); final EditText textBox = (EditText) findViewById(R.id.editText); CharSequence userText = textBox.getText(); outState.putCharSequence("savedText", userText); }@Overrideprotected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); final EditText textBox = (EditText) findViewById(R.id.editText); CharSequence userText = savedInstanceState.getCharSequence("savedText"); textBox.setText(userText);}
Describe three common use cases for using an Intent.
1) To start an activitystartActivity(intent)2) To start a servicestartService(intent)3) To deliver a broadcastsendBroadcast()sendOrderedBroadcast()sendStickyBroadcast()
Suppose that you are starting a service in an Activity as follows:Intent service = new Intent(context, MyService.class); startService(service);where MyService accesses a remote server via an Internet connection.If the Activity is showing an animation that indicates some kind of progress, what issue might you encounter and how could you address it?
Responses from a remote service via the Internet can often take some time, either due to networking latencies, or load on the remote server, or the amount of time it takes for the remote service to process and respond to the request.As a result, if such a delay occurs, the animation in the activity (and even worse, the entire UI thread) could be blocked and could appear to the user to be "frozen" while the client waits for a response from the service. This is because the service is started on the main application thread (or UI thread) in the Activity.The problem can (and should) be avoided by relegating any such remote requests to a background thread or, when feasible, using an an asynchronous response mechanism.Note well: Accessing the network from the UI thread throws a runtime exception in newer Android versions which causes the app to crash.
Do you need to save/restore the value of EditTexts when the device rotates?
No, as long as they have element IDs
When would you need to override onSaveInstanceState()/onRestoreInstanceState()?
When there are variables that are not associated with views that you'd like to store/restore.If the only values you need to store are related to views (ie text, image, progress), you can skip writing extra code because you can simply restore the variable values from the views themselves if needed.
Does the savedInstanceState Bundle survive when the OS restarts?
No.However, Since API 21 the savedInstanceState can survive reboots when set to persistableMode. The Bundle will be passed into onCreate(Bundle, PersistableBundle) as second parameter
Normally, in the process of carrying out a screen reorientation, the Android platform tears down the foreground activity and recreates it, restoring each of the view values in the activity's layout.In an app you're working on, you notice that a view's value is not being restored after screen reorientation. What could be a likely cause of the problem that you should verify, at a minimum, about that particular view?
You should verify that it has a valid id. In order for the Android system to restore the state of the views in your activity, each view must have a unique ID, supplied by the android:id attribute.
What is DDMS? Describe 7 of its capabilities.
DDMS is the Dalvik Debug Monitor Server that ships with Android. It provides a wide array of debugging features including:- port-forwarding services- screen capture- thread and heap information- network traffic tracking- incoming call and SMS spoofing- simulating network state, speed, and latency- location data spoofing
What is the relationship between the life cycle of an AsyncTask and an Activity? What problems can this result in? How can these problems be avoided?
An AsyncTask is not tied to the life cycle of the Activity that contains it. So, 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 Activty, which prevents the Activity from being garbage collected as long as the AsyncTask remains alive.For these reasons, using AsyncTasks for long-running background tasks is generally a bad idea . Rather, for long-running background tasks, a different mechanism (such as a service) should be employed.
What is an Intent? Can it be used to provide data to a ContentProvider? Why or why not?
The Intent object is a common mechanism for starting new activity and transferring data from one activity to another. However, you cannot start a ContentProvider using an Intent.When you want to access data in a ContentProvider, you must instead use the ContentResolver object in your application's Context to communicate with the provider as a client. The ContentResolver object communicates with the provider object, an instance of a class that implements ContentProvider. The provider object receives data requests from clients, performs the requested action, and returns the results.
What is a ContentResolver?
The ContentResolver object communicates with the provider object, an instance of a class that implements ContentProvider.
What is the difference between a fragment and an activity? Explain the relationship between the two.
An activity is typically a single, focused operation that a user can perform (such as dial a number, take a picture, send an email, view a map, etc.). Yet at the same time, there is nothing that precludes a developer from creating an activity that is arbitrarily complex.Activity implementations can optionally make use of the Fragment class for purposes such as producing more modular code, building more sophisticated user interfaces for larger screens, helping scale applications between small and large screens, and so on. Multiple fragments can be combined within a single activity and, conversely, the same fragment can often be reused across multiple activities. This structure is largely intended to foster code reuse and facilitate economies of scale.A fragment is essentially a modular section of an activity, with its own lifecycle and input events, and which can be added or removed at will. It is important to remember, though, that a fragment's lifecycle is directly affected by its host activity's lifecycle; i.e., when the activity is paused, so are all fragments in it, and when the activity is destroyed, so are all of its fragments.More information is available here in the Android Developer's Guide.
What is difference between Serializable and Parcelable ? Which is best approach in Android ?
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.
What are "launch modes"? What are the two mechanisms by which they can be defined? What specific types of launch modes are supported?
A "launch mode" is the way in which a new instance of an activity is to be associated with the current task.Launch modes may be defined using one of two mechanisms:Manifest file. When declaring an activity in a manifest file, you can specify how the activity should associate with tasks when it starts. Supported values include:standard (default). Multiple instances of the activity class can be instantiated and multiple instances can be added to the same task or different tasks. This is the common mode for most of the activities.singleTop. The difference from standard is, if an instance of the activity already exists at the top of the current task and the system routes the intent to this activity, no new instance will be created because it will fire off an onNewIntent() method instead of creating a new object.singleTask. A new task will always be created and a new instance will be pushed to the task as the root. However, if any activity instance exists in any tasks, the system routes the intent to that activity instance through the onNewIntent() method call. In this mode, activity instances can be pushed to the same task. This mode is useful for activities that act as the entry points.singleInstance. Same as singleTask, except that the no activities instance can be pushed into the same task of the singleInstance's. Accordingly, the activity with launch mode is always in a single activity instance task. This is a very specialized mode and should only be used in applications that are implemented entirely as one activity.Intent flags. Calls to startActivity() can include a flag in the Intent that declares if and how the new activity should be associated with the current task. Supported values include:FLAG_ACTIVITY_NEW_TASK. Same as singleTask value in Manifest file (see above).FLAG_ACTIVITY_SINGLE_TOP. Same as singleTop value in Manifest file (see above).FLAG_ACTIVITY_CLEAR_TOP. If the activity being started is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it are destroyed and this intent is delivered to the resumed instance of the activity (now on top), through onNewIntent(). There is no corresponding value in the Manifest file that produces this behavior.
What is the difference between Service and IntentService? How is each used?
Service is the base class for Android services that can be extended to create any service. A class that directly extends Service runs on the main thread so it will block the UI (if there is one) and should therefore either be used only for short tasks or should make use of other threads for longer tasks.IntentService is a subclass of Service that handles 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. Writing an IntentService can be quite simple; just extend the IntentService class and override the onHandleIntent(Intent intent) method where you can manage all incoming requests.
How do you supply construction arguments into a Fragment?
Construction arguments for a Fragment are passed via Bundle using the Fragment#setArgument(Bundle) method. The passed-in Bundle can then be retrieved through the Fragment#getArguments() method in the appropriate Fragment lifecycle method.It is a common mistake to pass in data through a custom constructor. Non-default constructors on a Fragment are not advisable because the Fragment may be destroyed and recreated due to a configuration change (e.g. orientation change). Using #setArguments()/getArguments() ensures that when the Fragment needs to be recreated, the Bundle will be appropriately serialized/deserialized so that construction data is restored.
What is ANR, and why does it happen?
'ANR' in Android is 'Application Not Responding.' It means when the user is interacting with the activity, and the activity is in the onResume() method, a dialog appears displaying "application not responding."It happens because we start a heavy and long running task like downloading data in the main UI thread. The solution of the problem is to start your heavy tasks in the backbround using Async Task class.
Is it possible to create an activity in Android without a user interface ?
Yes, an activity can be created without any user interface. These activities are treated as abstract activities.
What is a broadcast receiver?
The broadcast receiver communicates with the operation system messages such as "check whether an internet connection is available," what the battery label should be, etc.