NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

Android Development with Kotlin
- Layouts
- Activity Lifecycle
- UI Testing
- Fragments
- Notification
- Shared Preferences


Android Layouts
What is a layout in Android?
Layouts are the User Interfaces (UI), which is a presentation or view layer of your application where user can interact with your application to perform some actions.
All elements in the layout are built using a hierarchy of View and ViewGroup objects.
A View usually draws something the user can see and interact with. Whereas a ViewGroup is an invisible container that defines the layout structure for View and other ViewGroup objects

Resource files
Resource files are a way of separating static values from code so that you don't have to change the code itself to change the values. You can store all the strings, layouts, dimensions, colors, styles, and menu text separately in resource files.
Resource files are stored in folders located in the
res folder when viewing the Project > Android pane.

Resources folder names
Resource files are stored in folders located in the res folder when viewing the Project > Android pane. These folders include:
● drawable: For images and icons
● layout: For layout resource files
● menu: For menu items
● mipmap: For pre-calculated, optimized collections of app icons used by the Launcher
● values: For colors, dimensions, strings, and styles (theme attributes)

AndroidX vs Support Library
AndroidX simply maps the original Support Library API packages into the androidx.* namespace, AndroidX which is a succeedor of Support Library.
Only the package and Maven artifact names changed. Classes, methods, and field names did not change. This is finally a huge step to clean and order the confusing mess of old artifacts and package names.
Androidx feature:
● Material Design components compatible with older Android versions
● Android KTX (set of Kotlin extensions)
● Smaller, specified packages
● Architecture Components & Support Library together under androidx.* packages
Note: However, keep in mind that Support Libraries will no longer be updated by Google.

Material Design
● Contrast
● Opacity
● Typography
● Typeface
● Font styles
● Downloadable fonts
● Floating action buttons
● Navigation drawers
● Snackbars
● Tabs
● Cards
● Lists
● Motion
● Animations
● Circular reveal
● Activity transitions
● Curved motion

Activity
An activity represents a single screen in your app with an interface the user can interact with.
Although the activities in your app work with each other to form a cohesive user experience, each activity is independent of the others. This enables your app to start an activity in another app, and it enables other apps to start activities in your app.
Each Activity in your app has Activity Lifecycle, when the activity is first created, when it's stopped or resumed, and when the system destroys it.
Each has its own UI layout xml file and declaration in AndroidManifest.xml

Intents
Each activity is started or activated with an Intent, which is a message object that makes a request to the Android runtime to start an activity or other app component in your app or in some other app.
To start Activity you build your own intent and call the startActivity() method to send the intent.
An intent can also be used to pass data between one activity and another.

Intent types
Intents can be explicit or implicit:
● Explicit intent: You specify the receiving activity (or other component) using the activity's fully qualified class name. You use explicit intents to start components in your own app (for example, to move between screens in the UI), because you already know the package and class name of that component.
● Implicit intent: You do not specify a specific activity or other component to receive the intent. Instead, you declare a general action to perform, and the Android system matches your request to an activity or other component that can handle the requested action.

Intent objects and fields
For an explicit Intent, the key fields include the following:
● The Activity class (for an explicit Intent). This is the class name of the Activity or other component that should receive the Intent; for example, com.example.SampleActivity.class. Use the Intent constructor or the setComponent(), setComponentName(), or setClassName() methods to specify the class.
● The Intent data. The Intent data field contains a reference to the data you want the receiving Activity to operate on as a Uri object.
● Intent extras. These are key-value pairs that carry information the receiving Activity requires to accomplish the requested action.
● Intent flags. These are additional bits of metadata, defined by the Intent class. The flags may instruct the Android system how to launch an Activity or how to treat it after it's launched.

When to use Intent data or Intent extras
You can use either Intent data or Intent extras to pass data from one Activity to another.
The Intent data can hold only one piece of information: a URI representing the location of the data you want to operate on. That URI could be a web page URL (http://), a telephone number (tel://), a geographic location (geo://) or any other custom URI you define.
Use the Intent data field:
● When you only have one piece of information you need to send to the started Activity.
● When that information is a data location that can be represented by a URI.
Intent extras are for any other arbitrary data you want to pass to the started Activity. Intent extras are stored in a Bundle object as key and value pairs.
Use the Intent extras:
● If you want to pass more than one piece of information to the started Activity.
● If any of the information you want to pass is not expressible by a URI.

Explicit Intent - actions, categories, and data=
● The Intent action, which is the generic action the receiving Activity should perform. The available Intent actions are defined as constants in the Intent class and begin with the word ACTION_. A common Intent action is ACTION_VIEW, which you use when you have some information that an Activity can show to the user, such as a photo to view in a gallery app, or an address to view in a map app. You can specify the action for an Intent in the Intent constructor, or with the setAction() method.
● An Intent category, which provides additional information about the category of component that should handle the Intent. Intent categories are optional, and you can add more than one category to an Intent. Intent categories are also defined as constants in the Intent class and begin with the word CATEGORY_. You can add categories to the Intent with the addCategory() method.
● The data type, which indicates the MIME type of data the Activity should operate on. Usually, the data type is inferred from the URI in the Intent data field, but you can also explicitly define the data type with the setType() method.


Sending an implicit Intent
When you create an implicit Intent object, you:
● Do not specify the specific Activity or other component to launch.
● Add an Intent action or Intent categories (or both).
● Resolve the Intent with the system before calling startActivity() or startActivityforResult().
● Show an app chooser for the request (optional).

Intent filters
An Intent filter may contain the following elements, which correspond to the fields in the Intent object described above:
● <action>: The Intent action that the activity accepts.
● <data>: The type of data accepted, including the MIME type or other attributes of the data URI (such as scheme, host, port, and path).
● <category>: The Intent category.

Actions
An Intent filter can declare zero or more <action> elements for the Intent action. The action is defined in the name attribute, and consists of the string "android.intent.action." plus the name of the Intent action, minus the ACTION_ prefix. So, for example, an implicit Intent with the action ACTION_VIEW matches an Intent filter whose action is android.intent.action.VIEW.
For example, this Intent filter matches either ACTION_EDIT and ACTION_VIEW:

Categories
An Intent filter can declare zero or more <category> elements for Intent categories. The category is defined in the name attribute, and consists of the string "android.intent.category." plus the name of the Intent category, minus the CATEGORY prefix.
For example, this Intent filter matches either CATEGORY_DEFAULT and CATEGORY_BROWSABLE:

Data
An Intent filter can declare zero or more <data> elements for the URI contained in the Intent data. As the Intent data consists of a URI and (optionally) a MIME type, you can create an Intent filter for various aspects of that data, including:
● URI Scheme
● URI Host
● URI Path
● Mime type
For example, this Intent filter matches any data Intent with a URI scheme of http and a MIME type of either "video/mpeg" or "audio/mpeg".

Activity Lifecycle
The activity lifecycle is the set of states an activity can be in during its entire lifetime, from the time it's created to when it's destroyed and the system reclaims its resources. As the user interacts with your app and other apps on the device, activities move into different states.

Type of Launch modes
There are four launch modes available as part of the <activity> element:
1. "standard" (the default): A new Activity is launched and added to the back stack for the current task. An Activity can be instantiated multiple times, a single task can have multiple instances of the same Activity, and multiple instances can belong to different tasks.
2. "singleTop": If an instance of an Activity exists at the top of the back stack for the current task and an Intent request for that Activity arrives, Android routes that Intent to the existing Activity instance rather than creating a new instance. A new Activity is still instantiated if there is an existing Activity anywhere in the back stack other than the top.
3. "singleTask": When the Activity is launched the system creates a new task for that Activity. If another task already exists with an instance of that Activity, the system routes the Intent to that Activity instead.
4. "singleInstance": Same as single task, except that the system doesn't launch any other Activity into the task holding the Activity instance. The Activity is always the single and only member of its task.

Intent flags
Intent flags are options that specify how the activity (or other app component) that receives the intent should handle that intent. Intent flags are defined as constants in the Intent class and begin with the word FLAG_. You add Intent flags to an Intent object with setFlag() or addFlag().

Intent flags – Types
Three specific Intent flags are used to control activity launch modes, either in conjunction with the launchMode attribute or in place of it. Intent flags always take precedence over the launch mode in case of conflicts.
● FLAG_ACTIVITY_NEW_TASK: start the Activity in a new task. This behavior is the same as for singleTask launch mode.
● FLAG_ACTIVITY_SINGLE_TOP: if the Activity to be launched is at the top of the back stack, route the Intent to that existing Activity instance. Otherwise create a new Activity instance. This is the same behavior as the singleTop launch mode.
● FLAG_ACTIVITY_CLEAR_TOP: If an instance of the Activity to be launched already exists in the back stack, destroy any other Activity on top of it and route the Intent to that existing instance. When used in conjunction with FLAG_ACTIVITY_NEW_TASK, this flag locates any existing instances of the Activity in any task and brings it to the foreground.

Fragment
A Fragment represents a behavior or a portion of user interface in a FragmentActivity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running.
A fragment must always be hosted in an activity and the fragment's lifecycle is directly affected by the host activity's lifecycle.

Fragments lifecycle
To create a fragment, you must create a subclass of Fragment (or an existing subclass of it). The Fragment class has code that looks a lot like an Activity. It contains callback methods similar to an activity, such as onCreate(), onStart(), onPause(), and onStop().

Fragment Navigation
FragmentManager API can handle list of operations you can perform on a Fragment.
FragmentTransaction include
● add
● replace
● show
● hide
● attach
● Detach
You may also even decide to add them to a back stack.

UI testing
The Espresso testing framework, in the Android Testing Support Library, provides APIs for writing UI tests to simulate user interactions within a single app. Espresso tests run on actual device or emulator and behave as if an actual user is using the app.
You can use Espresso to create UI tests to automatically verify the following:
● The app returns the correct UI output in response to a sequence of user actions on a device.
● The app's navigation and input controls bring up the correct Activity and View elements.
● The app responds correctly with mocked-up dependencies, such as data from an outside server, or can work with stubbed out backend methods to simulate real interactions with backend components with programmed to reply set of defined responses.
A key benefit of using Espresso is that it has access to instrumentation information, such as the context for the app, so that you can monitor all of the interaction the Android system has with the app. Another key benefit is that it automatically synchronizes test actions with the app's UI. Espresso detects when the main thread is idle, so it is able to run your test at the appropriate time, improving the reliability of your tests. This capability also relieves you from having to add any timing workarounds, such as a sleep period, in your test code.
The Espresso testing framework works with the AndroidJUnitRunner test runner and requires instrumentation, which is described later in this section. Espresso tests can run on devices running Android 2.2 (API level 8) and higher.

Android Notification
A notification is a message your app displays to the user outside your app's normal UI. When your app tells the system to issue a notification, the notification appears to the user as an icon in the notification area, on the left side of the status bar.
If the device is unlocked, the user opens the notification drawer to see the details of the notification. If the device is locked, the user views the notification on the lock screen.

Notification channels
In the Settings app on an Android-powered device, users can adjust the notifications they receive. Starting with Android 8.0 (API level 26), you can assign each of your app's notifications to a notification channel. Each notification channel represents a type of notification, and you can group several notifications in each channel.
If you target only lower-end devices, you don't need to implement notification channels to display notifications.
Notification channels are called Categories in the user-visible Settings app.
When you create a notification channel in your code, you set behavior for that channel, and the behavior is applied to all of the notifications in the channel.

Set the intent for the notification's tap action
Every notification must respond when it is tapped, usually by launching an Activity in your app. To launch an Activity in your app, set a content intent using the setContentIntent() method, passing in the Intent wrapped in a PendingIntent object. When your app uses a PendingIntent, the system can launch the Activity in your app on your behalf.
To instantiate a PendingIntent, use one of the following methods, depending on how you want the contained Intent to be delivered:
1. To launch an Activity when a user taps the notification, use PendingIntent.getActivity(). Pass in an explicit Intent for the Activity you want to launch. The getActivity() method corresponds to an Intent delivered using startActivity().
2. For an Intent passed into startService(), for example a service to download a file, use PendingIntent.getService().
3. For a broadcast Intent delivered with sendBroadcast(), use PendingIntent.getBroadcast().

PendingIntent methods
Each of these PendingIntent methods takes the following arguments:
● The application context.
● A request code, which is a constant integer ID for the PendingIntent.
● The Intent to be delivered.
● A PendingIntent flag that determines how the system handles multiple PendingIntent objects from the same app.

Ongoing notifications
Ongoing notifications are notifications that the user can't dismiss. Use ongoing notifications for background tasks that the user actively engages with, for example playing music. You can also use ongoing notifications to show tasks that are occupying the device, for example file downloads, sync operations, and active network connections.
To make a notification ongoing, set setOngoing() to true.
Your app must explicitly cancel ongoing notifications by calling cancel() or cancelAll().

Clearing notifications
Notifications remain visible until one of the following happens:
● If the notification can be cleared, it disappears when the user dismisses it by swiping it or by using "Clear All".
● If you called setAutoCancel() when you created the notification, the notification cancels itself automatically. When the user taps the notification, the notification is removed from the status bar.
● If you call cancel() on the Notification object for a specific notification ID, the notification is removed from the status bar.
● If you call cancelAll() on the Notification object, all the notifications you've issued are removed from the status bar.

Data storage
Android provides several options for you to save persistent app data. The solution you choose depends on your specific needs.
Your data storage options include the following:
● Shared preferences: Store private primitive data in key-value pairs.
● Internal storage: Store private data on the device memory.
● External storage: Store public data on the shared external storage.
● SQLite databases: Store structured data in a private database.
● Room persistence library: Part of the Android Architecture Component libraries. Room caches an SQLite database locally, and automatically syncs changes to a network database.
● Cloud backup: Back up your app and user data in the cloud.
● Firebase realtime database: Store and sync data with a NoSQL cloud database. Data is synced across all clients in real time, and remains available when your app goes offline.
● Huawei Cloud DB: Real time could database solution.
● Custom data store: Configure the Preference APIs to store preferences in a storage location you provide.

Shared preferences
Shared preferences allow you to store small amounts of primitive data as key/value pairs in a file on the device. To get a handle to a preference file, and to read, write, and manage preference data, use the SharedPreferences class. The Android framework manages the shared preferences file itself. The file is accessible to all the components of your app, but it is not accessible to other apps.

App Setting
Apps often include settings that allow users to modify app features and behaviors.
Build an app's settings using various subclasses of the Preference class rather than using View elements. Preference provides the View to be displayed for each setting, and associates with it a SharedPreferences interface to store and retrieve the preference data.

Preference Classes
● PreferenceGroup: Represents a group of settings (Preference objects).
● PreferenceCategory: Provides a disabled title above a group as a section divider.
● PreferenceScreen: Represents a top-level Preference that is the root of a Preference hierarchy. Use a PreferenceScreen in a layout at the top of each screen of settings.
● CheckBoxPreference: Creates a list item that shows a checkbox for a setting that is either enabled or disabled. The saved value is a boolean (true if it's checked).
● ListPreference: Creates an item that opens a dialog with a list of radio buttons.
● SwitchPreference: Creates a two-state option that can be toggled (such as on/off or true/false).
● EditTextPreference: Creates an item that opens a dialog with an EditText element. The saved value is a String.
● RingtonePreference: Lets the user choose a ringtone from those available on the device.

     
 
what is notes.io
 

Notes.io is a web-based application for taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000 notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 12 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.