Thales Android Interview

Android

1) Difference between Service and Aysnc Task.
2) What is Broadcast Receiver and when to use one.
3) What is fragment
4) Tell the activity lifecycle
5) Why do we use DDMS
6) adb commands used by you

 

Java
1) What is static method
2) What values can be accessed from a static method in java


Git

1) Git command to add a file

2) Difference between git pull rebase vs git pull merge
https://www.atlassian.com/git/tutorials/merging-vs-rebasing

SQL
1) Difference between inner join and full join


Network

1) How to send a file from computer to server
2) What is ssh command

Linux
1) List the top 10 process which are taking most CPU.

Working with Bitmaps

The BitmapFactory.decode* methods should not be executed on the main UI thread if the source data is read from disk or a network location (or really any source other than memory). The time this data takes to load is unpredictable and depends on a variety of factors (speed of reading from disk or network, size of image, power of CPU, etc.). If one of these tasks blocks the UI thread, the system flags your application as non-responsive and the user has the option of closing it.


Loading Large Bitmaps into an ImageView Efficiently:
(https://developer.android.com/training/displaying-bitmaps/load-bitmap.html)

Images come in all shapes and sizes. In many cases they are larger than required for a typical application user interface (UI).

Given that you are working with limited memory, ideally you only want to load a lower resolution version in memory. The lower resolution version should match the size of the UI component that displays it. An image with a higher resolution does not provide any visible benefit, but still takes up precious memory and incurs additional performance overhead due to additional on the fly scaling.

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
        int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}

We have set inJustDecodeBounds to true to calculate the size of the image. Then we have calculated the sample size (the factor by which we can scale down the image). Then we decode the image.

 

https://android-developers.googleblog.com/2010/07/multithreading-for-performance.html

https://developer.android.com/training/displaying-bitmaps/process-bitmap.html

Caching & its issues

https://developer.android.com/training/displaying-bitmaps/cache-bitmap.html#memory-cache

 

Considerations to take while designing Cache:

How memory intensive is the rest of your activity and/or application?

How many images will be on-screen at once? How many need to be available ready to come on-screen?

What is the screen size and density of the device? An extra high density screen (xhdpi) device like Galaxy Nexus will need a larger cache to hold the same number of images in memory compared to a device like Nexus S (hdpi).

What dimensions and configuration are the bitmaps and therefore how much memory will each take up?

How frequently will the images be accessed? Will some be accessed more frequently than others? If so, perhaps you may want to keep certain items always in memory or even have multiple LruCache objects for different groups of bitmaps.

Can you balance quality against quantity? Sometimes it can be more useful to store a larger number of lower quality bitmaps, potentially loading a higher quality version in another background task.

 

DiskLRUCache: https://developer.android.com/samples/DisplayingBitmaps/src/com.example.android.displayingbitmaps/util/DiskLruCache.html

Android Basics

1)
Activity

An activity is a class that represents a single screen. It is like a Frame in AWT.

View

A view is the UI element such as button, label, text field etc. Anything that you see is a view.

Intent

Intent is used to invoke components. It is mainly used to:

  • Start the service
  • Launch an activity
  • Display a web page
  • Display a list of contacts
  • Broadcast a message
  • Dial a phone call etc.


Service

Service is a background process that can run for a long time.

There are two types of services local and remote.
Local service is accessed from within the application whereas remote service is accessed remotely from other applications running on the same device.

Content Provider

Content Providers are used to share data between the applications.

A ContentProvider manages access to a structured set of data. It encapsulates the data and provide mechanisms for defining data security. ContentProvider is the standard interface that connects data in one process with code running in another process.

Fragment

Fragments are like parts of activity. An activity can display one or more fragments on the screen at the same time.

AndroidManifest.xml

It contains informations about activities, content providers, permissions etc. It is like the web.xml file in Java EE.

Android Virtual Device (AVD)

It is used to test the android application without the need for mobile or tablet etc. It can be created in different configurations to emulate different types of real devices.


2) About Activity LifeCycle

Android-Activity-Lifecycle

Activity States:

State Description

Running

Activity is visible and interacts with the user.

Paused

Activity is still visible but partially obscured, instance is running but might be killed by the system.

Stopped

Activity is not visible, instance is running but might be killed by the system.

Killed

Activity has been terminated by the system of by a call to its finish() method.

Activity Methods

Method Purpose

onCreate()

Called then the activity is created.

Used to initialize the activity, for example create the user interface.

onResume()

Called if the activity get visible again and the user starts interacting with the activity again.

Used to initialize fields, register listeners, bind to services, etc.

onPause()

Called once another activity gets into the foreground. Always called before the activity is not visible anymore.

Used to release resources or save application data. For example you unregister listeners, intent receivers, unbind from services or remove system service listeners.

onStop()

Called once the activity is no longer visible.

Time or CPU intensive shut-down operations, such as writing information to a database should be down in the onStop() method.

This method is guaranteed to be called as of API 11.

3) Saving and restoring Activity Instance State

Instance state of an activity which is required to restore the activity to the state in which the user left it. This is non-persistent application data that needs to be passed between activities restarts during a configuration change to restore user selections. The application is responsible for restoring its instance state.

Assume for example the user scrolled through a ListView with thousands of items and the activity is recreated. Loosing the position in the list is annoying for the user, hence the position should be restored.

The onSaveInstanceState() can be used to store this instance state as a Bundle . A Bundle can contain primitive data types, arrays, String and objects which are of the Parcelable or Serialisable type.

The persisted Bundle data is passed at restart of the activity to the onCreate() method and onRestoreInstanceState() as parameter.

If you override onSaveInstanceState() and onRestoreInstanceState() you should call the super implementation of it, because the default views of Android store their data via a call to View.onSaveInstanceState from the onSaveInstanceState() method of the activity. For example EditText stores its content via the default call of this method.

The onRestoreInstanceState() or the onCreate() methods can be used to recreate the instance scope of an activity if it is restarted.

Prefer using the onRestoreInstanceState() method for restoring the instance state. This approach separates the initial setup from restoring the state.

If the user interacts with an activity and presses the Back button or if the finish() method of an activity is called, the activity is removed from the current activity stack and recycled. In this case there is no instance state to save and the onSaveInstanceState() method is not called.


If the user interacts with an activity and presses the Home button, the activity instance state must be saved. The onSaveInstanceState() method is called. If the user restarts the application it will resume or restart the last running activity. If it restarts the activity it provides the bundle with the save data to the onRestoreInstanceState() and onCreate() methods.

The onSaveInstanceState() method is not called if the user presses the back button. Don’t use this approach to save the data which needs to get persisted.

Android Tools

1) DDMS

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 (Take heap memory dump in hprof file )
  • network traffic tracking
  • incoming call and SMS spoofing
  • simulating network state, speed, and latency
  • location data spoofing


2) Eclipse Memory Analyzer

To analyze the heap memory dump in the hprof file.

3) Hierarchy Viewer

Hierarchy Viewer to view the time taken to draw the individual parts of the layout (it gives measure, layout and draw time of layouts).

We can use it to find the parts of layout which are taking long time to draw and which can be further optimized.
There is also a color code along side the time which tells us whether if time is optimal or not.

Android Concepts

1) In android for background tasks

If short –> can use AsyncTask
If long –> Use a Service and propagate the changes to the main activity with a BroadcastReceiver

2) Favor static inner classes over nonstatic. Each instance of a nonstatic inner class will have an extraneous reference to its outer Activity instance. Storing this reference can result in the Activity being retained when it would otherwise be eligible for garbage collection. If your static inner class requires a reference to the underlying Activity in order to function properly, make sure you wrap the object in a WeakReference to ensure that you don’t accidentally leak the Activity.

3)

Android To Read

1) Activity, Memory Leaks, Long running task

http://www.androiddesignpatterns.com/2013/04/activitys-threads-memory-leaks.html
http://www.androiddesignpatterns.com/2013/01/inner-class-handler-memory-leak.html

Retained Fragments to handle background tasks.
http://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html
The difference between static and non-static inner classes is subtle, but is something every Android developer should understand. What’s the bottom line? Avoid using non-static inner classes, anonymous inner classes in an activity if instances of the inner class could outlive the activity’s lifecycle.

Instead, prefer static inner classes and hold a weak reference to the activity inside.

 

 

 

2) Handling Configuration Changes with Fragments

http://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html

https://developer.android.com/guide/topics/resources/runtime-changes.html

Calling Fragment#setRetainInstance(true) allows us to bypass this destroy-and-recreate cycle, signaling the system to retain the current instance of the fragment when the activity is recreated.

It’s not a good practice to use configChanges to prevent destruction and recreation of activity on configuration change.

android:configChanges="orientation|screenSize"

To handle configuration changes you can implement function onConfigurationChanged().

When you declare your activity to handle a configuration change, you are responsible for resetting any elements for which you provide alternatives. If you declare your activity to handle the orientation change and have images that should change between landscape and portrait, you must re-assign each resource to each element during onConfigurationChanged().

3) Infinite View Pager

https://developer.android.com/training/animation/screen-slide.html

http://stackoverflow.com/questions/7766630/changing-viewpager-to-enable-infinite-page-scrolling

http://thehayro.blogspot.de/2013/09/infiniteviewpager-infinite-paging.html


4) Caching – How to use DiskLruCache

https://developer.android.com/training/displaying-bitmaps/cache-bitmap.html

https://android.googlesource.com/platform/libcore/+/jb-mr2-release/luni/src/main/java/libcore/io/DiskLruCache.java

http://stackoverflow.com/questions/21872028/jakewhartons-disklrucache-how-to-implement-with-volley

 

Android Questions

1)  What is ContentProvider and what is being used for?
A ContentProvider manages access to a structured set of data. It encapsulates the data and provide mechanisms for defining data security. ContentProvider is the standard interface that connects data in one process with code running in another process.

2) Under what condition could the code sample below crash your application? How would you modify the code to avoid this potential problem? Explain your answer.

    Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.putExtra(Intent.EXTRA_TEXT, textMessage);
    sendIntent.setType(HTTP.PLAIN_TEXT_TYPE); // “text/plain” MIME type
    startActivity(sendIntent);

Sol:

An implicit intent specifies an action that can invoke any app on the device able to perform the action. Using an implicit intent is useful when your app cannot perform the action, but other apps probably can. If there is more than one application registered that can handle this request, the user will be prompted to select which one to use.

However, it is possible that there are no applications that can handle your intent. In this case, your application will crash when you invoke startActivity(). To avoid this, before calling startActivity() you should first verify that there is at least one application registered in the system that can handle the intent. To do this use resolveActivity() on your intent object:

    // Verify that there are applications registered to handle this intent
    // (resolveActivity returns null if none are registered)
    if (sendIntent.resolveActivity(getPackageManager()) != null) {
        startActivity(sendIntent);
    } 

 

http://stackoverflow.com/questions/22479211/intent-resolveactivity-null-but-launching-the-intent-throws-an-activitynotfou

From what I could see, intent.resolveActivity() will return true if there is ANY activity resolving this intent. Even if this activity is not exported (which makes it unusable for all practical purposes in case it’s not from your package). Android’s API doesn’t care to mention that, so you have to figure it out by yourself, and make sure that the activity you’re trying to launch is indeed exported.

ActivityInfo activityInfo = intent.resolveActivityInfo(pm, intent.getFlags());
if (activityInfo.exported) {
    doSomething();
}


3) The last callback in the lifecycle of an activity is onDestroy(). The system calls this method on your activity as the final signal that your activity instance is being completely removed from the system memory. Usually, the system will call onPause() and onStop() before calling onDestroy(). Describe a scenario, though, where onPause() and onStop() would not be invoked.

Sol:

onPause() and onStop() will not be invoked if finish() is called from within the onCreate() method. This might occur, for example, if you detect an error during onCreate() and call finish() as a result. In such a case, though, any cleanup you expected to be done in onPause() and onStop() will not be executed.

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.

4) 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?

Sol:

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.


Android framework offers several classes that help you off-load operations onto a separate thread running in the background. The most useful of these is IntentService. (https://developer.android.com/training/run-background-service/index.html)

Note well: Accessing the network from the UI thread throws a runtime exception in newer Android versions which causes the app to crash.

 

5) 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?

Sol:

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.
6) 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?

Sol:

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.

7) What is an Intent? Can it be used to provide data to a ContentProvider? Why or why not?
Sol:

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.

8) What is the difference between a fragment and an activity? Explain the relationship between the two.

Sol:

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.

9) What is difference between Serializable and Parcelable ? Which is best approach in Android ?

Sol:

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.

10) What is the difference between Service and IntentService? How is each used?
Sol:

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.

Source: https://www.toptal.com/android/interview-questions


11) What are “launch modes”? What are the two mechanisms by which they can be defined? What specific types of launch modes are supported?

Sol:

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.


12) Enumerate the three key loops when monitoring an activity

Sol:

Entire lifetime – activity happens between onCreate and onDestroy
Visible lifetime – activity happens between onStart and onStop
Foreground lifetime – activity happens between onResume and onPause


13) What role does Dalvik play in Android development?

Sol : Dalvik serves as a virtual machine, and it is where every Android application runs. Through Dalvik, a device is able to execute multiple virtual machines efficiently through better memory management.


14) When does ANR occur?

Sol: The ANR dialog is displayed to the user based on two possible conditions. One is when there is no response to an input event within 5 seconds, and the other is when a broadcast receiver is not done executing within 10 seconds.


15) What is AIDL?

Sol: AIDL, or Android Interface Definition Language, handles the interface requirements between a client and a service so both can communicate at the same level through interprocess communication or IPC. This process involves breaking down objects into primitives that Android can understand. This part is required simply because a process cannot access the memory of the other process.

Data types supported by AIDL are:

AIDL has support for the following data types:
-string
-charSequence
-List
-Map
-all native Java data types like int,long, char and Boolean


16)  What is a visible activity?

Sol: 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.


17) Is it possible to use or add a fragment without using a user interface?

Sol: Yes, it is possible to do that, such as when you want to create a background behavior for a particular activity. You can do this by using add(Fragment,string) method to add a fragment from the activity.


18) What is a Sticky Intent?

Sol: 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.


19) What is the difference between a regular bitmap and a nine-patch image?

Sol: In general, a Nine-patch image allows resizing that can be used as background or other image size requirements for the target device. The Nine-patch refers to the way you can resize the image: 4 corners that are unscaled, 4 edges that are scaled in 1 axis, and the middle one that can be scaled into both axes.

20) What is AAPT?

Sol: AAPT is short for Android Asset Packaging Tool. This tool provides developers with the ability to deal with zip-compatible archives, which includes creating, extracting as well as viewing its contents.

21) What all configuration changes can cause restart of the activity?

Sol:
1) orientation change
2) changing the default language
3) Inserting your device into a display dock
4) modifying the device’s default font scaling factor

We can use configChanges to prevent restart of the activity for certain configurations.

<activity android:name=".ProgressTestActivity"
     android:label="@string/app_name"
     android:configChanges="orientation|keyboardHidden|keyboard">
</activity>

Avoid using the configChanges attribute if possible. It is typically better to use other means to handle configuration changes, like the Android loader framework or headless retained fragments.