Android Interview Questions
- Which was the first mobile brand with Android Application?
Answer : First Mobile brand with Android Application was HTC.
- What is the current version of android and its API ?
Answer: Current version of android is “Pie” (as per Nov 2018) and its API level 28.
- Life cycle of Activity ?
Answer:
OnCreate() - This method is called when the activity is created .
It is called only once in activity lifecycle.
It is called only once in activity lifecycle.
OnStart() - This method is called when the activity is getting started ,
no user interactions will be done at this stage,and this method will be called several times in activity life cycle depending upon the user navigation.(Loads UI)
no user interactions will be done at this stage,and this method will be called several times in activity life cycle depending upon the user navigation.(Loads UI)
OnResume()- On this method call user can interact with the activity and perform actions like click.
OnPause()- When the other application comes in the foreground ,then the activity will get into pause state.
Ex : When your using an application ABC and call comes in ,where the call application comes in the foreground at this stage your ABC Application will enter into pause stage.
When the call is disconnected again your ABC Application will come in the foreground and will move to resume stage.
When the call is disconnected again your ABC Application will come in the foreground and will move to resume stage.
OnStop()- On stop the application will stop the activity and user interaction cannot be performed.
OnRestart()- The activity gets restarted and follows the same process.
OnDestroy()-The activity will be killed by the system
- When the application is in the foreground and you get a call , in what stage your application will get into?
Answer: OnPause
- Difference between onstop() and ondestroy() 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 shutdown the activity.
- What is fragment and Lifecycle of Fragments ?
Answer : Fragment can be called as mini activity which is called inside the
Activity. You can add and remove fragment while activity is running.
- What is android Manifest.xml ?
Answer: Android manifest .xml is an xml file which contains all the activities,services details and permissions defined in it . It contains all the essential information about our applications.
- Can Android Application be programmed only in Java ?
Answer: Yes, Android application can be programmed in other languages like NDK,C,C++ and Kotlin also.
- What is Intent? Difference between Implicit Intent and Explicit Intent?
Answer: Intent is used to perform an action inside the activity or to link one activity to another activity.
Implicit Intent : Performs action inside the same class such as calling webview ,send sms ,call etc.
Explicit Intent : It is used connect from one activity to another.
- Where do you define the icon for your activity ?
Answer: <activity android:icon="@drawable/app_icon" android:name=".MyTestActivity"></activity>
Where the image is saved in drawable folder.
- What is ANR notification in android and when do you get that error?
Answer: Application Not Responding is the exception raised when the too much of work is done on main thread.
- Enumerate three key loops when monitoring the activity?
Answer:
• Entire lifetime – activity happens between onCreate and onDestroy
• Visible lifetime – activity happens between onStart and onStop
• Foreground lifetime – activity happens between onResume and onPause.
- How can ANR be prevented?
Answer: Stop doing heavy jobs on main thread. Instead use worker threads such as IntentService, AsyncTask or another Thread.
- How to convert your code into .apk file?
Answer: Build-> Build APK(s)
- What is Service ? When do you use it?
Answer: Service is a component that runs in the background to perform long run operations.There are 2 types of service
a)Bound : It is called when the application is running and killed when the application is killer.It is bound with the application.
b)UnBound: It runs in the background even when application is not running /killed.
Service is called by extending the activity with the keyword “Service”
Ex: To track the delivery boy ,even if the application is not being used it will run in the background.
- What is BroadCast Receiver ? When do you use it?
Answer: Broadcast receiver is used to receive the broadcast messages from other applications or within the application.
Ex :Reading OTP , we check the incoming sms using broadcast receiver.
- What is Content Provider ? When do you use it?
Answer: Content provider is used to share data between two or more different applications .
Ex: sharing data between cab user and driver application
- What is Intent Filter ? When do you use it?
Answer: Intent filter defines the type of intent to which activity,services and broadcast receivers can respond.
Ex: In Manifest.xml we define the <intent filter> to define which activity as to be launched first.
- Difference between styles and themes ?
Answer: Styles is set of field attributes and values which is applied to the element called.
Theme is set of field attribute and values which is applied for the whole application once called .
- Difference between ArrayList and Hash<Map> ?
Answer:
ArrayList :
1.Arraylist is inserted in an order.
2. Data is fetched from arraylist depending upon the idex.
3.Arraylist allows duplicate values.
4.It is represented by ArrayList keyword.
Hash<Map> :
1. HashMap is stores data in key,value pair
2. Data is fetched from hashmap using key
3.Hashmap does not allow duplication
4.It is represented by Hash<Map>
- What are the different types of storage in android?
Answer: Android uses 3 types of storage:
1.Shared Preference: It stores small data.Shared Preferences allow you to save and retrieve data in the form of key,value pair.
2.Files: It stores data in text ,.mp3,mp4,.png,.jpg format, fetching data among same type of data is difficult.
3. Sqlite Database: It overcomes the disadvantages of shared preference and files .It can store any type of data ,update ,delete easily. Sqllite storage depends on our mobile storage capacity.
- Difference between Rest and Soap?
Answer:
Rest:
- Uses Xml ,text,html and Json format to send and receive data.
- Security is less than soap
- Transfers data through HTTP only.
- Performance is better than Soap since it uses less CPU
- It doesn’t need much bandwidth
- Rest can make use of Soap
Soap:
- Uses Xml only for sending and receiving data.
- It is more secure than rest.
- Transfers data through HTTP ,SMTP,FTP etc.
- Performance is not better than rest.
- It need more bandwidth for usage.
- Soap cannot use Rest.
- What is Async Task and methods of Async Task ?
Answer: Async task is a class that extends object class to allow short operations to run asynchronously in background .Async task runs in new thread.
Methods of Asynctask are :
1.onPreExecute: a step used to set up the task
2.doInBackground: a step used to perform the actual task
3.onProgressUpdate: a step used to update the current progress status of the task that is being performed in doInBackground
4.onPostExecute: once doInBackground finishes executing the task, this step delivers the result back to the main UI thread and stops the AsyncTask process
- What is Shared Preference and Write its Syntax ?
Answer: Shared Preference is used to store and retrieve small data like login details in the form of key value of pair.
To save data in SharedPreference:
Editor edit=SharedPreferences();
edit.putString(“key”,”value”);
edit.commit();
To retrieve data from shared Preference:
SharedPreferences share = new SharedPreference(key,Context.Mode_Private);
- What is RecyclerView ?
Answer:RecyclerView is a advanced and more flexible version of listview where single view using its custom adapter can replace listview and gridview by maintaining limited number of views and optimized memory usage.
- Difference between RecyclerView and Listview/Gridview?
Answer:
RecyclerView:
1.Horizontal scrolling is supported.
2. Recycler can be used as list or grid format depending on the requirement.
3.Recyclerview gives optimized memory usage , it will allocate data only to the list of data shown on screen and extra 2 on top and bottom of the list.
Listview:
1.Horizontal scrolling is not supported.
2.Listview cannot be used as gridview.
3.It allocates memory for all the items in the list and hence memory is not optimized.
- What is Card View?
Answer:Cardview is an UI element which displays the data in card format with corner radius and drop shadow elevation.
- What is Sqlite and its methods ?
Answer: Sqlite is a relational open source database which comes inbuilt in android devices which enables you to store,retrieve,manipulate and delete data.
Using Sqlite android application can run in offline mode also.
Sqlite is implemented in our project by extending the class with SqliteOpenHelper class which overrides 2 methods i.e;
1.oncreate() -Where the database is created along with its version .
2.onUpgrade() -It is supporting function of onCreate() when the version is updated the changes in database will be performed in onupgrade method without disturbing the existing one.
- How to integrate firebase ?
Answer: Firebase gives you tools and infrastructure from google to help you develop ,Firebase provides several API where each one perform their own functions and can be utilized in our application.Lets see basic steps to integrate firebase which will be same initial steps for all the firebase api integrations.
Step1: Go to tools in your project and select firebase where it shows all the firebase api’s or go to Developer.Firebase.com and register your application/project
Step2 : Now select the api you want to integrate and add the details of your project and register the api ex: We are implementing Crash analytics
Step 3: Download the google-service.json file provided and place it inside your project app folder
Step 4: Go to tools -> Firebase and you see the firebase api connected and follow the next process which adds the dependency into your application or dependencies can be added manually also by following the document.
Step 5: Now your firebase integration is ready where u can use this log in your code and can see in firebase account.
- How to integrate facebook into our application?
Answer:
Step1: Go to Developer.facebook.com and create your project.
Step 2: Make sure your gradle contains jcenter() ,if it doesn’t exists add it.
Step 3: Add dependency in our app gradle file and build project
implementation 'com.facebook.android:facebook-login:[4,5)'
Step 4:Open your /app/res/values/strings.xml file.
<string name="facebook_app_id">**********62401</string>
And your facebook app_id .
Step 5: Open your manifest add internet permission:
<uses-permission android:name="android.permission.INTERNET"/>
Step 6: Add metadata file inside your manifest .xml file inside application tag
<meta-data android:name="com.facebook.sdk.ApplicationId"
android:value="@string/facebook_app_id"/>
<activity android:name="com.facebook.FacebookActivity"
android:configChanges=
"keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="@string/app_name" />
<activity
android:name="com.facebook.CustomTabActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="@string/fb_login_protocol_scheme" />
</intent-filter>
</activity>
Step7: Add your package name , and the activity name where the facebook login button will be used.
Step 8: Generate keyhash ,there are several ways to generate keyhash one among them are as follows, run this set of code in application where it generates the keyhash in log or toast ,copy the keyhash code and place it in developers account
public void generateHashkey(){
try {
PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
String hashKey = new String(Base64.encode(md.digest(), 0));
Log.e("hashkey",hashKey);
}
} catch (NoSuchAlgorithmException e) {
Log.e( "hashkey", String.valueOf(e));
} catch (Exception e) {
Log.e("hashkey", String.valueOf(e));
}
}
Step 9 : Add a facebook login button in the activity mentioned
<com.facebook.login.widget.LoginButton
android:id="@+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="30dp"
android:layout_marginBottom="30dp" />
Step 10: Add the following set of code which is given step by step in facebook doc and looks like this in the end .
public class MainActivity extends AppCompatActivity {
public class MainActivity extends AppCompatActivity {
//Facebook Login in
CallbackManager callbackManager;
//Initializing textview
TextView userdetails;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userdetails=(TextView)findViewById(R.id.txt);
//CallbackManager of facebook -REFER Developer.Facebook.com and follow as per the instruction
callbackManager = CallbackManager.Factory.create();
//Initializing facebook login button
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
//Permission for the user to his email and other details
loginButton.setReadPermissions("email");
//On click of facebook login button calls the method getUserdetails
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
//Prints accessToken (optional) for facebook login
AccessToken accessToken = loginResult.getAccessToken();
//Prints the login userdetails provided by FB.
getUserDetails(loginResult);
}
//On cancel click of fetching data
@Override
public void onCancel() {
// App code
}
//On error in fetching userdetails from facebook api
@Override
public void onError(FacebookException exception) {
// App code
}
});
}
//callback manager call back method
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
//response of userdetails provided by facebook
protected void getUserDetails(LoginResult loginResult) {
GraphRequest data_request = GraphRequest.newMeRequest(
loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(
JSONObject json_object,
GraphResponse response) {
Log.e("user_details",json_object.toString());
userdetails.setText(json_object.toString());
/* Intent intent = new Intent(MainActivity.this, UserDetails.class);
intent.putExtra("userProfile", json_object.toString());
startActivity(intent);*/
}
});
Bundle permission_param = new Bundle();
permission_param.putString("fields", "id,name,email,picture.width(120).height(120)");
data_request.setParameters(permission_param);
data_request.executeAsync();
}
protected void onResume() {
super.onResume();
// Logs 'install' and 'app activate' App Events.
AppEventsLogger.activateApp(this);
}
@Override
protected void onPause() {
super.onPause();
// Logs 'app deactivate' App Event.
AppEventsLogger.deactivateApp(this);
}
- Difference between picasso and glide?
Answer:
Picasso:
- Doesn’t support gif image.
- Downloads the image and stores full image in cache.
- Less memory efficient compared to Glide.
Glide :
- Supports Gif images.
- Downloads the image ,resize it to imageview size and stores in disk cache.
- More memory efficient.
- Difference between volley and Retrofit?
Answer:
Volley:
- Volley as caching mechanism
- Volley enables retry policy
- In Volley Json response is parsed manually.
- Volley as inbuilt image loader support
Retrofit:
- Retrofit doesn’t have caching mechanism
- Retrofit doesn’t support retry policy.
- Volley supports automatic parsing.
- Retrofit doesn’t have inbuilt image loader support ,which can be performed by using picasso/glide library.
- What is web service and how do you achieve it?
Answer:Webservice is a means of communication between your application and the server, where the data sent from application is stored into the server and data stored in server is retrieved by application.Web Service uses Soap or REST as a means of communication.
Webservice in android can be achieved by making API call . To make an API call we can use libraries like volley ,retrofit and OKHTTP etc.
- What is Service and types of services?
Answer: Service is a android component which runs in the background even when the application that started service is destroyed.
There are two types of service :
1.Bound Service - It is bound with the application and destroyed when the application or service is killed.
2.UnBound Service -It is not bound with the application ,once the service is started it runs in the background even when the application which started the service is destroyed.
- What is singleton and what is it use?
Answer: Singleton ensures only single instances/object will be created which can be used by all the other classes. It helps save memory since only one object is created.
- What is broadcast receiver ?
Answer: BroadCast Receivers are one which receives the message from other application or system itself.
Ex: The notification which we get when battery is charged.
- How to make responsive application which is used in mobile and tablet?
Answer:Application can be made responsive my creating two different layouts with same name and id’s.
res/layout/main_activity.xml # For phones
res/layout/main_activity_tablet.xml # For tablets
res/layout/main_activity_tablet.xml # For tablets
And calling it in your java class.
public class MyActivity extends Activity {
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate();
Configuration config = getResources().getConfiguration();
if (config.smallestScreenWidthDp >= 600) {
setContentView(R.layout.main_activity_tablet);
} else {
setContentView(R.layout.main_activity);
}
}
}
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate();
Configuration config = getResources().getConfiguration();
if (config.smallestScreenWidthDp >= 600) {
setContentView(R.layout.main_activity_tablet);
} else {
setContentView(R.layout.main_activity);
}
}
}
- What is the limit of data storage in sqlite?
Answer: Maximum data SQLite can store depends on storage space of your device.
- What is intent service?
Answer : Intent Service is used in long task where there is no communication with main thread.Intentservice runs on separate worker thread.
- What is the use of Bundle savedInstanceState?
Answer: savedInstanceState is a method parameter of oncreate method which saves the state of the activity.
Ex: When the activity goes into the background the state of the activity will be paused ,which is stored in savedInstanceState and helps to revoke the activity from same state.
APK- Application Packaging Key/Kit(It is a compressed key with classes, UI's, supportive assets and manifest. All files are compressed to a single file is called APK.)
AAPT- Application Assets Packaging Tool (It handles the packaging process)
ADB - Android Debug Bridge ( It is a command line tool that is used to communicate with the emulator instance)
NDK - Native Development Kit(By using NDK, you can develop a part of an app using native language such as C/C++ to boost the performance.)
ANR -Application not responding ( this message appears when too many work is done on main thread)
Google Android SDK- Android Software Development Kit (The Google Android SDK is a toolset which is used by developers to write apps on Android-enabled devices)
ADT- Android Development Tool(It is used to develop the applications and test the applications.)
DDMS- Dalvik Debug monitor service (It allows to debug Port forwarding services,Screen capture,Thread and heap information,Network traffic tracking,Location data spoofing.
Happy Reading 😊
Thank You
Sushmitha N
Hi there ! Im a experienced android developer with 4years of revelant exprience.My Skills include Android,Core Java ,Oops and Kotlin.
Comments
Post a Comment