Mobile Computing and App Development Notes PDF
Document Details
Uploaded by IntriguingNash4522
L.J. Polytechnic
CE & IT Department
Tags
Summary
This document provides notes on mobile computing and app development, focusing on different app development frameworks like React Native, Flutter, and Ionic. It covers native, progressive web, and cross-platform app development approaches.
Full Transcript
Mobile Computing and App Development NOTES OF MOBILE COMPUTING AND APP DEVELOPMENT Prepared and Compiled by CE & IT Department LJ...
Mobile Computing and App Development NOTES OF MOBILE COMPUTING AND APP DEVELOPMENT Prepared and Compiled by CE & IT Department LJ Polytechnic STUDENT ADVISORY Dear Students, Please be informed that the notes provided by the institute offer a concise presentation of the syllabus. While these notes are helpful for an overview and quick revision, We would strongly suggest that you refer to the prescribed textbooks / Reference book for a comprehensive understanding and thorough preparation of all exams and writing in the examination. Best regards, LJ Polytechnic. પ્રિય પ્રિદ્યાર્થીઓ, તમને જાણ કરિામા આિે છે કે સંસ્ર્થા દ્વારા િદાન કરિામાં આિેલી નોંધો અભ્યાસક્રમની સંક્ષિપ્ત િસ્તુપ્રત આપે છે. આ નોંધો પ્રિહંગાિલોકન અને ઝડપી પુનરાિતતન માટે મદદરૂપ હોઈ શકે છે તેમ છતા, અમે ભારપ ૂિતક સ ૂચન કરીએ છીએ કે પ્રિદ્યાર્થી તમામ પરીિાઓ અને પરીિામાં લેખનની વ્યાપક સમજણ અને સંપ ૂણત તૈયારી માટે માત્ર સ ૂચિેલા પાઠ્યપુસ્તકો/સંદભત પુસ્તકનો સંદભત લો. એલજે પોક્ષલટેકપ્રનક. Mobile Computing and App Development UNIT-1 Introduction of Mobile Applications 1.1 Introduction Talking about the mobile applications, the first thing that comes to mind are the apps like WhatsApp, Instagram, swigy, etc that we use in our everyday life. Ever thought about how these apps are made? Which technology is used? Let’s discuss what technologies or frameworks can be used to develop a mobile application. Mobile Apps are majorly developed for 3 Operating System: Android IOS Windows There are 3 different ways to develop Mobile apps: – 1. 1st Party Native App development: These types of apps normally run in the native devices, that is, it runs only in the OS that it is specifically designed for it. These apps cannot be used on different devices using a different OS. The apps that are developed for android are normally coded using Java or Kotlin languages. The IDE normally used for android app development is Android Studio which provides all features and the apps that are developed for IOS are generally coded in Swift language or Objective- C. The IDE suggested for IOS App Development is XCode. Example: Here’s an example of a 1st party native app: A retail company wants to improve the in-store shopping experience for its customers. They develop a 1st party native app that allows customers to: Browse the store’s inventory and product information Create a shopping list Scan barcodes to view product information and reviews Locate items in the store using an interactive map Pay for items directly through the app, without having to wait in line at the register The app is only available to the company’s customers and can only be used in their physical stores. The app is designed to integrate with the company’s existing systems, such as inventory management and point-of-sale systems. This app is developed by the retail company for their own use, to improve the in-store customer experience, increase sales and gain insights from the customer’s behaviour. Mobile Computing and App Development In this example, the retail company is the 1st party, and the app is a native app, because it is developed for the specific platform (iOS or Android) and can take full advantage of the device’s capabilities and features. 2. Progressive web Application: Progressive web apps are essentially a website which runs locally on your device. The technologies used are Microsoft Blazor, React, Angular JS, Native Script, Iconic. These technologies normally used for web development propose. The apps’ UI is developed the same way as they are developed while developing the website. This category has many ups and downs let’s start with the advantages of Progressive web apps. Example: Here’s an example of a Progressive Web App: A news website wants to provide its users with a better mobile experience. They develop a Progressive Web App that: Allows users to access the website offline by storing content on the user’s device Sends push notifications to users to alert them of breaking news Can be installed on the user’s home screen like a native app Provides a fast and smooth browsing experience Has a responsive design that adapts to different screen sizes Users can access the PWA by visiting the website on their mobile browser. They are prompted to install the PWA on their home screen, which allows them to access the website offline and receive push notifications. In this example, the news website is the 1st party and the app is a Progressive web app, because it can be accessed through a web browser and can be installed on the user’s device like a native app. It also allows users to access the content offline and have a fast and smooth experience. 3. Cross-Platform Application: These are frameworks that allow developing total native applications which have access to all the native features of IOS and Android but with the same code base. These apps run on both Android and IOS. So normally the development speeds of these apps are very fast and the maintenance cost is low. The performance speed is comparatively low to 1st party native apps but faster than PWA. Xamarin is Microsoft cross-platform solution that uses the programming languages like.NET, C#, F#. The IDE preferred is Visual Studio. The UI/UX is totally native giving access to all features. This technology is having a wide community. And whenever an update is released by Android and IOS the same updates are released by Microsoft through Visual Studio. React Native is Facebook’s cross-platform solution which uses the language JavaScript And the preferred IDE is WebStrome & Visual Studio Code. Same like Xamarin React Native has totally native UI/UX and gives access to all features. And the updates are released the same day by Facebook as Android and IOS. Flutter is Google’s cross-platform solution which uses the language, Dart. The IDE preferred is Android Studio, IntelliJ IDE, and Visual Studio Code. The UI/UX is bespoke and Flutters has to come up with their new libraries whenever Android and IOS comes up with an update to mimic those update. The community is fast growing. Mobile Computing and App Development Example: Here’s an example of a cross-platform application: A project management company wants to create a project management tool that can be used by teams on different platforms. They develop a cross-platform application that Can be used on Windows, Mac, iOS, and Android devices: Allows users to create and assign tasks, set deadlines, and track progress Integrates with popular tools such as Google Calendar and Trello Has a user-friendly interface that works seamlessly across all platforms The application can be downloaded from the company’s website or from different app stores such as App Store, Google Play Store, Microsoft Store, and Mac App Store, depending on the platform. This example illustrates how the company developed a project management tool that can be used by teams on different platforms, Windows, Mac, iOS and Android, which is a cross-platform application. It allows teams to collaborate and manage their projects seamlessly, regardless of the platform they use. 1.2 Mobile Development Framework A mobile development framework is a software framework that is designed to support mobile app development. It is a software library that provides a fundamental structure to support the development of applications for a specific environment. Frameworks can be in three categories: native frameworks for platform-specific development, mobile web app frameworks, and hybrid apps, which combine the features of both native and mobile web app frameworks. Mobile App Development Framework is a library that offers the required fundamental structure to create mobile applications for a specific environment. In short, it acts as a layout to support mobile app development. There are various advantages of Mobile App Development frameworks such as cost- effectiveness, efficiency, and many more. Moreover, mobile application frameworks can be classified majorly into 3 categories: Native Apps, Web Apps & Hybrid Apps. Before moving further, let’s take a quick look at all three categories of mobile development apps. Native Apps: A Native App is an application specifically designed for a particular platform or device. Mobile Computing and App Development Web Apps: A Web App is concerned with an application that is designed to deliver web pages on different web platforms for any device. Hybrid Apps: A Hybrid App is a combination of both native & web applications. It can be developed for any platform from a single code base. 1.2.1 React Native React Native is one of the most recommended Mobile App Frameworks in the development industry. The framework, created by Facebook, is an open-source framework that offers you to develop mobile applications for Android & iOS platforms. The React Native framework is based on React and JavaScript that aims to develop native applications over hybrid applications that run on a web view. Moreover, it is a cross-platform development framework that uses a single code base for both Android & iOS applications. Some of the major benefits of React Native are mentioned below: Code Re-usability & Cost-Effective Compatible with third-party plugins Re-usable components for optimal performance Provides hot deployment features Ease of Maintenance 1.2.2 Flutter Flutter, developed by Google, is a UI toolkit to build native applications for mobile apps, desktop & web platforms. Flutter is a cross-platform mobile app development framework that works on one code base to develop Android as well as iOS applications. The framework provides a large range of fully customizable widgets that helps to build native applications in a shorter span. Moreover, Flutter uses the 2D rendering engine called Skia for developing visuals and its layered architecture ensures the effective functioning of components. Some of the major benefits of Flutter are mentioned below: Provides Full Native Performance Flexible User interface (UI) Provides Strong Widget Support Offers Built-in Material Design Fast Application Development 1.2.3 Ionic Ionic, developed in 2013, is an open-source framework that allows you to build cross-platform for mobile apps using web technologies like HTML, CSS & JavaScript. The application built through the Ionic framework can work on Android, iOS & Windows platforms. The framework offers numerous default UI components such as forms, action sheets, filters, navigation menus, and many more for attractive and worthwhile design. Moreover, Ionic has its own command-line interface and various other in-built features such as Ionic Native, Cordova-Based App packages, etc. Some of the major benefits of Ionic for mobile development apps are mentioned below: Faster Application Development. Mobile Computing and App Development Availability of Cordova Plugins Built-in UI components Platform Independent Based on AngularJS Android Framework(Platform) Android is an open source, Linux-based software stack created for a wide array of devices and form factors. Figure shows the major components of the Android Framework/Platform. Mobile Computing and App Development Figure. The Android software stack. Linux kernel The foundation of the Android platform is the Linux kernel. For example, the Android Runtime (ART) relies on the Linux kernel for underlying functionalities such as threading and low-level memory management. Using a Linux kernel lets Android take advantage of key security features and lets device manufacturers develop hardware drivers for a well-known kernel. Hardware abstraction layer (HAL) The hardware abstraction layer (HAL) provides standard interfaces that expose device hardware capabilities to the higher-level Java API framework. The HAL consists of multiple library modules, each of which implements an interface for a specific type of hardware component, such as the camera or Bluetooth module. When a framework API makes a call to access device hardware, the Android system loads the library module for that hardware component. Android runtime For devices running Android version 5.0 (API level 21) or higher, each app runs in its own process and with its own instance of the Android Runtime (ART). ART is written to run multiple virtual machines on low- memory devices by executing Dalvik Executable format (DEX) files, a bytecode format designed specifically for Android that's optimized for a minimal memory footprint. Build tools, such as d8, compile Java sources into DEX bytecode, which can run on the Android platform. Some of the major features of ART include the following: Ahead-of-time (AOT) and just-in-time (JIT) compilation Optimized garbage collection (GC) On Android 9 (API level 28) and higher, conversion of an app package's DEX files to more compact machine code Better debugging support, including a dedicated sampling profiler, detailed diagnostic exceptions and crash reporting, and the ability to set watchpoints to monitor specific fields Prior to Android version 5.0 (API level 21), Dalvik was the Android runtime. If your app runs well on ART, then it can work on Dalvik as well, but the reverse might not be true. Android also includes a set of core runtime libraries that provide most of the functionality of the Java programming language, including some Java 8 language features, that the Java API framework uses. Native C/C++ libraries Many core Android system components and services, such as ART and HAL, are built from native code that requires native libraries written in C and C++. The Android platform provides Java framework APIs to expose the functionality of some of these native libraries to apps. For example, you can access OpenGL ES through the Android framework’s Java OpenGL API to add support for drawing and manipulating 2D and 3D graphics in your app. If you are developing an app that requires C or C++ code, you can use the Android NDK to access some of these native platform libraries directly from your native code. Java API framework Mobile Computing and App Development The entire feature-set of the Android OS is available to you through APIs written in the Java language. These APIs form the building blocks you need to create Android apps by simplifying the reuse of core, modular system components and services, which include the following: A rich and extensible view system you can use to build an app’s UI, including lists, grids, text boxes, buttons, and even an embeddable web browser A resource manager, providing access to non-code resources such as localized strings, graphics, and layout files A notification manager that enables all apps to display custom alerts in the status bar An activity manager that manages the lifecycle of apps and provides a common navigation back stack Content providers that enable apps to access data from other apps, such as the Contacts app, or to share their own data Developers have full access to the same framework APIs that Android system apps use. System apps Android comes with a set of core apps for email, SMS messaging, calendars, internet browsing, contacts, and more. Apps included with the platform have no special status among the apps the user chooses to install. So, a third-party app can become the user's default web browser, SMS messenger, or even the default keyboard. Some exceptions apply, such as the system's Settings app. The system apps function both as apps for users and to provide key capabilities that developers can access from their own app. For example, if you want your app to deliver SMS messages, you don't need to build that functionality yourself. You can instead invoke whichever SMS app is already installed to deliver a message to the recipient you specify. 1.3 Components of Android Application There are some necessary building blocks that an Android application consists of. These loosely coupled components are bound by the application manifest file which contains the description of each component and how they interact. The manifest file also contains the app’s metadata, its hardware configuration, and platform requirements, external libraries, and required permissions. There are the following main components of an android app: 1. Activities: Activities are said to be the presentation layer of our applications. The UI of our application is built around one or more extensions of the Activity class. By using Fragments and Views, activities set the layout and display the output and also respond to the user’s actions. An activity is implemented as a subclass of class Activity. class MainActivity : AppCompatActivity() { } Mobile Computing and App Development 2. Services: Services are like invisible workers of our app. These components run at the backend, updating your data sources and Activities, triggering Notification, and also broadcast Intents. They also perform some tasks when applications are not active. A service can be used as a subclass of class Service: class ServiceName : Service() { } 3. Content Providers: It is used to manage and persist the application data also typically interacts with the SQL database. They are also responsible for sharing the data beyond the application boundaries. The Content Providers of a particular application can be configured to allow access from other applications, and the Content Providers exposed by other applications can also be configured. A content provider should be a sub-class of the class ContentProvider. class contentProviderName : ContentProvider() { override fun onCreate(): Boolean {} } 4. Broadcast Receivers: They are known to be intent listeners as they enable your application to listen to the Intents that satisfy the matching criteria specified by us. Broadcast Receivers make our application react to any received Intent thereby making them perfect for creating event-driven applications. 5. Intents: It is a powerful inter-application message-passing framework. They are extensively used throughout Android. Intents can be used to start and stop Activities and Services, to broadcast messages system-wide or to an explicit Activity, Service or Broadcast Receiver or to request action be performed on a particular piece of data. 6. Widgets: These are the small visual application components that you can find on the home screen of the devices. They are a special variation of Broadcast Receivers that allow us to create dynamic, interactive application components for users to embed on their Home Screen. 7. Notifications: Notifications are the application alerts that are used to draw the user’s attention to some particular app event without stealing focus or interrupting the current activity of the user. They are generally used to grab user’s attention when the application is not visible or active, particularly from within a Service or Broadcast Receiver. Examples: E-mail popups, Messenger popups, etc. Mobile Computing and App Development 1.4 Android Manifest File in Android Every project in Android includes a Manifest XML file, which is AndroidManifest.xml, located in the root directory of its project hierarchy. The manifest file is an important part of our app because it defines the structure and metadata of our application, its components, and its requirements. This file includes nodes for each of the Activities, Services, Content Providers, and Broadcast Receivers that make the application, and using Intent Filters and Permissions determines how they coordinate with each other and other applications. The manifest file also specifies the application metadata, which includes its icon, version number, themes, etc., and additional top-level nodes can specify any required permissions, and unit tests, and define hardware, screen, or platform requirements. The manifest comprises a root manifest tag with a package attribute set to the project’s package. It should also include an xmls:android attribute that will supply several system attributes used within the file. We use the versionCode attribute is used to define the current application version in the form of an integer that increments itself with the iteration of the version due to update. Also, the versionName attribute is used to specify a public version that will be displayed to the users. We can also specify whether our app should install on an SD card of the internal memory using the installLocation attribute. A typical manifest file looks as: Example: XML android:name=".MainActivity" android:exported="true"> A manifest file includes the nodes that define the application components, security settings, test classes, and requirements that make up the application. Some of the manifest sub-node tags that are mainly used are: 1. manifest The main component of the AndroidManifest.xml file is known as manifest. Additionally, the packaging field describes the activity class’s package name. It must contain an element with the xmlns:android and package attribute specified. 2. uses-sdk: It is used to define a minimum and maximum SDK version by means of an API Level integer that must be available on a device so that our application functions properly, and the target SDK for which it has been designed using a combination of minSdkVersion, maxSdkVersion, and targetSdkVersion attributes, respectively. It is contained within the element. Mobile Computing and App Development 3. uses-permission It outlines a system permission that must be granted by the user for the app to function properly and is contained within the element. When an application is installed (on Android 5.1 and lower devices or Android 6.0 and higher), the user must grant the application permissions. 4. application A manifest can contain only one application node. It uses attributes to specify the metadata for your application (including its title, icon, and theme). During development, we should include a debuggable attribute set to true to enable debugging, then be sure to disable it for your release builds. The application node also acts as a container for the Activity, Service, Content Provider, and Broadcast Receiver nodes that specify the application components. The name of our custom application class can be specified using the android:name attribute. 5. uses-library It defines a shared library against which the application must be linked. This element instructs the system to add the library’s code to the package’s class loader. It is contained within the element. 6. activity The Activity sub-element of an application refers to an activity that needs to be specified in the AndroidManifest.xml file. It has various characteristics, like label, name, theme, launchMode, and others. In the manifest file, all elements must be represented by. Any activity that is not declared there won’t run and won’t be visible to the system. It is contained within the element.. 7. intent-filter It is the sub-element of activity that specifies the type of intent to which the activity, service, or broadcast receiver can send a response. It allows the component to receive intents of a certain type while filtering out those that are not useful for the component. The intent filter must contain at least one element.. 8. action It adds an action for the intent-filter. It is contained within the element. 9. category It adds a category name to an intent-filter. It is contained within the element.. 10. uses-configuration The uses-configuration components are used to specify the combination of input mechanisms that are supported by our application. It is useful for games that require particular input controls. 11. uses-features It is used to specify which hardware features your application requires. This will prevent our application from being installed on a device that does not include a required piece of hardware such as NFC hardware, as follows 12. permission It is used to create permissions to restrict access to shared application components. We can also use the existing platform permissions for this purpose or define your own permissions in the manifest. 1.5. Permission Model of Android If your app offers functionality that might require access to restricted data or restricted actions, determine whether you can get the information or perform the actions without needing to declare permissions. You can fulfill many use cases in your app, such as taking photos, pausing media playback, and displaying relevant ads, without needing to declare any permissions. If you decide that your app must access restricted data or perform restricted actions to fulfill a use case, declare the appropriate permissions. Some permissions, known as install-time permissions, are automatically granted when your app is installed. Other permissions, known as runtime permissions, require your app to go a step further and request the permission at runtime. Mobile Computing and App Development Types of permission: 1. Install-time permissions Install-time permissions give your app limited access to restricted data or let your app perform restricted actions that minimally affect the system or other apps. When you declare install-time permissions in your app, an app store presents an install-time permission notice to the user when they view an app's details page, as shown in figure 2. The system automatically grants your app the permissions when the user installs your app. 2.Normal permissions These permissions allow access to data and actions that extend beyond your app's sandbox but present very little risk to the user's privacy and the operation of other apps. 3. Signature permissions The system grants a signature permission to an app only when the app is signed by the same certificate as the app or the OS that defines the permission. Applications that implement privileged services, such as autofill or VPN services, also make use of signature permissions. These apps require service-binding signature permissions so that only the system can bind to the services. 4. Runtime permissions Runtime permissions, also known as dangerous permissions, give your app additional access to restricted data or let your app perform restricted actions that more substantially affect the system and other apps. Therefore, you need to request runtime permissions in your app before you can access the restricted data or perform restricted actions. Don't assume that these permissions have been previously granted—check them and, if needed, request them before each access. When your app requests a runtime permission, the system presents a runtime permission prompt. Mobile Computing and App Development Many runtime permissions access private user data, a special type of restricted data that includes potentially sensitive information. Examples of private user data include location and contact information. 5.Special permissions Special permissions correspond to particular app operations. Only the platform and OEMs can define special permissions. Additionally, the platform and OEMs usually define special permissions when they want to protect access to particularly powerful actions, such as drawing over other apps. The Special app access page in system settings contains a set of user-toggleable operations. Many of these operations are implemented as special permissions. 6. Permission groups Permissions can belong to permission groups. Permission groups consist of a set of logically related permissions. For example, permissions to send and receive SMS messages might belong to the same group, as they both relate to the application's interaction with SMS. Permission groups help the system minimize the number of system dialogs that are presented to the user when an app requests closely related permissions. When a user is presented with a prompt to grant permissions for an application, permissions belonging to the same group are presented in the same interface. However, permissions can change groups without notice, so don't assume that a particular permission is grouped with any other permission. 1.6. Downloading and Installing SDK Install the SDK 1. Click Tools > SDK Manager. 2. In the SDK Platforms tab, select Android UpsideDownCake Preview. 3. In the SDK Tools tab, select Android SDK Build-Tools 29. 4. Click OK to install the SDK. 1.7. Exploring the Development Environment Android Studio is the official Integrated Development Environment (IDE) for Android app development. Android Studio offers even more features that enhance your productivity when building Android apps, such as: A flexible Gradle-based build system A fast and feature-rich emulator A unified environment where you can develop for all Android devices Live Edit to update composables in emulators and physical devices in real time Mobile Computing and App Development Code templates and GitHub integration to help you build common app features and import sample code Extensive testing tools and frameworks Lint tools to catch performance, usability, version compatibility, and other problems C++ and NDK support Built-in support for Google Cloud Platform, making it easy to integrate Google Cloud Messaging and App Engine. Get to know the Android Studio UI 1. Toolbar: Carry out a wide range of actions, including running your app and launching Android tools. 2. Navigation bar: Navigate through your project and open files for editing. It provides a more compact view of the structure visible in the Project window. 3. Editor window: Create and modify code. Depending on the current file type, the editor can change. For example, when viewing a layout file, the editor displays the Layout Editor. 4. Tool window bar: Use the buttons on the outside of the IDE window to expand or collapse individual tool windows. Mobile Computing and App Development 5. Tool windows: Access specific tasks like project management, search, version control, and more. You can expand them and collapse them. 6. Status bar: Display the status of your project and the IDE itself, as well as any warnings or messages. Tool windows To expand or collapse a tool window, click the tool’s name in the tool window bar. You can also drag, pin, unpin, attach, and detach tool windows. To return to the default layout of the current tool window, click Window > Restore Default Layout. To customize your default layout, click Window > Store Current Layout as Default. To show or hide the entire tool window bar, click the window in the bottom left-hand corner of the Android Studio window. To locate a specific tool window, hover over the window icon and select the tool window from the menu. 1.8 Build Your First Android App in Kotlin 1.Install Android Studio 2.Create your first project click Start a new Android Studio project. Select Basic Activity (not the default). Click Next. Mobile Computing and App Development Give your application a name, such as My First App. Make sure the Language is set to Kotlin. Leave the defaults for the other fields. Click Finish. Get your screen set up If there's a Gradle window open on the right side, click on the minimize button (—) in the upper right corner. Depending on the size of your screen, consider resizing the pane on the left showing the project folders to take up less space. Mobile Computing and App Development Explore the project structure and layout Mobile Computing and App Development Double-click the app (1) folder to expand the hierarchy of app files. (See (1) in the screenshot.) If you click Project (2), you can hide or show the Project view. The current Project view selection is Project > Android. Create a virtual device (emulator) In Android Studio, select Tools > AVD Manager, or click the AVD Manager icon in the toolbar. 1ef215721ed1bd47.png Click +Create Virtual Device. (If you have created a virtual device before, the window shows all of your existing devices and the +Create Virtual Device button is at the bottom.) The Select Hardware window shows a list of pre-configured hardware device definitions. Choose a device definition, such as Pixel 2, and click Next. (For this codelab, it really doesn't matter which device definition you pick). In the System Image dialog, from the Recommended tab, choose the latest release. (This does matter.) If a Download link is visible next to a latest release, it is not installed yet, and you need to download it first. If necessary, click the link to start the download, and click Next when it's done. This may take a while depending on your connection speed. In the next dialog box, accept the defaults, and click Finish. The AVD Manager now shows the virtual device you added. If the Your Virtual Devices AVD Manager window is still open, go ahead and close it. Run your app on your new emulator] In Android Studio, select Run > Run ‘app', or click the Run icon in the toolbar. The icon changes once your app is running In Run > Select Device, under Available devices, select the virtual device that you just configured. A dropdown menu also appears in the toolbar. Once your app builds and the emulator is ready, Android Studio uploads the app to the emulator and runs it. You should see your app as shown in the following screenshot. Mobile Computing and App Development Mobile Computing and App Development UNIT-2 Designing Application 2.1 Working with activity In Android, an activity is referred to as one screen in an application. It is very similar to a single window of any desktop application. An Android app consists of one or more screens or activities. Each activity goes through various stages or a lifecycle and is managed by activity stacks. So when a new activity starts, the previous one always remains below it. There are four stages of an activity. If an activity is in the foreground of the screen i.e at the top of the stack, then it is said to be active or running. This is usually the activity that the user is currently interacting with. If an activity has lost focus and a non-full-sized or transparent activity has focused on top of your activity. In such a case either another activity has a higher position in multi-window mode or the activity itself is not focusable in the current window mode. Such activity is completely alive. If an activity is completely hidden by another activity, it is stopped or hidden. It still retains all the information, and as its window is hidden thus it will often be killed by the system when memory is needed elsewhere. The system can destroy the activity from memory by either asking it to finish or simply killing its process. When it is displayed again to the user, it must be completely restarted and restored to its previous state. For each stage, android provides us with a set of 7 methods that have their own significance for each stage in the life cycle. The image shows a path of migration whenever an app switches from one state to another. Activity Lifecycle in Android: There are 7 different method in activity lifecycle: – 1. onCreate(): It is called when the activity is first created. This is where all the static work is done like creating views, binding data to lists, etc. This method also provides a Bundle containing its previous frozen state, if there was one. Example: import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Bundle containing previous frozen state Mobile Computing and App Development setContentView(R.layout.activity_main) // The content view pointing to the id of layout // in the file activity_main.xml val toast = Toast.makeText(applicationContext, "onCreate Called", Toast.LENGTH_LONG).show() } } } Mobile Computing and App Development 2. onStart(): It is invoked when the activity is visible to the user. It is followed by onResume() if the activity is invoked from the background. It is also invoked after onCreate() when the activity is first started. Example: import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toast = Toast.makeText(applicationContext, "onCreate Called", Toast.LENGTH_LONG).show() } override fun onStart() { super.onStart() // It will show a message on the screen // then onStart is invoked val toast = Toast.makeText(applicationContext, "onStart Called", Toast.LENGTH_LONG).show() } } 3. onRestart(): It is invoked after the activity has been stopped and prior to its starting stage and thus is always followed by onStart() when any activity is revived from background to on-screen. Example: import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity Mobile Computing and App Development class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toast = Toast.makeText(applicationContext, "onCreate Called", Toast.LENGTH_LONG).show() } override fun onRestart() { super.onRestart() // It will show a message on the screen // then onRestart is invoked val toast = Toast.makeText(applicationContext, "onRestart Called", Toast.LENGTH_LONG).show() } } 4. onResume(): It is invoked when the activity starts interacting with the user. At this point, the activity is at the top of the activity stack, with a user interacting with it. Always followed by onPause() when the activity goes into the background or is closed by the user. Example: import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) Mobile Computing and App Development val toast = Toast.makeText(applicationContext, "onCreate Called", Toast.LENGTH_LONG).show() } override fun onResume() { super.onResume() // It will show a message on the screen // then onResume is invoked val toast = Toast.makeText(applicationContext, "onResume Called", Toast.LENGTH_LONG).show() } } 5. onPause(): It is invoked when an activity is going into the background but has not yet been killed. It is a counterpart to onResume(). When an activity is launched in front of another activity, this callback will be invoked on the top activity (currently on screen). The activity, under the active activity, will not be created until the active activity’s onPause() returns, so it is recommended that heavy processing should not be done in this part. Example: import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toast = Toast.makeText(applicationContext, "onCreate Called", Toast.LENGTH_LONG).show() } override fun onPause() { super.onPause() Mobile Computing and App Development // It will show a message on the screen // then onPause is invoked val toast = Toast.makeText(applicationContext, "onPause Called", Toast.LENGTH_LONG).show() } } 6. onStop(): It is invoked when the activity is not visible to the user. It is followed by onRestart() when the activity is revoked from the background, followed by onDestroy() when the activity is closed or finished, and nothing when the activity remains on the background only. Example: import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toast = Toast.makeText(applicationContext, "onCreate Called", Toast.LENGTH_LONG).show() } override fun onStop() { super.onStop() // It will show a message on the screen // then onStop is invoked val toast = Toast.makeText(applicationContext, "onStop Called", Toast.LENGTH_LONG).show() } } Mobile Computing and App Development 7. onDestroy():The final call received before the activity is destroyed. This can happen either because the activity is finishing (when finish() is invoked) or because the system is temporarily destroying this instance of the activity to save space. Example: import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toast = Toast.makeText(applicationContext, "onCreate Called", Toast.LENGTH_LONG).show() } override fun onDestroy() { super.onDestroy() // It will show a message on the screen // then onDestroy is invoked val toast = Toast.makeText(applicationContext, "onDestroy Called", Toast.LENGTH_LONG).show() } } 2.2 Redirecting to another activity and passing data How to “Send the data from one activity to second activity using Intent”. In this example, we have two activities, activity_first which are the source activity, and activity_second which is the destination activity. We can send the data using the putExtra() method from one activity and get the data from the second activity using the getStringExtra() method. Step by Step Implementation: Step1: Create a New Project in Android Studio Mobile Computing and App Development Step2: Working with the XML Files Next, go to the activity_main.xml file, which represents the UI of the project. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail. Open the “activity_first_activity.xml” file and add the following widgets in a Relative Layout. An EditText to Input the message A Button to send the data Also, Assign the ID to each component along with other attributes as shown in the image and the code below. The assigned ID on a component helps that component to be easily found and used in the Java/Kotlin files. Syntax: android:id="@+id/id_name" Send Button: send_button_id input EditText: send_text_id XML: This will make the UI of the Application Mobile Computing and App Development Step3: Working with the MainActivity File Go to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail. Now, after the UI, this step will create the Backend of the App. For this, open the “first_activity” file and instantiate the components made in the XML file (EditText, send Button) using findViewById() method. This method binds the created object to the UI Components with the help of the assigned ID. Syntax: General ComponentType object = (ComponentType)findViewById(R.id.IdOfTheComponent); Syntax: for components used is as follows: Button send_button= findViewById(R.id.send_button_id); send_text = findViewById(R.id.send_text_id); Setting up the Operations for the Sending and Receiving of Data. These Operations are as follows: Add the listener to the send button and this button will send the data. This is done as follows: send_button.setOnClickListener(v -> {} after clicking this button following operation will be performed. Now create the String type variable to store the value of EditText which is input by the user. Get the value and convert it to a string. This is done as follows: String str = send_text.getText().toString(); Now create the Intent object First_activity.java class to Second_activity class. This is done as follows: Intent intent = new Intent(getApplicationContext(), Second_activity.class); where getApplicationContext() will fetch the current activity. Put the value in the putExtra method in the key-value pair then start the activity. This is done as follows: intent.putExtra("message_key", str); startActivity(intent); where “str” is the string value and the key is “message_key” this key will use to get the str v alue Example: import android.content.Intent import android.os.Bundle import android.widget.Button import android.widget.EditText Mobile Computing and App Development import androidx.appcompat.app.AppCompatActivity class first_activity : AppCompatActivity() { // define the variable lateinit var send_button: Button lateinit var send_text: EditText override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_first_activity) send_button = findViewById(R.id.send_button_id) send_text = findViewById(R.id.send_text_id) // add the OnClickListener in sender button after clicked this button following Instruction will run send_button.setOnClickListener { // get the value which input by user in EditText and convert it to string val str = send_text.text.toString() // Create the Intent object of this class Context() to Second_activity class val intent = Intent(applicationContext, Second_activity::class.java) // now by putExtra method put the value in key, value pair key is // message_key by this key we will receive the value, and put the string intent.putExtra("message_key", str) // start the Intent startActivity(intent) } } } Step4: Creating Second_Activity to Receive the Data. The steps to create the second activity are as follows: Mobile Computing and App Development android project > File > new > Activity > Empty Activity Step5: Working with the Second XML File Add TextView to display the received messages. assign an ID to Textview. XML: The Second Activity is shown below: Step6: Working with the SecondActivity File Define the TextView variable, use findViewById() to get the TextView as shown above. receiver_msg = (TextView) findViewById(R.id.received_value_id); Now In the second_activity.java file create the object of getIntent to receive the value in String type vari able by the getStringExtra method using message_key. Intent intent = getIntent(); String str = intent.getStringExtra("message_key"); The received value set in the TextView object of the second activity XML file receiver_msg.setText(str); Kotlin: import android.os.Bundle import android.widget.TextView Mobile Computing and App Development import androidx.appcompat.app.AppCompatActivity class Second_activity : AppCompatActivity() { lateinit var receiver_msg: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_second_activity) receiver_msg = findViewById(R.id.received_value_id) // create the get Intent object val intent = intent // receive the value by getStringExtra() method and // key must be same which is send by first activity val str = intent.getStringExtra("message_key") // display the string into textView receiver_msg.text = str } } Toast A toast provides simple feedback about an operation in a small popup. It only fills the amount of space required for the message and the current activity remains visible and interactive. Toasts automatically disappear after a timeout. For example, clicking Send on an email triggers a "Sending message..." toast, as shown in the following screen capture: Mobile Computing and App Development If your app targets Android 12 (API level 31) or higher, its toast is limited to two lines of text and shows the application icon next to the text. Be aware that the line length of this text varies by screen size, so it's good to make the text as short as possible. Instantiate a Toast object Use the makeText() method, which takes the following parameters: 1. The activity Context. 2. The text that should appear to the user. 3. The duration that the toast should remain on the screen. The makeText() method returns a properly initialized Toast object. Show the toast To display the toast, call the show() method, as demonstrated in the following example: val text = "Hello toast!" val duration = Toast.LENGTH_SHORT val toast = Toast.makeText(this, text, duration) // in Activity toast.show() 2.3 Layouts: Android Layout is used to define the user interface that holds the UI controls or widgets that will appear on the screen of an android application or activity screen. Generally, every application is a combination of View and ViewGroup. As we know, an android application contains a large number of activities and we can say each activity is one page of the application. So, each activity contains multiple user interface components and those components are the instances of the View and ViewGroup. All the elements in a layout are built using a hierarchy of View and ViewGroup objects. Size, padding, and margins Mobile Computing and App Development The size of a view is expressed with a width and height. A view has two pairs of width and height values. The first pair is known as measured width and measured height. These dimensions define how big a view wants to be within its parent. You can obtain the measured dimensions by calling getMeasuredWidth() and getMeasuredHeight(). The second pair is known as width and height, or sometimes drawing width and drawing height. These dimensions define the actual size of the view on screen, at drawing time and after layout. These values might, but don't have to, differ from the measured width and height. You can obtain the width and height by calling getWidth() and getHeight(). To measure its dimensions, a view takes into account its padding. The padding is expressed in pixels for the left, top, right and bottom parts of the view. You can use padding to offset the content of the view by a specific number of pixels. For instance, a left padding of two pushes the view's content two pixels to the right of the left edge. You can set padding using the setPadding(int, int, int, int) method and query it by calling getPaddingLeft(), getPaddingTop(), getPaddingRight(), and getPaddingBottom(). Although a view can define a padding, it doesn't support margins. However, view groups do support margins. See ViewGroup and ViewGroup.MarginLayoutParams for more information. Types of Android Layout Android Linear Layout: LinearLayout is a ViewGroup subclass, used to provide child View elements one by one either in a particular direction either horizontally or vertically based on the orientation property. Android Relative Layout: RelativeLayout is a ViewGroup subclass, used to specify the position of child View elements relative to each other like (A to the right of B) or relative to the parent (fix to the top of the parent). Android Constraint Layout: ConstraintLayout is a ViewGroup subclass, used to specify the position of layout constraints for every child View relative to other views present. A ConstraintLayout is similar to a RelativeLayout, but having more power. Android Frame Layout: FrameLayout is a ViewGroup subclass, used to specify the position of View elements it contains on the top of each other to display only a single View inside the FrameLayout. Android Table Layout: TableLayout is a ViewGroup subclass, used to display the child View elements in rows and columns. 1.LinearLayout: Mobile Computing and App Development Android LinearLayout is a ViewGroup subclass, used to provide child View elements one by one either in a particular direction either horizontally or vertically based on the orientation property. We can specify the linear layout orientation using android:orientation attribute. All the child elements arranged one by one in multiple rows and multiple columns. 1. Horizontal list: One row, multiple columns. 2. Vertical list: One column, multiple rows. LinearLayout in activity_main.xml file: 2.RelativeLayout: Android RelativeLayout is a ViewGroup subclass, used to specify the position of child View elements relative to each other like (A to the right of B) or relative to the parent (fix to the top of the parent). Instead of using LinearLayout, we have to use RelativeLayout to design the user interface and keep our hierarchy flat because it improves the performance of the application. Attributes Description layout_alignParentLeft It is set “true” to match the left edge of view to the left edge of parent. layout_alignParentRight It is set “true” to match the right edge of view to the right edge of parent. layout_alignParentTop It is set “true” to match the top edge of view to the top edge of parent. layout_alignParentBottom It is set “true” to match the bottom edge of view to the bottom edge of parent. layout_alignLeft It accepts another sibling view id and align the view to the left of the specified view id layout_alignRight It accepts another sibling view id and align the view to the right of the specified view id. layout_alignStart It accepts another sibling view id and align the view to start of the specified view id. layout_alignEnd It accepts another sibling view id and align the view to end of specified view id. layout_centerInParent When it is set “true”, the view will be aligned to the center of parent. layout_centerHorizontal When it is set “true”, the view will be horizontally centre aligned within its parent. layout_centerVertical When it is set “true”, the view will be vertically centre aligned within its parent. layout_toLeftOf It accepts another sibling view id and places the view left of the specified view id. layout_toRightOf It accepts another sibling view id and places the view right of the specified view id. Mobile Computing and App Development layout_toStartOf It accepts another sibling view id and places the view to start of the specified view id. layout_toEndOf It accepts another sibling view id and places the view to end of the specified view id. layout_above It accepts another sibling view id and places the view above the specified view id. layout_below It accepts another sibling view id and places the view below the specified view id. RelativeLayout in activity_main.xml file: 3.ConstraintLayout: ConstraintLayout is similar to that of other View Groups which we have seen in Android such as RelativeLayout, LinearLayout, and many more. In this article, we will take a look at using ConstraintLayout in Android. Attributes Description android:id This is used to give a unique id to the layout. app:layout_constraintBottom_toBottomOf This is used to constrain the view with respect to the bottom position. Mobile Computing and App Development app:layout_constraintLeft_toLeftOf This attribute is used to constrain the view with respect to the left position. app:layout_constraintRight_toRightOf This attribute is used to constrain the view with respect to the right position. app:layout_constraintTop_toTopOf This attribute is used to constrain the view with respect to the top position. Advantages of using ConstraintLayout in Android: ConstraintLayout provides you the ability to completely design your UI with the drag and drop feature provided by the Android Studio design editor. It helps to improve the UI performance over other layouts. With the help of ConstraintLayout, we can control the group of widgets through a single line of code. With the help of ConstraintLayout, we can easily add animations to the UI components which we used in our app. Disadvantages of using ConstraintLayout: When we use the Constraint Layout in our app, the XML code generated becomes a bit difficult to understand. In most of the cases, the result obtain will not be the same as we got to see in the design editor. Sometimes we have to create a separate layout file for handling the UI for the landscape mode. Working with the activity_main.xml file: 4.Table Layout: Android TableLayout is a ViewGroup subclass which is used to display the child View elements in rows and columns. It will arrange all the children elements into rows and columns and does not display any border lines in between rows, columns or cells. The working of TableLayout is almost similar to HTML table and it contains as many columns as row with the most cells. Attributes Description android:id This is the ID which uniquely identifies the layout. android:collapseColumns This specifies the zero-based index of the columns to collapse. The column indices must be separated by a comma: 1, 2, 5. android:shrinkColumns The zero-based index of the columns to shrink. The column indices must be separated by a comma: 1, 2, 5. android:stretchColumns The zero-based index of the columns to stretch. The column indices must be separated by a comma: 1, 2, 5. How to declare TableLayout and TableRow? // Add Table rows here Mobile Computing and App Development activity_main.xml file: 2.4 Fragments In Android, the fragment is the part of Activity which represents a portion of User Interface(UI) on the screen. It is the modular section of the android activity that is very helpful in creating UI designs that are flexible in nature and auto-adjustable based on the device screen size. The UI flexibility on all devices improves the user experience and adaptability of the application. Fragments can exist only inside an activity as its lifecycle is dependent on the lifecycle of host activity. For example, if the host activity is paused, then Mobile Computing and App Development all the methods and operations of the fragment related to that activity will stop functioning, thus fragment is also termed as sub-activity. Fragments can be added, removed, or replaced dynamically i.e., while activity is running. tag is used to insert the fragment in an android activity layout. By dividing the activity’s layout multiple fragments can be added in it. Below is the pictorial representation of fragment interaction with the activity: Fragment Lifecycle: Mobile Computing and App Development Each fragment has it’s own lifecycle but due to the connection with the Activity it belongs to, the fragment lifecycle is influenced by the activity’s lifecycle. Methods of the Android Fragment 1. onAttach(): once during the lifetime of a fragment.. When we attach fragment(child) to Main(parent) activity then it call first and then not call this method any time(like you run an app and close and reopen) simple means that this method call only one time. 2. onCreate(): This method initializes the fragment by adding all the required attributes and components. 3. onCreateView(): System calls this method to create the user interface of the fragment. The root of the fragment’s layout is returned as the View component by this method to draw the UI. You should inflate your layout in onCreateView but shouldn’t initialize other views using findViewById in onCreateView. 4. onViewCreated(): It indicates that the activity has been created in which the fragment exists. View hierarchy of the fragment also instantiated before this function call. 5. onStart(): The system invokes this method to make the fragment visible on the user’s device. 6. onResume(): This method is called to make the visible fragment interactive. 7. onPause(): It indicates that the user is leaving the fragment. System call this method to commit the changes made to the fragment. 8. onStop(): Method to terminate the functioning and visibility of fragment from the user’s screen. 9. onDestroyView(): System calls this method to clean up all kinds of resources as well as view hierarchy associated with the fragment. It will call when you can attach new fragment and destroy existing fragment Resoruce 10. onDestroy(): It is called to perform the final clean up of fragment’s state and its lifecycle. 11. onDetach(): The system executes this method to disassociate the fragment from its host activity. It will call when your fragment Destroy(app crash or attach new fragment with existing fragment) Example: To create a fragment, you must create a subclass of Fragment (or an existing subclass of it). You can do it with 2 ways, First Create a class and extended with Fragment class and create resource layout file. OR Second ways is Right Click on Package -> New -> Fragment -> Fragments (Blank) then give Fragment Name , check Fragment Layout Name – > Finish Mobile Computing and App Development Step 1. Create an android project in the android studio Step 2. Create 2 Fragments and its resource layout. Follow upper section #Creating a Fragment First fragment resource file fragment_first.xml, Outer Layout is FrameLayout, you can use the choice of your layout (LinearLayout, RelativeLayout or ConstraintLayout etc) Mobile Computing and App Development FirstFragment.kotlin package `in`.eyehunt.androidfragmentexample import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup class FirstFragment : Fragment() { override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment return inflater!!.inflate(R.layout.fragment_first, container, false) } }// Required empty public constructor Second fragment resource file fragment_second.xml, Both fragments layout containing TextView widget to show text. Mobile Computing and App Development Output screenshot Android Fragment example app : 2.5 Themes A theme is a collection of attributes that's applied to an entire app, activity, or view hierarchy—not just an individual view. When you apply a theme, every view in the app or activity applies each of the theme's attributes that it supports. Themes can also apply styles to non-view elements, such as the status bar and window background. Styles and themes are declared in a style resource file in res/values/, usually named styles.xml. Figure - Two themes applied to the same activity: Theme.AppCompat (left) and Theme.AppCompat.Light (right). Mobile Computing and App Development Syntax : Themes versus styles Themes and styles have many similarities, but they are used for different purposes. Themes and styles have the same basic structure—a key-value pair that maps attributes to resources. A style specifies attributes for a particular type of view. For example, one style might specify a button's attributes. Every attribute you specify in a style is an attribute you can set in the layout file. Extracting all the attributes to a style makes it easy to use and maintain them across multiple widgets. A theme defines a collection of named resources that can be referenced by styles, layouts, widgets, and so on. Themes assign semantic names, like colorPrimary, to Android resources. Styles and themes are meant to work together. For example, you might have a style that specifies that one part of a button is colorPrimary, and another part is colorSecondary. The actual definitions of those colors are provided in the theme. When the device goes into night mode, your app can switch from its "light" theme to its "dark" theme, changing the values for all those resource names. You don't need to change the styles, since the styles are using the semantic names and not specific color definitions. Mobile Computing and App Development Android developers witness the ambiguity in styles and themes. The reason is that in Android there are only tag names , there is no tag available. Style is a collection of attributes that define the appearance of a single view. The style attributes are the font, color, size, background color, etc. For example, the font size may be different for heading and body. Theme, on the contrary, is applied to the entire app, or activity, or view hierarchy, not just for individual views. Themes can also apply styles to non-view elements such as status bar, window background, etc. For example, the colorPrimary is applied to all the Floating Action Buttons or Normal Buttons of the entire application. One can get the difference in the following image. 2.6 Notifications Android Notification provides short, timely information about the action happened in the application, even it is not running. The notification displays the icon, title and some amount of the content text. Notifications could be of various formats and designs depending upon the developer. In General, one must have witnessed these four types of notifications: 1. Status Bar Notification (appears in the same layout as the current time, battery percentage) 2. Notification drawer Notification (appears in the drop-down menu) 3. Heads-Up Notification (appears on the overlay screen, ex: Whatsapp notification, OTP messages) 4. Lock-Screen Notification (I guess you know it) Set Android Notification Properties: setSmallIcon(): It sets the icon of notification. setContentTitle(): It is used to set the title of notification. setContentText(): It is used to set the text message. setAutoCancel(): It sets the cancelable property of notification. setPriority(): It sets the priority of notification. Mobile Computing and App Development Example: Step1: Working with the activity_main.xml file Step2: Create a new empty activity Name the activity as afterNotification. When someone clicks on the notification, this activity will open up in our app that is the user will be redirected to this page. Below is the code for the activity_after_notification.xml file. Step3: Working with the MainActivity.kt file import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.graphics.Color import android.net.Uri import android.os.Build import android.os.Bundle import android.view.View import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.core.app.NotificationCompat class MainActivity : AppCompatActivity() { lateinit var notificationManager: NotificationManager lateinit var notificationChannel: NotificationChannel lateinit var builder: NotificationCompat.Builder private val channelId = "i.apps.notification" private val channelName = "NChannel" private val channelDescription = "Test Notification" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Mobile Computing and App Development setContentView(R.layout.activity_main) Toast.makeText(applicationContext,"On Create Called", Toast.LENGTH_LONG).show(); //Because you must create the notification channel before posting any notifications on Android 8.0 and later, execute this code as soon as your app starts. I if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val importance = NotificationManager.IMPORTANCE_DEFAULT notificationChannel = NotificationChannel(channelId, channelName, importance).apply { description = channelDescription } // notificationChannel.enableLights(true) // notificationChannel.lightColor = Color.GREEN // notificationChannel.enableVibration(false) // notificationManager.createNotificationChannel(notificationChannel) // Register the channel with the system. notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(notificationChannel) } notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val intent = Intent(this, MainActivity3::class.java) val pendingIntent = PendingIntent.getActivity(this, 2, intent, PendingIntent.FLAG_UPDATE_CURRENT) builder = NotificationCompat.Builder(this, channelId).setContentTitle("My notification").setContentText("Much longer text that cannot fit one line...").setSmallIcon(R.drawable.ic_launcher_background).setPriority(NotificationCompat.PRIORITY_DEFAULT).setContentIntent(pendingIntent).setAutoCancel(true) Mobile Computing and App Development notificationManager.notify(1234,builder.build()) } override fun onStart() { super.onStart() Toast.makeText(applicationContext,"On Start Called", Toast.LENGTH_LONG).show(); } override fun onResume() { super.onResume() Toast.makeText(applicationContext,"On Resume Called", Toast.LENGTH_LONG).show(); } override fun onStop() { super.onStop() Toast.makeText(applicationContext,"On onStop method Called", Toast.LENGTH_LONG).show(); } fun onClickSubmit(view: View) { val msg = "Hello from Main Activity" // Create the text message with a string. val sendIntent = Intent().apply { action = Intent.ACTION_SEND putExtra(Intent.EXTRA_TEXT, msg) type = "text/plain" } val callIntent = Intent(Intent.ACTION_DIAL,Uri.parse("tel:9898989898"))//.apply {data = Uri.parse("tel:9898989898")} val mapIntentn = Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=Ahmedabad, Gujarat")) val webIntent = Intent(Intent.ACTION_VIEW, Uri.parse("https://www.android.com")) val intent = Intent(applicationContext, MainActivity2::class.java) intent.putExtra("msg", msg); intent.putExtra("msg2", "hello"); Mobile Computing and App Development // Try to invoke the intent. try { startActivity(sendIntent) } catch (e: ActivityNotFoundException) { // Define what your app should do if no activity can handle the intent. Toast.makeText(applicationContext,"Activity Not Found", Toast.LENGTH_LONG).show(); } Toast.makeText(applicationContext,"btn clicked", Toast.LENGTH_LONG).show(); } //if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) //{ // ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CALL_PHONE) , 1); //} Step4: NotificationView.kt import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import android.widget.Toast; public class NotificationView extends AppCompatActivity { TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_notification_view); textView = findViewById(R.id.textView); //getting the notification message String message=getIntent().getStringExtra("message"); textView.setText(message); } } Mobile Computing and App Development 2.7 Invoking Built-in Applications In Android, you can invoke built-in applications using Intents. Intents are a fundamental part of the Android system that allows components (such as activities, services, and broadcast receivers) to request actions or interactions with other components. There are two types of intents: implicit and explicit. 1.Implicit Intent Using implicit Intent, components can’t be specified. An action to be performed is declared by implicit intent. Then android operating system will filter out components that will respond to the action. For Example, In the above example, no component is specified, instead, an action is performed i.e. a webpage is going to be opened. As you type the name of your desired webpage and click on the ‘CLICK’ button. Your webpage is opened. Step by Step Implementation Creating an Android App to Open a Webpage Using Implicit Intent Step 1: Create a New Project in Android Studio Step 2: Working with the XML Files Mobile Computing and App Development Next, go to the activity_main.xml file, which represents the UI of the project. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail. Syntax: android:id="@+id/id_name" XML Step 3: Working with the MainActivity File Now, we will create the Backend of the App. For this, Open the MainActivity file and instantiate the component (Button) created in the XML file using the findViewById() method. This method binds the created object to the UI Components with the help of the assigned ID. Syntax: ComponentType object = (ComponentType) findViewById(R.id.IdOfTheComponent); Kotlin import android.content.Intent import android.net.Uri import android.os.Bundle import android.widget.Button import android.widget.EditText import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { lateinit var editText: EditText override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Mobile Computing and App Development setContentView(R.layout.activity_main) editText = findViewById(R.id.editText) } fun search() { val url = editText.text.toString() val urlIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) startActivity(urlIntent) }} 2.Explicit Intent Using explicit intent any other component can be specified. In other words, the targeted component is specified by explicit intent. So only the specified target component will be invoked. For Example: In the above example, There are two activities (FirstActivity, and SecondActivity). When you click on the ‘GO TO OTHER ACTIVITY’ button in the first activity, then you move to the second activity. When you click on the ‘GO TO HOME ACTIVITY’ button in the second activity, then you move to the first activity. This is getting done through Explicit Intent. Mobile Computing and App Development Step by Step Implementation How to create an Android App to move to the next activity using Explicit Intent(with Example) Step 1: Create a New Project in Android Studio Step 2: Working with the activity_main.xml File Next, go to the activity_main.xml file, which represents the UI of the project. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail. Syntax: android:id="@+id/id_name" XML Step 3: Working with the MainActivity File Now, we will create the Backend of the App. For this, Open the MainActivity file and instantiate the component (Button, TextView) created in the XML file using the findViewById() method. This method binds the created object to the UI Components with the help of the assigned ID. Syntax: ComponentType object = (ComponentType) findViewById(R.id.IdOfTheComponent); Intent i = new Intent(getApplicationContext(), ); startActivity(i); Kotlin import android.content.Intent import android.os.Bundle Mobile Computing and App Development import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main)} fun newsScreen() { val i = Intent(applicationContext, MainActivity2::class.java) startActivity(i); } } Step 4: Working with the activity_main2.xml File Now we have to create a second activity as a destination activity. The steps to create the second activity are File > new > Activity > Empty Activity. Mobile Computing and App Development Next, go to the activity_main2.xml file, which represents the UI of the project. Below is the code for the activity_main2.xml file. Comments are added inside the code to understand the code in more detail. XML Mobile Computing and App Development Step 5: Working with the MainActivity2 File Now, we will create the Backend of the App. For this, Open the MainActivity file and instantiate the component (Button, TextView) created in the XML file using the findViewById() method. This method binds the created object to the UI Components with the help of the assigned ID. Syntax: ComponentType object = (ComponentType) findViewById(R.id.IdOfTheComponent); Intent i = new Intent(getApplicationContext(), ); startActivity(i); Kotlin import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity class MainActivity2 : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { Mobile Computing and App Development super.onCreate(savedInstanceState) setContentView(R.layout.activity_main2) } fun homeScreen() { val i = Intent(applicationContext, MainActivity::class.java) startActivity(i) } } Mobile Computing and App Development UNIT-3 Working with Views 3.1 Working with View Groups A ViewGroup is a special view that can contain other views. The ViewGroup is the base class for Layouts in android, like LinearLayout , RelativeLayout , FrameLayout etc. In other words, ViewGroup is generally used to define the layout in which views(widgets) will be set/arranged/listed on the android screen. ViewGroups acts as an invisible container in which other Views and Layouts are placed. Yes, a layout can hold another layout in it, or in other words a ViewGroup can have another ViewGroup in it.View: A View is defined as the user interface which is used to create interactive UI components such as TextView, ImageView, EditText, RadioButton, etc., and is responsible for event handling and drawing. They are Generally Called Widgets. ViewGroup: A ViewGroup act as a base class for layouts and layouts parameters that hold other Views or ViewGroups and to define the layout properties. They are Generally Called layouts. The Android framework will allow us to use UI elements or widgets in two ways: Use UI elements in the XML file Create elements in the Kotlin file dynamically 3.2 Designing different types of Views Android WebView: WebView is a browser that is used to display the web pages in our activity layout. Android ListView: ListView is a ViewGroup, used to display scrollable lists of items in a single column. Android GridView: GridView is a ViewGroup that is used to display a scrollable list of items in a grid view of rows and columns. Mobile Computing and App Development Android RecyclerView: A RecyclerView is an advanced version of ListView with improved performance. Android CardView: CardView is a new widget in Android that can be used to display any sort of data by providing a rounded corner layout along with a specific elevation. Android TextView: Android TextView is simply a view that are used to display the text to the user and optionally allow us to modify or edit it. Android Button: A Button is a user interface that is used to perform some action when clicked or tapped. Android RadioGroup: RadioGroup class of Kotlin programming language is used to create a container which holds multiple RadioButtons. Android ToggleButton: ToggleButton is just like a switch containing two states either ON or OFF which is represented using boolean values true and false respectively. Android CheckBox: A CheckBox is a special kind of button in Android which has two states either checked or unchecked. ListView: Android ListView is a ViewGroup which is used to display the list of items in multiple rows and contains an adapter which automatically inserts the items into the list. The main purpose of the adapter is to fetch data from an array or database and insert each item that placed into the list for the desired result. So, it is main source to pull data from strings.xml file which contains all the required strings in Kotlin or xml files. Android Adapter: Adapter holds the data fetched from an array and iterates through each item in data set and generates the respective views for each item of the list. So, we can say it act as an intermediate between the data sources and adapter views such as ListView, Gridview. Different Types of Adapter: ArrayAdapter: It always accepts an Array or List as input. We can store the list items in the strings.xml file also. CursorAdapter: It always accepts an instance of cursor. Mobile Computing and App Development SimpleAdapter: It mainly accepts a static data defined in the resources like array or database. BaseAdapter: It is a generic implementation for all three adapter types and it can be used in the views according to our requirements. activity_main.xml file GridView: A Grid View is a type of adapter view that is used to display the data in the grid layout format. For setting the data to the grid view adapter is used with the help of the setAdapter() method. This adapter helps to set the data from the database or array list to the items of the grid view. In this article, we will take a look at How to implement Grid View in Android using Kotlin language. Working with the activity_main.xml file: RecyclerView: A RecyclerView is an advanced version of ListView with improved performance. When you have a long list of items to show you can use RecyclerView. It has the ability to reuse its views. In RecyclerView when the View goes out of the screen or not visible to the user it won’t destroy it, it will reuse these views. This feature helps in reducing power consumption and providing more responsiveness to the application. onCreateViewHolder(): This function sets the views to display the items. onBindViewHolder(): This function is used to bind the list items to our widgets such as TextView, ImageView, etc. getItemCount(): It returns the count of items present in the list. Working with XML: Mobile Computing and App Development CardView: CardView is a new widget in Android that can be used to display any sort of data by providing a rounded corner layout along with a specific elevation. CardView is the view that can display views on top of each other. The main usage of CardView is that it helps to give a rich feel and look to the UI design. This widget can be easily seen in many different Android Apps. CardView can be used for creating items in listview or inside Recycler View. The best part about CardView is that it extends Framelayout and it can be displayed on all platforms of Android. Some important attributes of Cardview are : 1.cardBackgroundColor : Used for setting up the background-color of the card. 2.cardElevation : Defines the elevation (the process of moving to a higher place or more important position) of the card. It’s value should not be quite large else the design may not look good. 3.cardCornerRadius : It sets radius around the corners of the card. More the value of this attribute more circular the edges would appear in the card. 4.cardUseCompactPadding : It has two values true and false. By default, the cardview is set to (0,0) top left corner of the screen. And if this attribute is set to true then the card will set padding for itself so that our UI looks good. This case is helpful in the scenarios when our gravity is not set to center or any other parameters. Working with XML: Mobile Computing and App Development Mobile Computing and App Development TextView: Android TextView is simply a view that are used to display the text to the user and optionally allow us to modify or edit it. Different attributes of TextView: Attributes Description ndroid:text Sets text of the Textview android:id Gives a unique ID to the Textview android:cursorVisible Use this attribute to make cursor visible or invisible. Default value is visible. android:drawableBottom Sets images or other graphic assets to below of the Textview. android:drawableEnd Sets images or other graphic assets to end of Textview. android:drawableLeft Sets images or other graphic assets to left of Textview. android:drawablePadding Sets padding to the drawable(images or other graphic assets) in the Textview. android:autoLink This attribute is used to automatically detect url or emails and show it as clickable link. android:autoText Automatically correct spelling errors in text of the Textview. android:capitalize It automatically capitalize whatever the user types in the Textview. android:drawableRight Sets drawables to right of text in the Textview. android:drawableStart Sets drawables to start of text in the Textview. android:drawableTop Sets drawables to top of text in the Textview. android:ellipsize Use this attribute when you want text to be ellipsized if it is longer than the Textview width. android:ems Sets width of the Textview in ems. android:gravity We can align text of the Textview vertically or horizontally or both. android:height Use to set height of the Textview. android:hint Use to show hint when there is no text. android:inputType Use to set input type of the Textview. It can be Number, Password, Phone etc. Mobile Computing and App Development android:lines Use to set height of the Textview by number of lines. android:maxHeight Sets maximum height of the Textview. android:minHeight Sets minimum height of the Textview. android:maxLength Sets maximum character length of the Textview. android:maxLines Sets maximum lines Textview can have. android:minLines Sets minimum lines Textview can have. android:maxWidth Sets maximum width Textview can have. android:minWidth Sets minimum lines Textview can have. android:textAllCaps Show all texts of the Textview in capital letters. android:textColor Sets color of the text. android:textSize Sets font size of the text. android:textStyle Sets style of the text. For example, bold, italic, bolditalic. android:typeface Sets typeface or font of the text. For example, normal, sans, serif etc android:width Sets width of the TextView. activity_main.xml file; Mobile Computing and App Development Button: A Button is a user interface that is used to perform some action when clicked or tapped. It is a very common widget in Android and developers often use it. XML Attributes of Button: XML Attributes Description android:id Used to specify the id of the view. android:text Used to the display text of the button. android:textColor Used to the display color of the text. Used to the display size of the text. android:textSize Used to the display style of the text like Bold, Italic, etc. android:textStyle android:textAllCaps Used to display text in Capital letters. android:background Used to set the background of the view. android:padding Used to set the padding of the view. Mobile Computing and App Development XML Attributes Description android:visibility Used to set the visibility of the view. android:gravity Used to specify the gravity of the view like center, top, bottom, etc activity_main.xml file : RadioGroup: RadioGroup class of Kotlin programming language is used to create a container which holds multiple RadioButtons. The RadioGroup class is beneficial for placing a set of radio buttons inside it because this class adds multiple-exclusion scope feature to the radio buttons. This feature assures that the user will be able to check only one of the radio buttons among all which belongs to a RadioGroup class. If the user checks another radio button, the RadioGroup class unchecks the previously checked radio button. XML attributes of RadioGroup: XML Attributes Description android:id To uniquely identify the RadioGroup android:background To set a background colour android:onClick A method to perform certain action when RadioGroup is clicked android:onClick It’s a name of the method to invoke when the radio button clicked. android:visibility Used to control the visibility i.e., visible, invisible or gone android:layout_width To set the width android:layout_height To set the height Mobile Computing and App Development android:contentDescription To give a brief description of the view XML Attributes Description android:checkedButton Stores id of child radio button that needs to be checked by default within this radio gr