Current Android Release version:
Version Code: Pie
Version: 9
API level: 28

Showing posts with label Android. Show all posts
Showing posts with label Android. Show all posts

Android Interview questions

1) Which method is called only once in Fragment life cycle?
2) Explain Fragment life cycle? What is the use of Fragments?
3) What is Intent? Difference between Implicit and Explicit Intents?
4) How to Display Toast message in Asyctask in doInBackground method?
5) 
What is an Application Not Responding (ANR) error, and how can you prevent them from occurring in your app?
6) Retrofit vs Volley? Which is the best to use in android?
7) Glide vs Picasso? Which is more efficient?
8) If you nest a RelativeLayout inside a LinearLayout then which layout parameters will the RelativeLayout use?
        a. RelativeLayout.layoutparams
        b. Viewgroup.margin
        c. Viewgroup.layoutParams
        d. LinearLayout.layoutParams

9) In Photo sharing app, user receives new photo and a notification is created and the user clicks on the notification. What do you attach to the notification to open the app and show the user the photo?
        a. intent
        b. photoIntent
        c. PendingIntent
        d. Service

10) App that periodically checks if something is "working" What do you use?
        a. Wake lock with power manager
        b. setInexactRepeating
        c. Post Handler
        d. call set periodic timer

11) 
The user is in their text messaging app - they click share - how do you get your app to show up?
        a. intent service
        b. broadcast receiver
        c. register content observer to telephone
        d. register an intent filter

12) 
What is the difference between a fragment and an activity? Explain the relationship between the two?
13) 
What is difference between Serializable and Parcelable ? Which is best approach in Android ?
14) 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?
15) 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?
16) What is UI/Main thread in Android
17) When can you use Thread over Service?
18) Explain detail about your favorite android API?
19) Difference between Views and Fragments?
20) Why are 2 boot loaders used in Android
21) What is binder in Android
22) What’s the difference between onCreate() and onStart()?
23)  What are the various ways an Android developer can apply multi-threading to their app?
24) LinearLayout vs RelativeLayout
25) Describe image caching
26) What is the difference between a regular .png and a nine-patch image?
27) What is difference between Serializable and Parcelable? Which is best approach in Android?
28) What are the four essential states of an activity?

     
     The four essential states of an activity are:
  • 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
29) What is dp, sp, pt, and px?
30) Explain MVP? Advantages over MVC
31) Explain MVVM? Advantages over MVC and MVP
32) What are the things which you mention in Manifest File
33) Suppose your doInBackGround() is running, and you rotated your device,
What will happen?
34) Can we execute AsyncTask from another AsyncTask’s doInBackground() method?
35) Activity Life Cycle, in detail?
36) How will you send data between two Fragments
37) Difference between ListView and RecyclerView
38) Explain Job Scheduler in detail
39) Difference between notifyDataSetChanged and notifyItemChanged
40) What is the difference between Dynamic Receiver and Static Receiver. Which to use when?
41) Which lifecycle method gets called when A goes to B/come back to A?
      Activity Launch Modes with examples
42) Let’s say 4 activities are there A->B->C->D. How to launch A from D finishing in between activities?
43) 4 Activities are there A->B->C->D.How to finish application from D if none of the activities opened earlier finished till now?
44) How CLEAR_TOP flag intent works in android
45) Service vs IntentService?When to prefer which type of service?
46) Explain ways for Activity to activity communication/Activity to fragment communication/Fragment to fragment communication
47) How to make a service persist even after Application killed
48) How to handle Background service and execution limits with new Oreo Updates?
49) Why do we use Headless fragments?
50) Suppose you have 10 images to fetch from Server. What is the best way to fetch images?
51) Should we provide a context in presenter/Model? Answering yes/no is not enough. You have to provide a solution for it.
52) Why do we prefer Framelayout for Fragments?
53) How to make a custom view in android? Explain lifecycle methods.Difference between onLayout/onMeasure.
54) Have you ever faced any issue with SingleInstance launch mode or example if you have used it? Providing real-life examples are preferred more.
55) How to load Large Bitmaps? Handle Memory leaks and Sample sizing
56) How to retain data on orientation change? Explain lifecycle during orientation changes.
57) What the Fragment’s method setRetainInstance(boolean) does?
58) How to analyse and fix Activity transition flickering in android?

59) Main components of android 
60) What are Activities Life cycles, explain with an Example? 
61) Explain remote service. 
62) Explain pending intent. 
63) What is advantage of pending intent over intent? 
64) Explain Broadcast Receivers with an Example 
65) Explain content provider and content resolver. 
66) Explain content provider and content resolver with help of a sample code. 
67) What is .apk? How is it generated? 
68) What is .aidl file? Can we use any different name instead of .aidl and create interface using any commands? 
69) What are threads? 
70) What are the two ways of implementing threads and which is the better one? 
71) startBroadcast(), startOrderBroadcast() and startStickyBroadcast() 
72) What are the different states of a thread? 
73) Explain Widget in android? 
74) Explain about android runtime environment. 
75) What is a Launcher? 
76) Explain init.c with respect to Dalvik Virtual Machine? 
77) Explain Services?Different type of services? 
78) Explain aidl interface and its implementation? 
79) Explain remote service with examples? 
80) Explain intent filter and intents? 
81) If an activity ‘A’ starts activity ‘B’ and ‘B’ starts another activity ‘C’,what is the method to call to finish all activities? 
82) Explain startService() and bindService()? 
83) What is content Resolver?Is it a wrapper Class? 
84) What is the difference between content receiver and content Provider? 
85) Explain Service Lifecycle? 
86) Local service and remote service? 
87) What are Broadcast Receivers and how to register them statically and dynamically? 
88) What are Content providers and how do we access the data? 
89) What adb commands you have used? 
90) What is manifest file? What all are mentioned in AndroidManifest.xml
91) What is category,action and data in intents and how they work? 
92) Shared preference - how to get it? 
93) Android listview and adapters 
94) How android manage applications on low memory? 
95) Pass data across different applications 
96) How to start Activity of another application 
97) How to use Bundles and pass parameters? 
98) How to make an Activity to launch at start 
99) Can we have two launcher Activities? 
100) How to make onCreate execute multiple times? 
101) How to get intent in a newly launched Activity 
102) How to troubleshoot when adb is not detecting device 
103) List some adb commands 
104) If I want to save the state of activity,in which method of lifecycle , I have to store? 
105) When OnsaveInstantState method will be called? 
106) Difference between service and broadcast-receiver? 
106) Difference between Activity and view
107) What is Shared Preference and difference with normal preference
108) What are the killable methods in Activity life cycle?

109) Can Activity run in background? 
110) What is layout and what are the different types of layouts? 
111) What is the difference between linear and relative layout? 
112) Can linear layout be nested in relative layout and vice versa? 
113) How to position the layout? 
114) Diff b/w SimpleCursorAdapter and CursorAdapter 
115) What is Handlers and its implementation. 
116) How Library and frameWork layer communicating. 
117) What is JNI.How it works. 
118) Difference between cursor adapter and Simple cursor adapter. 
119) How do you debug your application.

120) What are the different types of launch modes in Android and How to declare for Activity?
121) What is Application class?
122) What is Context? How is it used? 
123) What is the structure of an Android Application?
124) What is the difference between a Fragment and an Activity? Explain the relationship between the two.
125) Why is it recommended to use only the default constructor to create a Fragment? 
126) How would you communicate between two Fragments? 
127) What is retained Fragment?
128) What is View in Android?
129) Difference between View.GONE and View.INVISIBLE?
130) What are ViewGroups and how they are different from the Views?
131) What is a canvas?
132) What is a SurfaceView?
133) What is Constraint Layout?
134) What is the difference between ListView and RecyclerView?
135) What is the ViewHolder pattern? Why should we use it?
136) What the difference between Dialog and Dialog Fragment?
137) What is a Sticky Intent?
138) Is it possible to run an Android app in multiple processes? How?
139) What can you use for background processing in Android?
140) How would you perform a long-running operation in an application?
141) Why should you avoid to run non-ui code on the main thread?
142) What are the problems in asynctask?
143) When would you use java thread instead of an asynctask?
144) What is a Loader?
145) Explain Looper, Handler and HandlerThread
146) How to persist data in an Android app?
147) What is ORM? How does it work?
148) How would you preserve Activity state during a screen rotation?
149) What are different ways to store data in your Android app?
150) What is a Spannable?
151) What is the onTrimMemory() method?
152) How does the OutOfMemory happens?
153) How do you find memory leaks in Android applications?
154) What is Doze? What about App Standby?
155) What is overdraw?
156) How did you support different types of resolutions?
157) What are the different protection levels in permission?
158) What is the Dalvik Virtual Machine?
159) What is the difference JVM, DVM and ART?
160) What is DEX?
161) Can you manually call the Garbage collector?
162) What is ADB?
163) What is Lint? What is it used for?
164) Why Bundle class is used for data passing and why cannot we use simple Map data structure
165) How do you troubleshoot a crashing application?
166) Explain Android notification system?
167) What is AAPT?
168) What is the best way to update the screen periodically?
169) HashMap, ArrayMap and SparseArray
170) What are Annotations?
171) What is the support library? Why was it introduced?
172) What is Android Data Binding? 
173) What are Android Architecture Components?
174) Describe how REST APIs work. What is REST?
175) Reverse Engineering an APK.
176) What is proguard used for?
177) About multiple apk for android application
178) What is obfuscation? What is it used for? What about minification?
179) onSavedInstanceState() and onRestoreInstanceState() in activity?
180) How will you pass data to sub-activities?
181) Explain Fragment Life Cycle?
182) When activity is moved to stopped state, then what will happen to the life cycle of a fragment which is in that activity?
183) Is Fragment Life Cycle dependent on Activity Life Cycle?
184) How to call context in Fragment?
185) Explain the parameters of onCreateView()?
186) android.app.Fragment vs android.support.v4.app.Fragment?
187) How many ways to call Fragment?
188) What is FragmentManager Class?

189) Difference between Activity vs FragmentActivity?
190) How to handle the backPress in Fragment?
191) How to Persist data between configurations changes?
192) What is Headless Fragment?
193) How to begin the transaction?
194) Difference in adding and replacing a Fragment?

What is Kotlin?

Kotlin is a general purpose, open source, statically typed “pragmatic” programming language for the JVM and Android that combines object-oriented and functional programming features. 

Kotlin is officially supported language for Android.

JetBrains, known for IntelliJ IDEA (Android Studio is based on IntelliJ IDEA), introduced the Kotlin language in 2011.

Android Latest versions and API levels

The code names match the following version numbers, along with API levels and NDK releases provided for convenience:
Code nameVersionAPI level
Pie9API level 28
Oreo8.1.0API level 27
Oreo8.0.0API level 26
Nougat7.1API level 25
Nougat7.0API level 24
Marshmallow6.0API level 23
Lollipop5.1API level 22
Lollipop5.0API level 21
KitKat4.4 - 4.4.4API level 19
Jelly Bean4.3.xAPI level 18
Jelly Bean4.2.xAPI level 17
Jelly Bean4.1.xAPI level 16
Ice Cream Sandwich4.0.3 - 4.0.4API level 15, NDK 8
Ice Cream Sandwich4.0.1 - 4.0.2API level 14, NDK 7
Honeycomb3.2.xAPI level 13
Honeycomb3.1API level 12, NDK 6
Honeycomb3.0API level 11
Gingerbread2.3.3 - 2.3.7API level 10
Gingerbread2.3 - 2.3.2API level 9, NDK 5
Froyo2.2.xAPI level 8, NDK 4
Eclair2.1API level 7, NDK 3
Eclair2.0.1API level 6
Eclair2.0API level 5
Donut1.6API level 4, NDK 2
Cupcake1.5API level 3, NDK 1
(no code name)1.1API level 2
(no code name)1.0API level 1

Android Jetpack

Google IO 2018 introduced Android Jetpack.

Android Jetpack is a set of libraries, tools and architectural guidance to help make it quick and easy to build great Android apps. It provides common infrastructure code so you can focus on what makes your app unique.

Android Jetpack is available from Android Studio 3.2.

Android Jetpack is backward compatible library supports till Android 4.4 versions



For more information: https://developer.android.com/jetpack/

Android: Autosizing TextViews

Android O introduced new feature to autosize the Textview based on its layout. This setting makes it easier to optimize the text size on different screens with dynamic content.

The Support Library 26.0 Beta provides full support to the autosizing TextView feature on devices running Android versions prior to Android O. The library provides support to Android 4.0 (API level 14) and higher. The android.support.v4.widget package contains the TextViewCompat class to access features in a backward-compatible fashion

There are three ways you can set up the autosizing of TextView:

  • Default
  • Granularity
  • Preset Sizes
Default:

To define the default setting in XML, use the android namespace and set the autoSizeTextType attribute to none or uniform.

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:autoSizeTextType="uniform"
  />
Granularity:

You can define a range of minimum and maximum text sizes and a dimension that specifies the size of each step. The TextView scales uniformly in a range between the minimum and maximum size attributes. Each increment occurs as per the step size set in the granularity attribute.

<TextView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:autoSizeTextType="uniform"
  android:autoSizeMinTextSize="12sp"
  android:autoSizeMaxTextSize="100sp"
  android:autoSizeStepGranularity="2sp"
/>

Preset Sizes:

Preset sizes lets you specify all the values that the TextView picks when automatically auto-sizing text.

To use preset sizes to set up the autosizing of TextView in XML, use the android namespace and set the following attributes:
  • Set the autoSizeText attribute to either none or uniform. none is a default value and uniform lets TextView scale uniformly on horizontal and vertical axes.
  • Set the autoSizePresetSizes attribute to an array of preset sizes. To access the array as a resource, define the array in the res/values/arrays.xml file.

    <resources>
      <array
        name="autosize_text_sizes">
        <item>10sp</item>
        <item>12sp</item>
        <item>20sp</item>
        <item>40sp</item>
        <item>100sp</item>
      </array>
    </resources>
    <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:autoSizeTextType="uniform"
      android:autoSizePresetSizes="@array/autosize_text_sizes"
    />

More information will be available in official Android developer documentation:
https://developer.android.com/preview/features/autosizing-textview.html#setting-textview-autosize

Android: Working with Fonts

Fonts feature can be used from Android O version. You can create "font" folder in resources folder of your application. Below Font features are providing in Android O release.

  • Fonts in XML
  • System Fonts

Fonder name in Android application: res/font/

Adding the font files in the resource directory

Using Fonts in XML file:
<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="@font/lobster"/>

Using Fonts Programatically:
Typeface typeface = getResources().getFont(R.font.myfont);
textView.setTypeface(typeface);
Retrieving System Fonts:
FontManager fontManager = context.getSystemService(FontManager.class);
FontConfig systemFontsData = fontManager.getSystemFonts();

For more information, Check in official Android developer documentation.
https://developer.android.com/preview/features/working-with-fonts.html

Android: runOnUiThread ()

runOnUiThread is useful whenever you want to update UI from background thread.

Activity_Name.this.runOnUiThread (new Runnable () {
       @override
        public void run () {
               //add code to update UI 
        }
});

Chrome Custom Tabs in Android

Chrome custom tabs give apps more control over their web experience.
CustomTabs is part of chromium platform.

Chrome Custom Tabs is now generally available to all users of Chrome, on all of Chrome's supported Android versions (Jellybean onwards).

Chrome Custom Tabs allow an app to customize how Chrome looks and feels. An app can change things like:
  • Toolbar color
  • Enter and exit animations
  • Add custom actions to the Chrome toolbar, overflow menu and bottom toolbar
Launching links in custom tabs more faster than chrome and webview.



Implementation:

First, add custom tab library in build.gradle file.


dependencies { 
        ... 
        compile 'com.android.support:customtabs:23.3.0' 
}

Then, start url with custom tabs

String url = ¨https://coderinsight.blogspot.com/¨; 
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(this, Uri.parse(url));

after this you can customize tabs based on your needs.

More information will be available in below official Chrome page:
https://developer.chrome.com/multidevice/android/customtabs


Android Intent Service

What is Intent Service:

Intent Service is a base class for service. This handles asynchronous requests 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 It will stop by itself as soon as it is done performing the task.


All requests are handled on a single worker thread.


How to create Intent Service:

For using IntentService, create a class which extends IntentService and implement onHandleIntent(Intent). It will receive requests and handle them in background thread.


A single background thread is used to handle all the requests and requests are processed one by one. It might take time to process one request and other one has to wait for that time. When all requests have been handled, the IntentService stops itself.

public class MyService extends IntentService {
    MyService () 
    {
       super("MyService");
    }
    @Override
    protected void onHandleIntent(Intent intent) {
     //This method is invoked on the worker thread with a request to process 
    }
}

Limitations:
  • At a time it will process only one request
  • Can not be interrupted
  • The IntentService cannot run tasks in parallel. Hence all the consecutive intents will go into the message queue for the worker thread and will execute sequentially.the request waits until the first operation is finished.
  • It can't interact directly with your user interface.


Differences between Service & IntentService:
  • Service uses application main thread. Intent Service create worker thread to perform operations.
  • The Service can be used in tasks with no UI, but shouldn't be too long. If you need to perform long tasks, you must use threads within Service.The IntentService can be used in long tasks usually with no communication to Main Thread. If communication is required, can use Main Thread handler or broadcast intents. 
  • The Service is triggered calling to method onStartService(). The IntentService is triggered using an Intent.
  • The Service runs in background but it runs on the Main Thread of the application. The IntentService runs on a separate worker thread.

Understanding Android Broadcast Receivers

A broadcast receiver is an Android component which allows you to register for system or application events. All registered receivers for an event are notified by the Android run time once this event happens.

Create Broadcast Receiver:

Create Receiver class by extending BroadcastReceiver class.
Below onReceive() method will execute whenever your receiver gets notifications whenever the system event, for which it is registered, occurs.

public class MyReceiver extends BroadcastReceiver 
{
     @Override
     public void onReceive(Context context, Intent intent) 
     {
        // Implement code here to be performed when broadcast is detected
     }
}

The Broadcast Receiver object is active only for the duration of onReceive (Context, Intent). Once your code returns from this function, 
the system considers the object to be finished and no longer active.

When a matching broadcast is detected, the onReceive() method of the broadcast receiver is called, at which point the method has 10 seconds time within which to perform any necessary tasks before returning. So, Don't perform any long operations on onReceive() method. To perform long running operations inside onReceive() method, always start Services or use goAsync() method.

you can use goAsync() method to create another thread to perform long operations. This can be called by an application in onReceive(Context, Intent) to allow it to keep the broadcast active after returning from that function. This does not change the expectation of being relatively responsive to the broadcast (finishing it within 10s), but does allow the implementation to move work related to it over to another thread to avoid glitching the main UI thread due to disk IO.

You cannot launch a popup dialog in your implementation of onReceive() and also you can not bind to existing service.For the former, you should instead use the NotificationManager API. For the latter, you can use Context.startService() to send a command to the service.

Register Broadcast Receiver:

Broadcast receivers can be registered in two ways.
  • Static: With this approach, your receiver will be active to listen for events even if your application is not launched.
       Use <receiver> tag to register broadcasts in manifest file.
       <receiver
               android:name="com.example.techchai
               android:exported="true" >
               <intent-filter>
                     <action android:name="com.example.broadcast" />
               </intent-filter>
       </receiver>

  • Dynamic: Receivers are tightly coupled with Activity or Fragment life cycles. This receiver will listen for events only when your application is active only.
       IntentFilter filter = new IntentFilter("com.example.Broadcast");
       MyReceiver receiver = new MyReceiver();
       registerReceiver(receiver, filter);

    • When a broadcast receiver registered in code is no longer required, it may be unregistered via a call to the unregisterReceiver(receiver) method of the activity class. 
    • Dynamically registered receivers are called on the UI thread. Dynamically registered receivers blocks any UI handling and thus the onReceive() method should be as fast as possible.

Types of Broadcast Receivers:
  • Normal BroadcastReceiver: (sent with Context.sendBroadcast) are completely asynchronous. All receivers of the broadcast are run in an undefined order, often at the same time.This is more efficient, but means that receivers cannot get the results.
  • Ordered BroadcastReceiver: (sent with Context.sendOrderedBroadcast) are delivered to one receiver at a time..are completely synchronous. These will follow a specific order.The order is defined using android:priority attribute in Manifest file. The receivers with greater priority would receive the broadcast first. In case there are receivers with same priority levels, the broadcast would not follow an order. Sometimes to avoid system overload, run time system delivers the broadcasts one at a time, even in case of normal broadcasts. However, the receivers still cannot use the results.
  • Sticky BroadcastReceiver: This method is deprecated in API level 21 due to security concerns.

Security:

As the broadcast receivers have a global work-space, security is very important concern here. If you do not define the limitations and filters for the registered receivers, other applications can abuse them.
  • When you use registerReceiver(BroadcastReceiver, IntentFilter), any application may send broadcasts to that registered receiver. You can control who can send broadcasts to it through permissions.
  • When you use sendBroadcast(Intent) normally any other application can receive these broadcasts. You can control who can receive such broadcasts through permissions. Alternatively, you can also safely restrict the broadcast to a single application with Intent.setPackage.
  • Whenever you publish a receiver in your application’s manifest, make it unavailable to external applications by using android: exported=”false”. 

Conclusion:

If you don't need to send broadcasts across applications, consider using LocalBroadcastManager. This will give you a much more efficient implementation (no cross-process communication needed) and allow you to avoid thinking about any security issues related to other applications being able to receive or send your broadcasts.

Refer usage of LocalBroadcastManager.