Accreditation Bodies
Accreditation Bodies
Accreditation Bodies
Supercharge your career with our Multi-Cloud Engineer Bootcamp
KNOW MOREMost mobile devices today rely on Android, an open-source Linux-based OS. The Android development process involves developing applications for these Android-based devices. As a result, the demand for Android developers has been at an all-time high. We have compiled a list of commonly asked Android interview questions, and this article is aimed at helping freshers, intermediate and expert Android developers about to appear for interviews. These top Android interview questions with answers are prepared by Android experts and cover various topics like MVVM, ART, onstraintLayout, fragment, and activity and help you understand the different purposes of AndroidManifest.xml file, to name a few. With these top Android interview questions, you can be confident that you will be well-prepared for your next interview. So, if you are looking to advance your career in App development, this guide is the perfect resource for you.
Filter By
Clear all
There is no direct way to terminate a thread but using the two following ways it can be done.
MVVM stands for Model-View-ViewModel. Android applications built using MVVM are more robust, fast, scalable and very less prone to memory leaks. In MVVM ViewModel is the key between View and Model.
The important key point about MVVM is that View has reference to the ViewModel but not in reverse and that makes the application’s UI-Components related memory leak-proof. Each View may have a dedicated ViewModel or may be shared by multiple in case of fragments to enable sharing data cross fragments of an activity. MVVM is a more suitable candidate for automated testing.
It stands for Android Run Time. ART is used for running Android applications. It uses AOT (Ahead Of Time) compilation on the device. When an APK is getting installed on the Android device, the .dex files from the APK file will be converted to processor’s native instructions set/machine code (.art extension) and that will be stored in the app’s runtime cache directory on the device’s internal storage. This will make installation little bit longer and take more space on the device storage but it makes apps run much faster, less battery consumption, robots application debugging support and better user experience.
The recommended way going forward is using WorkManager APIs, that makes it easy to specify deferrable, asynchronous tasks and when they should run under the circumstances you choose, or recurring tasks that run at a specified interval. Internally WorkManager might use JobScheduler, Firebase-JobDispatcher, Executor, and AlarmManager for running the task.
Android is a ‘Linux based software stack’ created for a wide array of devices and form factors. It is open source. It has layers of major components from bottom to top as follows…
It is the foundation for any Android application. It will be in app module’s src/main/ directory for Android Studio projects. This file contains information of application package, including components of the application such as activities, services, broadcast receivers, content providers etc. It performs some other tasks also: It is responsible to protect the application to access any protected parts by provision of permissions.
In Android, UI is representing as an Activity. Single Screen in an application represents as Activity while Fragments are reusable UI with business logic. Activity is a collection of Screen. In android application, Fragments are using in Navigation Drawer in our entire screen. You can also use fragment to display Google Map on screen.
Following are important points about a fragment:
Android OS provides back stack function for Activity, it also provides back stack function for Fragment. If you add one Fragment into the back stack, when you press the android device back menu, you can find the Fragment that is saved in back stack popup. Until all saved Fragments in back stack popup, then the activity will exit.
We have to create “FragmentTransaction” objects on the back stack and when the user presses the Back button, the “FragmentManager” pops the most recent transaction off the back stack and performs the reverse action.
As mentioned in below code:
getSupportFragmentManager().beginTransaction() .add(detailFragment, "detail") // Add this transaction to the back stack .addToBackStack(null) .commit();
In Android when we want to share data between two applications we are using Content Provider. It has a complete mechanism to share data between applications. It will also provide security while sharing data from one application to another application. For getting data from any Content Provider you need to create Content Resolver. For Creating Content Resolver, you need to call Activity’s getContentResolver method.
For Modifying data from Content Provider, you can invoke the basic method of Content Resolver like insert, delete, update and query. These operations are the same as the SQLite DB Operation.
Android we have two steps for retrieving data from a Content Provider:
For this, we can modify our build Gradle file of the application. In Gradle file we will add code for adding build type and build flavour like below:
buildTypes { debug { applicationIdSuffix '.debug' versionNameSuffix '-DEBUG' resValue "string", "app_name", "AppName debug" } release { minifyEnabled true shrinkResources true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' signingConfig signingConfigs.release zipAlignEnabled true resValue "string", "app_name", "AppName" } }
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:
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".
There are many differences between IntentService and Bound Service:
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.
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);
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.
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.
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.
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; }
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);
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:
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit(); editor.putString("name", "ABC"); editor.commit();
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. }
We will write below to do display an image in imageview after clicked by Camera
<uses-permission android:name="android.permission.CAMERA" />
intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent, 1);
H if (requestCode == 1 && resultCode == RESULT_OK) { Bitmap bitmap = (Bitmap) data.getExtras().get("data"); imageView.setImageBitmap(bitmap);
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();
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");
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();
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);
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();
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);
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:
<string-array name="country_array"> <item>India</item> <item>Pakisthan</item> <item>Sri Lanka</item> </string-array> <string-array name="state_india"> <item>Maharasta</item> <item>TamilNadu</item> <item>Delhi</item> <item>Madhya Pradesh</item> </string-array>
SpinnerCountry = (Spinner) findViewById(R.id.spinnerCountry); spinnerState = (Spinner) findViewById(R.id.spinnerState); spinnerCountry.setOnItemSelectedListener(this); @Override public void onItemSelected(AdapterView<?> parent, View arg1, int pos, long arg3) { parent.getItemAtPosition(pos); if (pos == 0) { ArrayAdapter<CharSequence> adapter = ArrayAdapter .createFromResource(this, R.array.state_india, android.R.layout.simple_spinner_item); spinnerCity.setAdapter(adapter); } else if (pos == 1) { ArrayAdapter<CharSequence> adapter = ArrayAdapter .createFromResource(this, R.array.state_pakisthan, android.R.layout.simple_spinner_item); spinnerCity.setAdapter(adapter); } else if (pos == 2) { ArrayAdapter<CharSequence> adapter = ArrayAdapter .createFromResource(this, R.array.state_srilanka, android.R.layout.simple_spinner_item); spinnerCity.setAdapter(adapter);
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.
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:
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.
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.
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.
Using 'stopSelf()' is same as 'stopService()' but used within the service to indicate system to stop itself.
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.
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.
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.
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:
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
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)
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.
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:
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
<uses-permission android:name="string" android:maxSdkVersion="integer" />
<permission android:name="com.me.app.myapp.permission.DEADLY_ACTIVITY" android:label="@string/permlab_deadlyActivity" android:description="@string/permdesc_deadlyActivity" android:permissionGroup="android.permission-group.COST_MONEY" android:protectionLevel="dangerous" />
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:
<intent-filter> <action android:name="android.intent.action.SEND" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="text/plain" /> </intent-filter>
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:
<receiver android:name=".SampleBroadcastReceiver"> <intent-filter> <action android:name=" android.intent.action.BATTERY_LOW "/> </intent-filter> </receiver>
Intent intent = new Intent(this, Reciver.class); sendBroadcast(intent);
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.
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.
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?
intentActivityD = new Intent(…); intentActivityD; startActivityForResult(intentActivityD, SOME_REQUEST_CODE)
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(); }
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { // check if the requestCode is the wanted one and if the result is what we are expecting if (requestCode == REQUEST_FORM && resultCode == RESULT_OK) { val name = data?.getStringExtra(FormActivity.INPUT_NAME) addItemToList(name) // do something with the value } }
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.
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);
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"
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>
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_ACCOUNTS
The 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);
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.
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>
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());
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);
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);
There is no direct way to terminate a thread but using the two following ways it can be done.
MVVM stands for Model-View-ViewModel. Android applications built using MVVM are more robust, fast, scalable and very less prone to memory leaks. In MVVM ViewModel is the key between View and Model.
The important key point about MVVM is that View has reference to the ViewModel but not in reverse and that makes the application’s UI-Components related memory leak-proof. Each View may have a dedicated ViewModel or may be shared by multiple in case of fragments to enable sharing data cross fragments of an activity. MVVM is a more suitable candidate for automated testing.
It stands for Android Run Time. ART is used for running Android applications. It uses AOT (Ahead Of Time) compilation on the device. When an APK is getting installed on the Android device, the .dex files from the APK file will be converted to processor’s native instructions set/machine code (.art extension) and that will be stored in the app’s runtime cache directory on the device’s internal storage. This will make installation little bit longer and take more space on the device storage but it makes apps run much faster, less battery consumption, robots application debugging support and better user experience.
The recommended way going forward is using WorkManager APIs, that makes it easy to specify deferrable, asynchronous tasks and when they should run under the circumstances you choose, or recurring tasks that run at a specified interval. Internally WorkManager might use JobScheduler, Firebase-JobDispatcher, Executor, and AlarmManager for running the task.
Android is a ‘Linux based software stack’ created for a wide array of devices and form factors. It is open source. It has layers of major components from bottom to top as follows…
It is the foundation for any Android application. It will be in app module’s src/main/ directory for Android Studio projects. This file contains information of application package, including components of the application such as activities, services, broadcast receivers, content providers etc. It performs some other tasks also: It is responsible to protect the application to access any protected parts by provision of permissions.
In Android, UI is representing as an Activity. Single Screen in an application represents as Activity while Fragments are reusable UI with business logic. Activity is a collection of Screen. In android application, Fragments are using in Navigation Drawer in our entire screen. You can also use fragment to display Google Map on screen.
Following are important points about a fragment:
Android OS provides back stack function for Activity, it also provides back stack function for Fragment. If you add one Fragment into the back stack, when you press the android device back menu, you can find the Fragment that is saved in back stack popup. Until all saved Fragments in back stack popup, then the activity will exit.
We have to create “FragmentTransaction” objects on the back stack and when the user presses the Back button, the “FragmentManager” pops the most recent transaction off the back stack and performs the reverse action.
As mentioned in below code:
getSupportFragmentManager().beginTransaction() .add(detailFragment, "detail") // Add this transaction to the back stack .addToBackStack(null) .commit();
In Android when we want to share data between two applications we are using Content Provider. It has a complete mechanism to share data between applications. It will also provide security while sharing data from one application to another application. For getting data from any Content Provider you need to create Content Resolver. For Creating Content Resolver, you need to call Activity’s getContentResolver method.
For Modifying data from Content Provider, you can invoke the basic method of Content Resolver like insert, delete, update and query. These operations are the same as the SQLite DB Operation.
Android we have two steps for retrieving data from a Content Provider:
For this, we can modify our build Gradle file of the application. In Gradle file we will add code for adding build type and build flavour like below:
buildTypes { debug { applicationIdSuffix '.debug' versionNameSuffix '-DEBUG' resValue "string", "app_name", "AppName debug" } release { minifyEnabled true shrinkResources true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' signingConfig signingConfigs.release zipAlignEnabled true resValue "string", "app_name", "AppName" } }
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:
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".
There are many differences between IntentService and Bound Service:
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.
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);
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.
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.
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.
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; }
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);
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:
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit(); editor.putString("name", "ABC"); editor.commit();
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. }
We will write below to do display an image in imageview after clicked by Camera
<uses-permission android:name="android.permission.CAMERA" />
intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent, 1);
H if (requestCode == 1 && resultCode == RESULT_OK) { Bitmap bitmap = (Bitmap) data.getExtras().get("data"); imageView.setImageBitmap(bitmap);
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();
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");
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();
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);
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();
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);
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:
<string-array name="country_array"> <item>India</item> <item>Pakisthan</item> <item>Sri Lanka</item> </string-array> <string-array name="state_india"> <item>Maharasta</item> <item>TamilNadu</item> <item>Delhi</item> <item>Madhya Pradesh</item> </string-array>
SpinnerCountry = (Spinner) findViewById(R.id.spinnerCountry); spinnerState = (Spinner) findViewById(R.id.spinnerState); spinnerCountry.setOnItemSelectedListener(this); @Override public void onItemSelected(AdapterView<?> parent, View arg1, int pos, long arg3) { parent.getItemAtPosition(pos); if (pos == 0) { ArrayAdapter<CharSequence> adapter = ArrayAdapter .createFromResource(this, R.array.state_india, android.R.layout.simple_spinner_item); spinnerCity.setAdapter(adapter); } else if (pos == 1) { ArrayAdapter<CharSequence> adapter = ArrayAdapter .createFromResource(this, R.array.state_pakisthan, android.R.layout.simple_spinner_item); spinnerCity.setAdapter(adapter); } else if (pos == 2) { ArrayAdapter<CharSequence> adapter = ArrayAdapter .createFromResource(this, R.array.state_srilanka, android.R.layout.simple_spinner_item); spinnerCity.setAdapter(adapter);
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.
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:
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.
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.
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.
Using 'stopSelf()' is same as 'stopService()' but used within the service to indicate system to stop itself.
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.
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.
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.
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:
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
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)
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.
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:
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
<uses-permission android:name="string" android:maxSdkVersion="integer" />
<permission android:name="com.me.app.myapp.permission.DEADLY_ACTIVITY" android:label="@string/permlab_deadlyActivity" android:description="@string/permdesc_deadlyActivity" android:permissionGroup="android.permission-group.COST_MONEY" android:protectionLevel="dangerous" />
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:
<intent-filter> <action android:name="android.intent.action.SEND" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="text/plain" /> </intent-filter>
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:
<receiver android:name=".SampleBroadcastReceiver"> <intent-filter> <action android:name=" android.intent.action.BATTERY_LOW "/> </intent-filter> </receiver>
Intent intent = new Intent(this, Reciver.class); sendBroadcast(intent);
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.
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.
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?
intentActivityD = new Intent(…); intentActivityD; startActivityForResult(intentActivityD, SOME_REQUEST_CODE)
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(); }
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { // check if the requestCode is the wanted one and if the result is what we are expecting if (requestCode == REQUEST_FORM && resultCode == RESULT_OK) { val name = data?.getStringExtra(FormActivity.INPUT_NAME) addItemToList(name) // do something with the value } }
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.
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);
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"
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>
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_ACCOUNTS
The 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);
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.
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>
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());
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);
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);
Android is a software package and Linux based OS for mobile devices such as computers, tablets, and smartphones. Is developed by Google and later the OHA (Open Handset Alliance). The goal of the Android project is to create a successful real-world product that improves the mobile experience for end users. For today there are many codes names of Android such a Lollipop, KitKat, Jelly Bean, etc.
Today Android become the indisputable leader of the global smartphone market share. This is mainly due to an increase in the use of smartphones in Countries like India, USA, Brazil, China and many more. One of the important features of Android is the integration of Google products and services.
It’s the best time for you to launch a career in Android development. There’s a healthy supply of jobs, demand for Android apps. The expansion is increasing the demand for mobile application developers, currently, have lots of opportunities for employment. 2018 has been a game the dynamic year for the smartphone market.
So, if you are planning to start your career in Android development then you need to be well prepared with all the possible Android interview questions which could be asked in an Android interview. There are several complicated Android developer interview questions you might come across in the Android interview. This article will equip you to deal with Android interview questions asked in Android developer interviews.
Submitted questions and answers are subjecct to review and editing,and may or may not be selected for posting, at the sole discretion of Knowledgehut.
Get a 1:1 Mentorship call with our Career Advisor
By tapping submit, you agree to KnowledgeHut Privacy Policy and Terms & Conditions