InterviewSolution
This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.
| 1. |
I have created one application where I am trying to create a task to send a notification daily at 5:00 am. And my requirement is this task should run even if the application is off. Can you suggest me a good solution to write code for this task? |
|
Answer» There is no direct way to terminate a thread but using the two following ways it can be done.
|
|
| 2. |
I have design one application where I have an async task to get a string value and this value I am using to update the textView in OnPostExecute(). But when I am running it I found MemoryLeak issue. Can you please tell me how to resolve that? |
|
Answer» Here we have to create an application that schedules a task and send a notification. For that, we need to execute a particular JOB daily at a specific time defined by the user. We can do it using the AlarmManager in android. Android has a built-in AlarmManager class which makes SCHEDULING tasks. AlarmManager PROVIDES access to system-level alarm services. This gives a way to perform any operations outside the lifetime of your application. So we can trigger events or actions even when your application is not running. Step to schedule task is mentioned below:
Please find below code for more detail: // check task is scheduled or not boolean alarmUp = (PendingIntent.getBroadcast(this, 0, new Intent("com.example.dummy.AlarmReceiver"), PendingIntent.FLAG_NO_CREATE) != null); if ( !alarmUp) { Intent intent = new Intent("com.example.dummy.AlarmReceiver"); intent.putExtra("activate", true); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 1); calendar.set(Calendar.SECOND, 0); AlarmManager alarmManager = (AlarmManager) this.getSystemService(this.ALARM_SERVICE); alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent); calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.set(Calendar.HOUR_OF_DAY, 7); calendar.set(Calendar.MINUTE, 0); alarmManager = (AlarmManager) this.getSystemService(this.ALARM_SERVICE); PendingIntent pendingIntent2 = PendingIntent.getBroadcast(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT); alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent2); |
|
| 3. |
I have to design one application where if update us going on Screen should ON. What approach I should follow here to make Screen On. |
|
Answer» In Android, it is very normal to found memory leak scenario as many TASKS are running in the background thread. Many TIME if ACTIVITY or fragment who start background thread using Async task is KILLED, Still the background thread will be alive. We can handle this problem by calling the method removeCallbacksAndMessages on the handler in the onDestroy method of the activity. If we cancel the task, we will not cause a memory leak. We can also solve that problem by constructing the new JAVA file with a context.getApplicationContext() instead of normal getContext / this (Activity). Then it will not be tied to the activity but to the application. We won't be able to access the dialog in onPostExecute(). Instead, we can use a callback to a listener if we want. Please find below code for more detail: @Override protected void onDestroy() { super.onDestroy(); //This resolves the memory leak by removing the handler references. mHandler.removeCallbacksAndMessages(null); |
|
| 4. |
Take a scenario where I have to design a screen in Frame Layout. In this frame layout, I have 4 child view for displaying buttons for other functionality. But when I am running it they are overlapping with each other.Can you suggest me a solution to resolve this problem? |
|
Answer» For doing some job like Application Update or where you want your CPU KEEPS running before the device go to sleep so we can use Power MANAGER service. This service will GIVE you ONE feature like WakeLock that allows our application to control the power state. if we need to want to keep the screen on in our activity, we need to use FLAG_KEEP_SCREEN_ON. As mention below: permission android:name="android.permission.WAKE_LOCK" />We will write below code in activity.java // Get an instance of the SensorManager mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); // Get an instance of the PowerManager mPowerManager = (PowerManager) getSystemService(POWER_SERVICE); // Get an instance of the WindowManager mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE); mWindowManager.getDefaultDisplay(); // Create a bright wake lock mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, getClass() .getName()); |
|
| 5. |
Explain what is ADBD tool in android how you can install it and how it will connect with Emulator. |
|
Answer» In Android we have one draw back with Frame layout, when you have multiple CHILD view in Frame layout, they used overlap each other. For resolving this problem we can use CoordinatorLayout. In Coordinator Layput has additional level of control over it’s child views. It can coordinates the animations and transitions of child views with one another.Please find below CODE where we are adding child view in coordinator view. <android.support.design.widget.CoordinatorLayout xmlns:android="HTTP://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="TRUE"> <android.support.design.widget.AppBarLayout android:id="@+id/app_bar" android:layout_width="match_parent" android:layout_height="@dimen/app_bar_height" android:fitsSystemWindows="true" android:THEME="@style/AppTheme.AppBarOverlay"> <android.support.design.widget.CollapsingToolbarLayout android:id="@+id/toolbar_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" app:contentScrim="?attr/colorPrimary" app:layout_scrollFlags="scroll|exitUntilCollapsed"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:layout_collapseMode="pin" app:popupTheme="@style/AppTheme.PopupOverlay" /> <TableLayout android:layout_width="match_parent" android:layout_height="wrap_content"/> </android.support.design.widget.CollapsingToolbarLayout> </android.support.design.widget.AppBarLayout> <include layout="@layout/content_scolling" /> <android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="@dimen/fab_margin" app:layout_anchor="@id/app_bar" app:layout_anchorGravity="bottom|end" app:srcCompat="@android:drawable/ic_dialog_email" /> </android.support.design.widget.CoordinatorLayout> |
|
| 6. |
Create an Android Activity with component like Email and Password. You need to write to code for auto fill data in field of Email and password. How you will do that. |
|
Answer» ADB is an Android device bridge command-line tool. Basically, we are using ABD for controlling your device over USB from a computer and we can copy files back and forth, install and uninstall apps, RUN shell commands. ADB LETS you modify your device and its software using the PC command line. Before connecting with ADB we need to remember to put your device in USB debugging mode. This can be found by navigating to Menu>Settings>APPLICATIONS>Development and checking the box for USB debugging. WITHOUT doing this, your PC won’t recognize your device. ADB is part of Android SDK, from here we can download it. You can connect it using the Terminal window of Android Studio. Once ADB, install we can all device connected with your machine in this terminal. If your device does not show up, you may have an issue with your drivers. We have many Linux command here to control device. Some commands are: ll <path-to-file-on-device> <destination-path-on-computer> * This command pulls a file from your device to your computer.* adb install -r <path-to-APK-file> This command installs an APK file (an APP) from your computer to your phone. adb logcat This command displays a real-time stream of your device's log on your computer. |
|
| 7. |
Design one custom view for displaying TextView in UI with a attributes tribute like Title and Colour. |
|
Answer» In your scenario, we have to DESIGN a login screen in the application where the login activity is having two control an email and a password. An email we want to display AUTOFILL data based on the user email address. We will USE AutoCompleteTextView in our layout to display email and password data. What we can do here in our Java activity we can create an object of Account Manager and we load the user accounts through the AccountManager. As some accounts MAY not have an email address linked to them, we filter them and keep only the ones who match an email regex. We also use a Set to remove the duplicates. Now we just have an array of Strings as the data source and we just bind via an ArrayAdapter the list of an email address. Now we can display data of email and password in autocomplete text view. One we need to REMEMBER before running this code we need to add below permission in our manifest file. android.permission.GET_ACCOUNTSThe layout file will look like this: <AutoCompleteTextView android:id="@+id/autoCompleteTextView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:text="Enter Email Address" />And. Activity, java file will be like this: private ArrayAdapter<String> getEmailAdapter(Context context) { Account[] accounts = AccountManager.get(context).getAccounts(); String[] addresse= new String[accounts.length]; for (int i = 0; i < accounts.length; i++) { addresses[i] = accounts[i].name; } return new ArrayAdapter<String>(context, android.R.layout.simple_dropdown_item_1line, addresses); |
|
| 8. |
Take the scenario where we have two applications from the same package like Gmail and Google Calendar. This app can share data with each other for example Gmail meeting mail will save in Google calendar. Now how we will make sure the data cannot be used by some other third party application. How you will secure your data? |
|
Answer» When we need to create any custom VIEW in Android, we will EXTEND our class from the View parent class. In this scenario, as we need to create a custom Text view so we will create a subclass of TextView class. And then we can our Custom textview in a layout.xml file. For example please follow below code where I am trying to create Custom TextView CustomTextView extends TextView { private String title; private boolean COLOR; title = tarry.getString(R.styleable.CustomTextView_settitle); if(title == null) setText("Custom Message"); else setText("Welcome to the Class"); color = tarry.getBoolean(R.styleable. CustomTextView _setColor, false); if(color == true) setTextColor(Color.RED); }We need to define our custom textview in \res\layout folder and write the code LIKE as shown below. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:app="http://schemas.android.com/apk/res-auto" android:orientation="vertical"> <com.example.CustomTextView android:layout_width="wrap_content" android:layout_height="wrap_content" app:settitle="Welcome" app:setColor="true" android:layout_marginTop="200dp" android:layout_marginLeft="120dp" android:textStyle="bold" android:textSize="18dp"/> </LinearLayout> |
|
| 9. |
Suppose if I want to change menu Item at runtime what approach I should follow? |
|
Answer» In Android, applications cannot ACCESS the data of other application. For sharing data between two applications, we need to provide PERMISSIONS. Here we have to provide permission on both side:
There are many scenarios where we want other application can read our application data but can not change it. Or sometimes we are providing them access to modify our application data. In your SCENARIO, we can provide read permission “android:readPermission” attribute in the provider so that GOOGLE CALENDAR read data from Gmail application. android:readPermission="com.android.GMAIL.calenderwithcontentpfonrovider.PERMISSION" |
|
| 10. |
I have created one background service playing music in the background. If I need to make Foreground what steps do I have to follow? |
|
Answer» Menu Item is part of the menu.xml file. When we want to ADD a menu in-out activity we need to method OnCreateOptionMenu(Menu menu). But If you want to add any Menu Item at run time then the system calls your activity’s onPrepareOptionsMenu() method. this method passes currently exist menu OBJECT to MODIFY the menu item. Please follow the below code for more DETAIL: @Override public boolean onPrepareOptionsMenu(Menu menu) { if(Build.VERSION.SDK_INT > 11) { invalidateOptionsMenu(); menu.findItem(R.id.option1).setVisible(false); menu.findItem(R.id.option2).setVisible(true); } return super.onPrepareOptionsMenu(menu); |
|
| 11. |
I have two activities: main activity as Activity A and child activity as Activity B. When I press a button Next in the ActivityA, it will call the ActivityB. Suppose I have to send data back to Activity A from Activity. How I will do that? |
|
Answer» In Android, service is a component which is like ACTIVITY and running in the background. Once it is started, it will run in the background even if the application goes background. But from Android O, they INTRODUCE a new concept that a user should know what TASK is running in the background and it also should show the notification to user with some action buttons so that the user can INTERACT with the ongoing operation if they want. So for this, we have the best approach called as an Android Foreground Service. This foreground service is giving notification to the user that task is running in the background, for example, playing music or downloading files from the internet. And if the user wants to stop that service, then he can stop using Notification. So to create foreground service you have to use NotificationManager.startServiceInForeground() method to send a notification to the user that the Background Service is running and if he wants he can stop it. |
|
| 12. |
I want to pass a String value from one Fragment to another fragment How to do this? |
|
Answer» In, we can send information from one activity to another and vice-versa using startActivityForResult() method. The android startActivityForResult method requires a result from the second activity. For that, we need to override the onActivityResult method that is invoked automatically when the second activity returns a result. public void startActivityForResult (Intent intent, int requestCode)Now we will see how to send data from Activity B back to Activity A?
In Activity B we will send someResultCode to Activity A, which will HANDLE it with the onActivityResult and send it back again with setResult(…) finish(); goBackToActivityA(){ setResult(someResultCode); finish(); }
|
|
| 13. |
What is the difference between FindViewById and Data Binding? Which one is fast in performance? |
|
Answer» If you want to send data from fragment to another Fragment we need to use an interface. Intents are only usable for sending data on an Activity level. To pass data between fragments we need to CREATE our own interfaces. Fragment 1 -> MainActivity -> FragmentInterFace-> Fragment 2 In onAttach() lifecycle method , the fragment IMPLEMENT the Interface logic and it will call Interface methods to communicate with an activity. @Override PUBLIC void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw NEW RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } }The activity that hosts fragment must implement the interface For receiving callback events from Fragment class. First host activity creates an instance of fragment using findFragmentById method then it can deliver a MESSAGE to fragment directly by calling the fragment's public methods. |
|
| 14. |
Consider a situation in which you are downloading a large file in your app and suddenly the battery goes critically low, you don’t want the download to stop abruptly and would like to show the user a notification/dialog so that he can pause the download. How you will achieve this in android application? |
|
Answer» findViewById is a method that finds the view from the layout resource file that is attached to the current Activity. This method refers to a view with REQUESTED viewId. is already created and exists. If you do not call findViewById for some view, then nothing changes. Button button1 = (Button) findViewById(R.id.button1); TextView topLeft = (TextView) findViewById(R.id.textView2);There is a disadvantage of findViewById() returns a View if it exists in the layout you provided in setContentView(), otherwise it returns NULL at runtime. There is no compile time check for this method.
Android data binding generates binding classes at compile time for layouts. <data> <variable name="user" type="com.example.databindingsample.User" /> </data>We have to add data<> tag before the UI view root within the layout tag. It will bind OBJECT . data<> element can have multiple variable<> tag within it. Those are using to describe a property that can be used within the layout. |
|
| 15. |
Is it possible to remove and add intent filters from activity based on user preference? |
|
Answer» For checking the status of BatteryLow and sending information to the user, we can create a BroadCast Receiver who will send a triggers battery LOW notification that you see on your mobile screen. A Broadcast Receiver is an Android component which ALLOWS you to register for system or application events. Once Event occur it will Broadcast message to the user. There are two steps to create a Broadcast Receiver:
|
|
| 16. |
What is the difference between these two syntaxes: android:uses-permission and uses-permission? |
|
Answer» An Intent object carries information that the Android system uses to determine which component to start. The Intent object contains information which is used either from the components that receive that intent or the Android system itself. We are defining the Intent Filter in Manifest File. We can set the type of intents to accept perform some ACTION using these elements:
|
|
| 17. |
Suppose you have wanted to share from one application to another application, how you will share that? And from another application how you will retrieve data from first application? |
|
Answer» For protecting the PRIVACY of an Android user we are using PERMISSION concept in android. When the application is trying to access user data like contact, Gallery they REQUESTING permission. Depending on the feature, the system might grant the permission automatically or might prompt the user to approve the request
|
|
| 18. |
When using setDuration() for a Toast, is it possible to set a custom length or at least something longer than Toast.LENGTH_LONG? |
|
Answer» For sharing data from ONE application to another application we are using Content Provider in android. Other application can access data from Content Provider using the provider client object. These provider client object providing an interface between application to access data and handle inter-process communication. Content Provider is saving data in the form of TABLES. These tables are having the same schema as relational database tables. To access the data from the content provider, we use the ContentResolver client object. ContentResolver PROVIDES basic methods RELATED to database storage. ContentResolver object and Content Provider objects are handling interprocess communication between application. The ContentResolver methods provide the basic create, retrieve, update, and delete functions of persistent storage. To retrieve data from a content provider, we need to follow these steps:
|
|
| 19. |
What is the use of Notification Chanel and how to create it? |
|
Answer» A toast can be displayed on the screen is defined by a flag as Duration. We can set duration SHORT or Long. The value for Short is 2.0 second and value for Long is 3.5 Second. Context context = getApplicationContext(); Toast.makeText(context, "Testing Toast Message.", Toast.LENGTH_SHORT).show();You can not directly change the duration of Toast Message which is showing in the show() method. But there is a workaround. You can use CountDownTimer Class or Handler Class to INCREASE display time of Toast. |
|
| 20. |
Tell me some advantage of LiveData. |
|
Answer» NOTIFICATION Channels. Notification Channels allow us to separate notifications into different groups/categories. BASICALLY, Notification Channel is DESIGNED for USER. They can get full control of what they want to be notified about. If they don’t want any notification they can specifically turn off notifications for a certain channel. They can also specify importance as well as the preferred sound for a particular category of notifications and determine whether or not to OVERRIDE Do not disturb The NotificationChannel constructor requires us to specify the channel_id and channel_name strings. The Importance argument is an int which specifies the level of interruption by the notification. val MessagesChannel = NotificationChannel( MESSAGES_CHANNEL_ID, context.getString(R.string_channel_name), NotificationManager.IMPORTANCE_DEFAULT) notificationManager.createNotificationChannel(privateMessagesChannel) |
|
| 21. |
What is WorkManager? How it is useful in the application? |
|
Answer» By USING LiveData, we can Observe activity lifecycle METHOD, so livedata will not trigger the change method if view is destroyed. There are many advantages of LiveData
|
|
| 22. |
Why Google is using MVVM over MVP? |
|
Answer» When you need to execute some background WORK fast and need a guarantee of that execution, create WorkerManager. Work manager APIs GO beyond the only current state of the task and allows tasks to return data in key-value format. We are using LiveData to return data and state of Work. By using WorkManager, our activity can observe livedata and it will get notified whenever the task is finished. For creating WorkManager, we need to create one subclass of the Worker class. This class has one abstract method called doWork(). As the NAME SUGGESTS, you need to perform the work you want to do in the background. This method will be called in the background/worker thread. Write a program to perform the task in this method. In return, you have to return WorkerResult. Returning WorkerResult.SUCCESS indicates that the task you PERFORMED completed successfully. Returning WorkerResult.RETRY tells WorkManager to retry the work again. Returning WorkerResult.FAILURE indicates one or more errors occurred. We can use WorkManager for:
|
|
| 23. |
Can you tell me how exactly Fused Location API works? How can I get location updates while GPS is off but the network connection is on? |
|
Answer» I would advise MVVM, it is the pattern of the future. And it is the only architecture that can give you full testing without dependencies. Once you get your head around the DATA-binding concept, it is super easy. In MVVM we are using Android Architecture Components. There LiveData and ViewModel are the main components which will help in resolving the view dependency. LiveData is an observable data holder class which is Lifecycle state of the ACTIVITY or Fragment. And ViewModel is LIKE the state representation of UI which stores and manages UI-related data in a lifecycle conscious way. It will ALSO save data when screen orientation changed. MVP is tight coupling, so there are many things that are difficult to test. |
|
| 24. |
Difference between FragmentPagerAdapter vs FragmentStatePagerAdapter? |
|
Answer» Fused location provider tries to get the best possible location which is certainly the location data from GPS. If you want location from your MOBILE network put the FOLLOWING permission in your manifest. <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>The fused location provider is one of the location APIs in Google Play services. It manages the underlying location technology and provides a simple API so that you can specify requirements at a high level, like high accuracy or low power. It also optimizes the device's use of battery power. |
|
| 25. |
If a service is implementing the method of onStartCommand(), then what are the ways a service must be stopped after the task is completed? |
|
Answer» The main difference between FragmentPagerAdapter and FragmentStatePagerAdapter is FragmentPagerAdapter stores the whole fragment in memory, and If we used a large amount of Fragment in ViewPager it will increase memory while FragmentStatePagerAdapter only stores the savedInstanceState of fragments, and destroys all the fragments when they lose focus. FragmentPagerAdapter stores the previous DATA which is fetched from the adapter while FragmentStatePagerAdapter TAKES the new value from the adapter every time it is EXECUTED. Let's take an example of Book Reader APPLICATION here. I will use FragmentStatePagerAdapter and if I am CREATING an application which will store heavy data, then I will use FragmentPagerAdapter. |
|
| 26. |
What mean by explicit & implicit Intent? |
|
Answer» Using 'stopService()' that a given application SERVICE will be STOPPED. If the service is not running, nothing HAPPENS. Otherwise, it is stopped. NOTE that calls to startService() are not counted -- this stops the service no matter how many times it was started. |
|
| 27. |
In Activity life-cycle, what is the first and last callback method will be guaranteed invoked by the system? |
Answer»
They specify which application will satisfy the intent, by supplying either the target app's package name or a fully-qualified component class name.For EXAMPLE, to start a component in your own app, because you know the class name of the activity or service you want to start. For example, you might start a new activity within your app in response to a user action, or start a service to download a FILE in the background.
They do not name a specific component, but instead declare a general action to PERFORM, which allows a component from another app to handle it. For example, if you want to show the user a location on a map, you can use an implicit intent to REQUEST that another capable app show a specified location on a map. |
|
| 28. |
I am using getLastLocation() method for getting my last Latitude and Longitude to displaying my last location on Google map. But getLastLocation() method is returning null. Can you tell me why? |
|
Answer» The first method is called 'onCreate()', which fires when the system first creates the activity. On activity CREATION, the activity enters the Created state. The LAST method is guaranteed called ‘onPause()’. The system calls this method as the first indication that the user is leaving your activity (though it does not ALWAYS MEAN the activity is being destroyed), but you should save you work/variables/state here. Other methods e.g. onStop, onDestroy may be called or not depends on the system. |
|
| 29. |
Can you please explain in detail what difference between Async Task and Intent Service. Also explain the situation where we have to use Async Task and where have to use Intent Service. |
|
Answer» When we will try to display our CURRENT location in google map android is giving us one api to use the name as google map api. For displaying the last location we need to override one method name as getLastLocation(). The getLastLocation() method returns a task that we can use to GET a Location object with the latitude and longitude coordinates of a geographic location. Sometimes it happens when the location object may be null. There are below situations when we will get null from getLastLocation() method:
|
|
| 30. |
Design one Spinier control for displaying list of Country and add another spinner for displaying State based on Country Selection. |
|
Answer» In Android when we have to perform the long-running operation we can create Async Task to INTENT Service. In AsyncTask, it will create one background thread where the long-running operation will execute and after task result will update in Main Thread. In Intent Service we can also do the operation but it is running in the background and it will not update UI in Main Thread. if you want to DOWNLOAD and cache maps, you may want to call an IntentService so the user doesn't have to be looking at the app for it to download. Likewise, if you're sending data to your server, an IntentService is extremely HELPFUL in this regard because you can start and forget. As a conclusion, we can say AsyncTask is meant for short tasks that have to COMMUNICATE with the main thread. IntentService is meant for long tasks that don't have to communicate with the main thread. |
|
| 31. |
Use the same scenario of “Contact Us“screen and one more functionality therefor make a call. Can you please write code to make a call for a specific mobile number. |
|
Answer» We need to create two Spinner control for our activity name as State and COUNTRY. This spinner control will display from the ADAPTER. State spinner adapter CHANGES depending on County spinner adapter. I have written below code to displaying data in Adapter . Please find below step for displaying spinner control:
|
|
| 32. |
Suppose we have to design an activity name as Contact Us. Where you have to provide an option to send an email. Can you please write the code in android to send an email to any specific email address? |
|
Answer» In “ContactUs” Activity I will add ONE more button for send SMS. When user will click on this button it will call Implicit INTENT with Action_View. But for SENDING SMS we NEED to add permission in our manifest.xml file. I have written below code for sending SMS in number “111-1111-111”. Uri smsUri = Uri.parse("tel:111-1111-111"); Intent intent = new Intent(Intent.ACTION_VIEW, smsUri); intent.putExtra("sms_body", "sms TEXT"); intent.setType("vnd.android-dir/mms-sms"); startActivity(intent); |
|
| 33. |
In Oreo how you will create one Notification for receiving new message and also explain how we can add action in Notification? |
|
Answer» In “Contact Us” ACTIVITY I will create ONE button name as “Send Email”. Once the user clicks on this button it calls Implicit Intent with Action_Send and we will try to send an email with a SPECIFIC address. Please find my below CODE for SENDING an email to a user with an email address” test123@example.com”. String[] TO = { "test123@example.com " }; Intent emailIntent = new Intent(Intent.ACTION_SEND); emailIntent.setData(Uri.parse("mailto:")); emailIntent.setType("text/plain"); emailIntent.putExtra(Intent.EXTRA_EMAIL, TO); emailIntent.putExtra(Intent.EXTRA_CC, CC); emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Your subject"); emailIntent.putExtra(Intent.EXTRA_TEXT, "Email message goes here"); try { startActivity(Intent.createChooser(emailIntent, "Send mail...")); finish(); Log.i("Finished sending email...", ""); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(ContactUs.this, "There is no email client installed.", Toast.LENGTH_SHORT).show(); |
|
| 34. |
How I will display popup message to a user with toast or SnakeBar. Explain with code. |
|
Answer» Notification is kind of short message that is used to post from an application for giving information that some event has been HAPPENING if the application is still not running in the background. From the Oreo, a new concept has come NAME as Notification Chanel. This is using for GROUPING notification based on behavior. So before creating any notification we need to create Notification Chanel at the application level and need to provide its id in Manifest file. For creating any notification we need to create an object of NotificationCompact.Builder. We can define all the components of Notification like title, IMAGE,duration etc by calling setters on the builder object. We can note that we pass a string as parameter to the NotificationCompact.Builder constructor, this string is the Notification Channel ID which means that this notification will now be a part of that particular channel. ublic static final String NOTIFICATION_CHANNEL_ID = "channel_id"; //Notification Channel ID passed as a parameter here will be ignored for all the Android versions below 8.0 NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID); builder.setContentTitle("New message "); builder.setContentText("You have new message "); builder.setSmallIcon(R.drawable.icon); builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.icon)); Notification notification = builder.build();At last we need to call NotificationManager object.and we will display our notification using notify() method. NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this); notificationManagerCompat.notify(NOTIFICATION_ID, notification);For adding action in Notification we need to specify action. When user click on notification it will open an activity in your app that corresponds to the notification. To do so, we will specify a content intent defined with a PendingIntent object and pass it to setContentIntent(). Intent intent = new Intent(this, MessageDetail.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0); NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setContentTitle("New Message") .setContentText("Message come") .SETPRIORITY(NotificationCompat.PRIORITY_DEFAULT) .setContentIntent(pendingIntent) .setAutoCancel(true); |
|
| 35. |
I have one Text sending application. I need to display a popup message to a user when the text will send to other contacts with a message” Text Send Want to do UN Do” and button one “ Undo”. |
|
Answer» When we need to display simple popup message to the USER without interaction then we are creating Toast Message. But you want to display some popup message with Action then we need to create SnackBars. In our scenario we will create a SnakBars with one button “UnDo” and it will display a message to the user “Text has been send, do you want to undo?”. Please follow the below code for more detail: Snackbar.make(getCurrentFocus(), "Message has been sent, Do you want to undo?", Snackbar.LENGTH_SHORT) .setAction("Undo", new View.OnClickListener() { @Override public VOID onClick(View view) { //RETURN his picture } }) .SHOW(); |
|
| 36. |
I want to build one feature in my app where a user performs a long press on a contact it will show option like make Call and send SMS. How we can do that. |
|
Answer» In android application when user long press on any content it will SHOW an option to PERFORM ACTION this can be done using Context Menu. In your scenario, if user long presses on any contact we can show him a context menu with two options “MakeCall” and “Send SMS”. Please find below code for check how to implement a Context menu in our application: For adding context menu in our application we NEED register View who is going to display data at a long press on it. We will create registerForContextMenu(View) for register view in our ACTIVITY and we need to override onCreateContextMenu() in our activity for displaying option to a user when the view has been long press by the user. In our scenario, Listview is having a list of contact so we will register Listview here. When user long press on any contact it call onCreateContaxtMenu method and show option like MakeCall and SendSMS. Please find below code for more detail: Listview listview = (ListView) findViewById(R.id.listShow); registerForContextMenu(listview); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.setHeaderTitle("Context Menu"); menu.add(0, v.getId(), 0, "Make Call"); menu.add(0, v.getId(), 0, "Send SMS"); |
|
| 37. |
I have to build one Alert Dialog box for my app. Write the step to show Alert Dialogue box and why we are using it. |
|
Answer» In Android application when we need to display a message to the user with to warn him with a button like “Ok” and “Cancel” we are using Alert Dialog Box. Android Alert Dialog is built with the use of THREE FIELDS: Title, Message AREA, Action Button. The code for creating an Alert Dialogue box is mention below: AlertDialog.Builder alertDialogBuilder = NEW AlertDialog.Builder(context); // set title alertDialogBuilder.setTitle(" Are you Sure"); // set dialog message alertDialogBuilder .setMessage("Click yes to exit!") .setCancelable(false) .setPositiveButton("Yes",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int ID) { // if this button is clicked, close // current activity MainActivity.this.finish(); } }) .setNegativeButton("No",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { // if this button is clicked, just close // the dialog box and do nothing dialog.cancel(); } });// create alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); |
|
| 38. |
Suppose you are designing activity and you need to set some background image on that screen. How you will make sure this image will look the same in all the screen size of the phone. What kind of image you will use to set background. |
Answer»
|
|
| 39. |
Suppose you need to create an App name as ” MyGalryApp”. Here you have an activity name as “Home Activity” where you have one button to take a Picture. If you click on that button it will open Camera to click Picture. Once you click the Picture it should display in Imageview. What code you will write for this problem? |
|
Answer» We will write below to do display an image in imageview after clicked by Camera
|
|
| 40. |
I want to store some text value like UserName and need to retrieve and edit it. How can I use SharedPreferences to do this? |
|
Answer» In Android, we have many ways to store user data. SharedPreference is a CLASS that allows us to save and retrieve user data in the form of Key and Values. If you kill your application still data will be saved in the shared preference. It will store data in an XML file. For using shared preference we need to create an INSTANCE of the getSharedPreferences method. This method is taking two parameters: For WRITING data in the sharedpreferences file we need to follow below steps:
To read values use such methods as getString() and getInt() of SharedPreferences instance. SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); String restoredText = prefs.getString("text", null); if (restoredText != null) { String name = prefs.getString("name", "No name defined");//"No name defined" is the default value. } |
|
| 41. |
Implement an AsyncTask that repeats itself after a given interval? |
|
Answer» For creating AsyncTask with a specific interval, we can USE a Handler. A Handler is a safe option because we don't need an extra THREAD to keep tracking when firing the event. When we LAUNCH any android application it will create a thread which called the Main thread, this thread is handling all the UI event handling so it is also called as UI Thread. A Handler is also a Thread which is running on Main Thread. A Handler allows you to send and PROCESS Message and Runnable objects associated with a thread's MessageQueue. A Handler can be used to schedule messages or runnable to executed at some point in the future. You can send a message using Handler // Create the Handler object (on the main thread by default) Handler handler = new Handler(); // Define the code block to be executed private Runnable runnableCode = new Runnable() { @Override public void run() { // Do SOMETHING here on the main thread Log.d("Handlers", "Called on main thread"); } }; // Run the above code block on the main thread after 2 seconds handler.postDelayed(runnableCode, 2000); |
|
| 42. |
Implement an EditText that clears itself when the enter key is pressed |
|
Answer» You can do it by setting an OnKeyListener on your EditText. This is only useful for hardware keyboards. A software INPUT method has no obligation to trigger this listener. Please find below code for more clarification: Here I am overriding onKey Method which will return a false value if press KEY is not “Enter” Else it will clear text of EDIT text as empty. @Override public boolean onKey(View V, int keyCode, KeyEvent event) { if (keyCode == 66) { editText.setText(""); } return false; } |
|
| 43. |
If you rotate your phone how it will save data in the background. Which lifecycle methods will call? |
|
Answer» Having rotated the device, the following state change sequence should appear Clearly this has RESULTED in the activity being destroyed and re-created. To save the state information override onSaveInstanceState() method and add key-value pairs to the BUNDLE OBJECT. It will save data in the EVENT that your activity is destroyed unexpectedly. This method gets called before onStop(). To get saved from an activity state, we are using method onRestoreInstanceState. The first step in extending the StateChange application is to make sure that the text entered by the user is extracted from the EditText component within the onSaveInstanceState() method of the StateChangeActivity activity and then saved as a key-value pair into the Bundle object. Alternately, use the onRestoreInstanceState( ) method to EXTRACT saved state from the Bundle and restore it into new instances of the activity. The onRestoreInstanceState( ) method is another callback lifecycle method that is also rarely seen in the activity lifecycle diagrams. The onRestoreInstanceState( ) method is automatically invoked by Android between the onStart( ) and the onResume( ) lifecycle methods. |
|
| 44. |
What is RecyclerView how its different from ListView? |
|
Answer» The Recycler view is the most advanced component of Android. We can also say that RecyclerView is the most advanced FORM of ListView. Recycler view is containing new feature like ViewModel, Adapter, LayoutManager, SoothScroller. There are many differences many difference between listview and RecyclerView. In ListView we cannot do HORIZONTAL scrolling while in RecyclerView we have both OPTION Horizontal and Vertical Scrolling. In RecyclerView class, it is using a ViewHolder OBJECT which is used by the adapter to bind ViewHolder with a position while in ListView we are not using ViewHolder. In ListView, if the data set is changed you have to call the notifyDataSetChanged method of the underlying adapter to refresh data. While in a RecyclerView adapter, if a single item or a range of items have changed, there are methods to NOTIFY the change accordingly like notifyItemChanged and notifyItemRangeChanged. |
|
| 45. |
What is View Group? How are they different from Views |
|
Answer» View is a BASIC building block of UI (User Interface) in android. A view is a small rectangular box which responds to user inputs. For example, a Text View is used to display some text to the user that is a subclass of View. In Android, we are using many View subclass like EditText, Button, CheckBox, Radio Button, ImageView, DatePicker etc. ViewGroup is an invisible container of other child view. ViewGroup is a special kind of view which is extended from View as its base CLASS. ViewGroup is the base class for LAYOUTS. Viewgroups can contain other views in it. For example LinearLayout, it is a group of many views those are arranging in LINEAR or Veridical way. In Android, we have other layouts as well like Relative Layout, Table Layout, Frame Layout etc. |
|
| 46. |
What is Sticky Intent? |
|
Answer» In Android Sticky Intent is a type of Intent who will COMMUNICATE between Service and Function. Sticky Intent is using with Sticky Broadcast that’s why they are CALLING as StickyIntent. In simple language, we can say that StickyIntent is stick with till Broadcast is not completed its job this intent will be present and return data of registerReceiver() method and will be re-delivered or re-broadcasted to the future requests from any broadcast receivers. We have one more advantage of Sticky Intent that Sticky Broadcast will replace the previous instance of the sticky broadcast and save your application from memory leak. For example, if we need to SEND a notification for Low status of Battery, we will create a sticky broadcast sent via the operating system is ACTION_BATTERY_CHANGED. As soon broadcast that action we will get the Intent with data. For this first, we need to add special permission in the manifest file that allows an application to broadcast sticky intents. <uses-permission android:NAME="android.permission.BROADCAST_STICKY"/>Here's an example of how we can use a sticky broadcast for : Intent intent = new Intent("action. ACTION_BATTERY_CHANGED"); intent.putExtra("status ", true); sendStickyBroadcast(intent); |
|
| 47. |
Difference between Background Service & Intent Service? |
|
Answer» In Android Service is something that is running in the background. In a simple way, we can say that a background service is same as an Activity. The only difference is it doesn’t have UI. A background Service can be started by calling the startService method in your Activity. we need to create an explicit Intent, which means that you either make a reference to the Service’s class, or you include the package name of your APP in the Intent. For example: Intent intent = new Intent(mContext, MyService.class); startService(intent);There is one drawback with Service is that it is running on Main Thread so you can not ASSIGN any long running operation to service. But if you want to run some long running operation in the background, you should use IntentService. IntentService is CREATING its own Worker Thread which is running separately from the Main Thread. EXAMPLES for its usage would be to download certain resources from the Internet. For creating Intent Service you need to create a service class by extending IntentService and implementing onHandleIntent() method. public class TestIntentService extends IntentService{ @Override protected void onHandleIntent(Intent intent) { }In Intent Service we can start service by calling startService method passing intent which identifies the service. We can call startService any number of times, but in the background it will create only one instance of intent service and all requests are queued and processed in separate work thread. We don’t need to worry about calling stopService, as IntentService stops itself when there are no requests to serve. |
|
| 48. |
What is the difference between Bound Service and Intent Service |
|
Answer» There are many differences between IntentService and Bound Service:
|
|
| 49. |
Suppose there are two activities in a single android application with launch modes as 'singleInstance'. Assume an example below.I am navigating from activity A -> B(launchMode="singleInstance"). Now from activity B -> C. Finally, I navigate from activity C -> D(launchMode="singleInstance").Now we know the instance of activity B will be created in a different task, and A & C will be in different tasks.Now, my question is, in which task instance of activity D would be placed. Will it be with activity B, or some other task would be created for activity D? |
|
Answer» Launch mode is an instruction for ANDROID OS which specifies how the activity should be launched. It instructs how any new activity should be associated with the current task. So in your scenario When using launchMode="singleInstance", there are two THINGS that we need to remember:
As such, an Activity with launchMode of singleInstance will always be isolated in its own task. There won't be another Activity inside of that task. So with your example from your question of Activities A, B, C, and D:
From what happened here, you have one a task that stores the launchMode="standard" Activity A and Activity C. Activity B is in its own task. Activity D is in its own task. Therefore, if you choose to Back out of these Activities, you'll notice that:
Also, Activity D definitely won't be in the same task as Activity B because Activity B's task is meant only for Activity B due to launchMode="singleInstance". |
|
| 50. |
In Android application how you will transfer Object like complex POJO code from one Activity to another? Hint: What is the difference between Serializable and Parcelable? |
|
Answer» When you need to send Object from one activity to another activity, we are using TWO techniques: 1. Serialization and 2. Parcelable. In other case passing data from one activity to another activity, we are using Intent. Parcelable is a FASTER approach compared to Serialization because it is using Android SDK. There are some reasons also:
|
|