Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore CU-MCA-SEM-VI-Advanced mobile application development

CU-MCA-SEM-VI-Advanced mobile application development

Published by Teamlease Edtech Ltd (Amita Chitroda), 2021-11-02 12:53:52

Description: CU-MCA-SEM-VI-Advanced mobile application development

Search

Read the Text Version

MASTER OF COMPUTER APPLICATION SEMESTER-VI ADVANCED MOBILE APPLICATION DEVELOPMENT

CHANDIGARH UNIVERSITY Institute of Distance and Online Learning SLM Development Committee Prof. (Dr.) H.B. Raghvendra Vice- Chancellor, Chandigarh University, Gharuan, Punjab:Chairperson Prof. (Dr.) S.S. Sehgal Registrar Prof. (Dr.) B. Priestly Shan Dean of Academic Affairs Dr. Nitya Prakash Director – IDOL Dr. Gurpreet Singh Associate Director –IDOL Advisors& Members of CIQA –IDOL Prof. (Dr.) Bharat Bhushan, Director – IGNOU Prof. (Dr.) Majulika Srivastava, Director – CIQA, IGNOU Editorial Committee Prof. (Dr) Nilesh Arora Dr. Ashita Chadha University School of Business University Institute of Liberal Arts Dr. Inderpreet Kaur Prof. Manish University Institute of Teacher Training & University Institute of Tourism & Hotel Management Research Dr. Manisha Malhotra Dr. Nitin Pathak University Institute of Computing University School of Business © No part of this publication should be reproduced, stored in a retrieval system, or transmitted in any formor by any means, electronic, mechanical, photocopying, recording and/or otherwise without the prior written permission of the authors and the publisher. SLM SPECIALLY PREPARED FOR CU IDOL STUDENTS 2 CU IDOL SELF LEARNING MATERIAL (SLM)

First Published in 2021 All rights reserved. No Part of this book may be reproduced or transmitted, in any form or by any means, without permission in writing from Chandigarh University. Any person who does any unauthorized act in relation to this book may be liable to criminal prosecution and civil claims for damages. This book is meant for educational and learning purpose. The authors of the book has/have taken all reasonable care to ensure that the contents of the book do not violate any existing copyright or other intellectual property rights of any person in any manner whatsoever. In the event the Authors has/ have been unable to track any source and if any copyright has been inadvertently infringed, please notify the publisher in writing for corrective action. CONTENT Unit - 1: Basics Of Android................................................................................................... 5 3 CU IDOL SELF LEARNING MATERIAL (SLM)

Unit - 2: Intent & Filters...................................................................................................... 18 Unit - 3: Andriod Tab Activities.......................................................................................... 35 Unit - 4: Data Storage.......................................................................................................... 51 Unit - 5: Database Connectivity........................................................................................... 75 Unit - 6: Online Data Parsing .............................................................................................. 87 Unit - 7: Android Multimedia............................................................................................ 107 Unit - 8: Telephony Api .................................................................................................... 125 Unit - 9: Sms And E-Mail Connectivity............................................................................. 150 Unit - 10: Device Connectivity.......................................................................................... 181 Unit - 11: Maps And Other Services.................................................................................. 200 Unit - 12: Android Application Deployment And Camera ................................................. 222 4 CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT - 1:BASICS OF ANDROID STRUCTURE 1.0 Learning Objectives 1.1 Introduction 1.2 Coding 1.3 Security Tips 1.4 Storing Data 1.5 Using Networking 1.6 Android Permission 1.7 Intents 1.8 Broadcast Receiver 1.9 Activities 1.10 Content Providers 1.11 Files 1.12 Summary 1.13 Keywords 1.14 Learning Activity 1.15 Unit End Questions 1.16 References 1.0 LEARNING OBJECTIVES After studying this unit, you will be able to:  State and explain various security tips related to android.  Explain the networking used in android  Explain the concept of storing in internal and external memory  List the different files associated with android 1.1 INTRODUCTION Android is an open-source, Linux-based operating system for mobile devices such as smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by Google, and other companies. Android offers a unified approach to application 5 CU IDOL SELF LEARNING MATERIAL (SLM)

development for mobile devices which means developers need to develop only for Android, and their applications should be able to run on different devices powered by Android. Google Inc. sponsored the project at initial stages and in the year 2005, it acquired the whole company. In September 2008, the first Android-powered device launched in the market. The source code for Android is available under free and open source software licenses. Google publishes most of the code under the Apache License version 2.0 and the rest, Linux kernel changes, under the GNU General Public License version 2.Google uses many of its own tools and libraries to help the work of developers, and these are all collected in the Android Software Development Toolkit (SDK). The modules in it contain different tools (Build- Tools, Platform-Tools, Debug-Tool, and Emulator etc.). With the emulator, we can test how an app works and gets displayed on Android devices (cell phones, tablets etc.). Google released its own Integrated Development Environment. (IDE) for this called Android Studio. There are many special tools built-in to Android Studio besides an editor. Once developed, Android applications can be packaged easily, posted on website, transferred on mobile through network and distributed through app-stores such as iOS app store, Google Play, Amazon Appstore, and Samsung Galaxy Apps etc. 1.2CODING Java is one of the most popular and widely used languages with an enormous codebase, many accessible learning materials, and experienced programmers. Most Android applications run in Java, and parts of the Android operating system were even written in Java, the rest being written in C++. With time, this emphasis on Java may shift because Google started supporting Kotlin. Developing the Android Application using Kotlin is preferred by Google, as Kotlin is made an official language for Android Development, which is developed and maintained by JetBrains. Previously before the Java is considered the official language for Android Development. Kotlin is made official for Android Development in Google I/O 2017. 1.3SECURITY TIPS Android has built-in security features that significantly reduce the frequency and impact of application security issues. The system is designed so that you can typically build your apps with the default system and file permissions and avoid difficult decisions about security. The following core security features help you build secure apps:  The Android Application Sandbox, which isolates your app data and code execution from other apps.  An application framework with robust implementations of common security functionality such as cryptography, permissions, and secure IPC. 6 CU IDOL SELF LEARNING MATERIAL (SLM)

 Technologies like ASLR, NX, ProPolice, safe_iop, OpenBSD dlmalloc, OpenBSD calloc, and Linux mmap_min_addr to mitigate risks associated with common memory management errors.  An encrypted file system that can be enabled to protect data on lost or stolen devices.  User-granted permissions to restrict access to system features and user data.  Application-defined permissions to control application data on a per-app basis. It is important that you be familiar with the Android security best practices in this document. Following these practices as general coding habits reduces the likelihood of inadvertently introducing security issues that adversely affect your users. 1.4STORING DATA The most common security concern for an application on Android is whether the data that you save on the device is accessible to other apps. There are three fundamental ways to save data on the device:  Internal storage.  External storage.  Content providers. Use internal storage: By default, files that you create on internal storage are accessible only to your app. Android implements this protection, and it's sufficient for most applications. Generally, avoid the MODE_WORLD_WRITEABLE or MODE_WORLD_READABLE modes for IPC files because they do not provide the ability to limit data access to particular applications, nor do they provide any control of data format. If you want to share your data with other app processes, instead consider using a content provider, which offers read and write permissions to other apps and can make dynamic permission grants on a case-by-case basis. To provide additional protection for sensitive data, you can encrypt local files using the Security library. This measure can provide protection for a lost device without file system encryption. Use external storage: Files created on external storage, such as SD cards, are globally readable and writable. Because external storage can be removed by the user and also modified by any application, don't store sensitive information using external storage. To read and write files on external storage in a more secure way, consider using the Security library, which provides the Encrypted File class. 7 CU IDOL SELF LEARNING MATERIAL (SLM)

You should perform input validation when handling data from external storage as you would with data from any untrusted source. You should not store executables or class files on external storage prior to dynamic loading. If your app does retrieve executable files from external storage, the files should be signed and cryptographically verified prior to dynamic loading. Use content providers: Content providers offer a structured storage mechanism that can be limited to your own application or exported to allow access by other applications. If you do not intend to provide other applications with access to your Content Provider, mark them as android: exported=false in the application manifest. Otherwise, set the android: exported attribute to true to allow other apps to access the stored data. When creating a Content Provider that is exported for use by other applications, you can specify a single permission for reading and writing, or you can specify distinct permissions for reading and writing. You should limit your permissions to those required to accomplish the task at hand. Keep in mind that it’s usually easier to add permissions later to expose new functionality than it is to take them away and impact existing users. If you are using a content provider for sharing data between only your own apps, it is preferable to use the android: protection Level attribute set to signature protection. Signature permissions do not require user confirmation, so they provide a better user experience and more controlled access to the content provider data when the apps accessing the data are signed with the same key. When accessing a content provider, use parameterized query methods such as query (), update (), and delete() to avoid potential SQL injection from untrusted sources. Note that using parameterized methods is not sufficient if the selection argument is built by concatenating user data prior to submitting it to the method. Don't have a false sense of security about the write permission. The write permission allows SQL statements that make it possible for some data to be confirmed using creative WHERE clauses and parsing the results. For example, an attacker might probe for the presence of a specific phone number in a call log by modifying a row only if that phone number already exists. If the content provider data has predictable structure, the write permission may be equivalent to providing both reading and writing. 1.5 USING NETWORKING Network transactions are inherently risky for security, because they involve transmitting data that is potentially private to the user. People are increasingly aware of the privacy concerns of a mobile device, especially when the device performs network transactions, so it's very 8 CU IDOL SELF LEARNING MATERIAL (SLM)

important that your app implement all best practices toward keeping the user's data secure at all times. Use IP networking: Networking on Android is not significantly different from other Linux environments. The key consideration is making sure that appropriate protocols are used for sensitive data, such as HttpsURLConnection for secure web traffic. You should use HTTPS over HTTP anywhere that HTTPS is supported on the server, because mobile devices frequently connect on networks that are not secured, such as public Wi-Fi hotspots. Authenticated, encrypted socket-level communication can be easily implemented using the SSLSocket class. Given the frequency with which Android devices connect to unsecured wireless networks using Wi-Fi, the use of secure networking is strongly encouraged for all applications that communicate over the network. Some applications use local host network ports for handling sensitive IPC. You should not use this approach because these interfaces are accessible by other applications on the device. Instead, use an Android IPC mechanism where authentication is possible, such as with a Service. Binding to INADDR_ANY is worse than using loopback because then your application may receive requests from anywhere. Make sure that you don't trust data downloaded from HTTP or other insecure protocols. This includes validation of input in Web View and any responses to intents issued against HTTP. Use telephony networking: The SMS protocol was primarily designed for user-to-user communication and is not well- suited for apps that want to transfer data. Due to the limitations of SMS, you should use Google Cloud Messaging (GCM) and IP networking for sending data messages from a web server to your app on a user device. Beware that SMS is neither encrypted nor strongly authenticated on either the network or the device. In particular, any SMS receiver should expect that a malicious user may have sent the SMS to your application. Don't rely on unauthenticated SMS data to perform sensitive commands. Also, you should be aware that SMS may be subject to spoofing and/or interception on the network. On the Android-powered device itself, SMS messages are transmitted as broadcast intents, so they may be read or captured by other applications that have the READ_SMS permission. 1.6 ANDROID PERMISSIONS Because Android sandboxes applications from each other, applications must explicitly share resources and data. They do this by declaring the permissions they need for additional capabilities not provided by the basic sandbox, including access to device features such as the camera. 9 CU IDOL SELF LEARNING MATERIAL (SLM)

Request permissions: You should minimize the number of permissions that your app requests. Restricting access to sensitive permissions reduces the risk of inadvertently misusing those permissions, improves user adoption, and makes your app less vulnerable for attackers. Generally, if a permission is not required for your app to function, don't request it. If there is a feature that the app can't run without, declare it using a <uses-feature> element in the manifest file. If it's possible to design your application in a way that does not require any permissions, that is preferable. For example, rather than requesting access to device information to create a unique identifier, create a GUID for your application (see the section about handling user data). Or, rather than using external storage (which requires permission), store data on the internal storage. In addition to requesting permissions, your application can use the <permission> element to protect IPC that is security sensitive and is exposed to other applications, such as a Content Provider. In general, we recommend using access controls other than user confirmed permissions where possible because permissions can be confusing for users. For example, consider using the signature protection level on permissions for IPC communication between applications provided by a single developer. Do not leak permission-protected data. This occurs when your app exposes data over IPC that is available only because your app has permission to access that data. The clients of your app's IPC interface may not have that same data-access permission. More details on the frequency and potential effects of this issue appear in the research paper Permission Re- Delegation: Attacks and Defenses, published at USENIX. Create permissions: Generally, you should strive to define as few permissions as possible while satisfying your security requirements. Creating a new permission is relatively uncommon for most applications, because the system-defined permissions cover many situations. Where appropriate, perform access checks using existing permissions. If you must create a new permission, consider whether you can accomplish your task with a signature protection level. Signature permissions are transparent to the user and allow access only by applications signed by the same developer as the application performing the permission check. If the new permission is still required, it's declared in the app manifest using the <permission> element. Apps that wish to use the new permission can reference it by each adding a <uses-permission> element in their respective manifest files. You can also add permissions dynamically by using the add Permission () method. If you create a permission with the dangerous protection level, there are a number of complexities that you need to consider: 10 CU IDOL SELF LEARNING MATERIAL (SLM)

The permission must have a string that concisely expresses to a user the security decision they are required to make.  The permission string must be localized to many different languages.  Users may choose not to install an application because a permission is confusing or perceived as risky.  Applications may request the permission when the creator of the permission has not been installed.  Each of these poses a significant nontechnical challenge for you as the developer while also confusing your users, which is why we discourages the use of the dangerous permission level. 1.7 INTENTS Android Intent is the message that is passed between components such as activities, content providers, broadcast receivers, services etc. The dictionary meaning of intent is intention or purpose. So, it can be described as the intention to do action. The labeled intent is the subclass of android.content.Intent class. Android intents are mainly used to:  Start the service  Launch an activity  Display a web page  Display a list of contacts  Broadcast a message  Dial a phone call etc. 1.8 BROADCAST RECEIVER Broadcast Receivers simply respond to broadcast messages from other applications or from the system. For example, applications can also initiate broadcasts to let other applications know that some data has been downloaded to the device and is available for them to use, so this is broadcast receiver who will intercept this communication and will initiate appropriate action. A broadcast receiver is implemented as a subclass of Broadcast Receiver class and each message is broadcasted as an Intent object. Public class My Receiver extends Broadcast Receiver { } 11 CU IDOL SELF LEARNING MATERIAL (SLM)

1.9 ACTIVITIES They dictate the UI and handle the user interaction to the smartphone screen. An activity represents a single screen with a user interface. For example, an email application might have one activity that shows a list of new emails, another activity to compose an email, and one for reading emails. If an application has more than one activity, then one of them should be marked as the activity that is presented when the application is launched. An activity is implemented as a subclass of Activity class as follows: Public class Main Activity extends Activity { // code to be performed in activity } Android Activity Lifecycle is controlled by 7 methods of android.app.Activity class. The Android Activity is the subclass of ContextThemeWrapper class Figure 1.1 An activity is the single screen in android. It is like window or frame of Java. By the help of activity, you can place all your UI components or widgets in a single screen. The 7 lifecycle method of Activity describes how activity will behave at different states. Method Description onCreate() called when activity is first created. onStart () called when activity is becoming visible to the user. onResume() called when activity will start interacting with the user. onPause() called when activity is not visible to the user. 12 CU IDOL SELF LEARNING MATERIAL (SLM)

onStop() called when activity is no longer visible to the user. onRestart() called after your activity is stopped, prior to start. onDestroy() called before the activity is destroyed. Figure 1.2 State Transition Diagram for Activity Life Cycle 1.10 CONTENT PROVIDERS A content provider component supplies data from one application to others on request. Such requests are handled by the methods of the Content Resolver class. The data may be stored in the file system, the database or somewhere else entirely. A content provider is implemented as a subclass of Content Provider class and must implement a standard set of APIs that enable other applications to perform transactions. Public class MyContentProvider extends Content Provider { } 13 CU IDOL SELF LEARNING MATERIAL (SLM)

1.11FILES A brief overview few of the important application files The main activity file: The main activity code is a Java file MainActivity.java. This is the actual application file which ultimately gets converted to a Dalvik executable and runs your application. Manifest file whatever component you develop as a part of your application, you must declare all its components in a manifest file called AndroidManifest.xml which resides at the root of the application project directory. This file works as an interface between Android OS and your application, so if you do not declare your component in this file, then it will not be considered by the OS. The strings.xml: The strings.xml file is located in the res/values folder and it contains all the text that your application uses. For example, the names of buttons, labels, default text, and similar types of strings go into this file. This file is responsible for their textual content. The R File: The gen/com.example.helloworld/R.java file is the glue between the activity Java files likeMainActivity.java and the resources like strings.xml. It is an automatically generated file and you should not modify the content of the R.java file. The Layout file: The activity_main.xml is a layout file available in res/layout directory that is referenced by your application when building its interface. You will modify this file very frequently to change the layout of your application 1.12 SUMMARY  Security features that helps to build Android is discussed in detail.  Three fundamental ways to store data on the devices : i. Internal storage. ii. External storage. iii. Content providers.  The permission must have a string that concisely expresses to a user the security decision  Android intents are mainly used to: i. Start the service ii. Launch an activity iii. Display a web page iv. Display a list of contacts v. Broadcast a message  There are 7 lifecycle method of Activity describes how activity will behave at different states. 14 CU IDOL SELF LEARNING MATERIAL (SLM)

1.13 KEYWORDS  CODING-the process of creating instructions for computers using programming languages. Computer code is used to program the websites, apps, and other technologies we interact with every day.  NETWORK SECURITY –It is any activity designed to protect the usability and integrity of your network and data. It includes both hardware and software technologies. It targets a variety of threats. It stops them from entering or spreading on your network. Effective network security manages access to the network.  Telephony– Telephony describes the technology that allows people to interact and communicate across long distances through the electronic transmission of voice, fax or other information.  BROADCAST – Broadcasting is the distribution of audio or video content to a dispersed audience via any electronic mass communications medium,  Files – A file is the common storage unit in a computer, and all programs and data are \"written\" into a file and \"read\" from a file. A folder holds one or more files, and a folder can be empty until it is filled. A folder can also contain other folders, and there can be many levels of folders within folders. 1.14 LEARNING ACTIVITY 1. Explain the transition diagram for activity life cycle ___________________________________________________________________________ ___________________________________________________________________________ 2. Explain importance of file in android ___________________________________________________________________________ ___________________________________________________________________________ 1.15 UNIT END QUESTIONS A. Descriptive Questions 15 Short Questions 1. Explain intent in reference to android. 2. Explain how permission is created in android. 3. What is telephony network? 4. Explain IP networking. 5. What are the security features that help you build secure applications? CU IDOL SELF LEARNING MATERIAL (SLM)

Long Questions 16 1. Explain in detail the concept of storing data in android. 2. What is networking in context of mobile programming? 3. How is permission requested and created in mobile programming? 4. Explain the concept of activities in mobile programming. 5. Explain file handling in detail. B. Multiple Choice Questions 1. Manifest file works as an interface between _______ and application a. Android File b. Android OS c. Memory d. All of these 2. The strings.xml file is located in the ________ folder a. res/values b. core c. string d. external 3. There are _____ life cycle method of activity a. 6 b. 7 c. 5 d. 9 4. A broadcast receivers simply respond to ______ messages. a. broadcast b. individual c. live d. group 5. The SMS protocol was primarily designed for _____ communication a. simplex b. duplex c. user-to-user d. direct CU IDOL SELF LEARNING MATERIAL (SLM)

Answers 1-b, 2-a, 3-b, 4-a, 5-c 1.16REFERENCES References book  Wei - Meng Le, “Beginning Android 4 Applications Development”, John Wiley & Sons, Inc., 2012.  Reto Meier, “Professional Android 4 Applications Development”, John Wiley & Sons, Inc., 2012  Zigurd Mednieks, Laird Dornin, Blake Meike G, and Masumi Nakamura, “Programming Android”, O’Reily books, 2011. Website  https://developer.android.com/training/articles/security-tips  https://www.javatpoint.com/  https://developer.android.com/reference/android/media/MediaRecorder  https://android-developers.googleblog.com/2020/02/Android-11-developer- preview.html 17 CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT - 2: INTENT & FILTERS STRUCTURE 2.0 Learning Objectives 2.1 Introduction 2.2 Explicit Intent 2.3 Implicit Intent 2.4 Service Life Cycle 2.5 Option Menu 2.6 Content Menu 2.7 Popup Menu 2.8 Android Alarm Manager 2.9 Summary 2.10 Keywords 2.11 Learning Activity 2.12 Unit End Questions 2.13 References 2.0 LEARNING OBJECTIVES After studying this unit, you will be able to:  Explain the concept of Intent.  Explain the menu option of android.  Create android alarm manager.  Explain service life cycle of android. 2.1 INTRODUCTION An Intent is a messaging object you can use to request an action from another app component. Although intents facilitate communication between components in several ways, there are three fundamental use cases: Starting an activity: An Activity represents a single screen in an app. You can start a new instance of an Activity by passing an Intent to start Activity (). The Intent describes the activity to start and carries any necessary data. 18 CU IDOL SELF LEARNING MATERIAL (SLM)

If you want to receive a result from the activity when it finishes, call startActivityForResult (). Your activity receives the result as a separate Intent object in your activity's onActivityResult () callback. For more information, see the Activities guide. Starting a service: A Service is a component that performs operations in the background without a user interface. With Android 5.0 (API level 21) and later, you can start a service with Job Scheduler. For more information about Job Scheduler, see its API-reference documentation. For versions earlier than Android 5.0 (API level 21), you can start a service by using methods of the Service class. You can start a service to perform a one-time operation (such as downloading a file) by passing an Intent to start Service (). The Intent describes the service to start and carries any necessary data. If the service is designed with a client-server interface, you can bind to the service from another component by passing an Intent to bind Service (). For more information, see the Services guide. Delivering a broadcast: A broadcast is a message that any app can receive. The system delivers various broadcasts for system events, such as when the system boots up or the device starts charging. You can deliver a broadcast to other apps by passing an Intent to send Broadcast () or sendOrderedBroadcast (). Intent types: There are two types of intents: Explicit intents specify which application will satisfy the intent, by supplying either the target app's package name or a fully-qualified component class name. You'll typically use an explicit intent to start a component in your own app, because you know the class name of the activity or service you want to start. For example, you might start a new activity within your app in response to a user action, or start a service to download a file in the background. Implicit intents do not name a specific component, but instead declare a general action to perform, which allows a component from another app to handle it. For example, if you want to show the user a location on a map, you can use an implicit intent to request that another capable app show a specified location on a map. 2.2 EXPLICIT INTENTS It specify which application will satisfy the intent, by supplying either the target app's package name or a fully-qualified component class name. You'll typically use an explicit intent to start a component in your own app, because you know the class name of the activity 19 CU IDOL SELF LEARNING MATERIAL (SLM)

or service you want to start. For example, you might start a new activity within your app in response to a user action, or start a service to download a file in the background. Explicit Intent Syntax: Intent i = new Intent (getApplicationContext(), ActivityTwo.class); start Activity(i); Example explicit intent: If you built a service in your app, named DownloadService, designed to download a file from the web, you can start it with the following code: // Executed in an Activity, so 'this' is the Context // The fileUrl is a string URL, such as \"http://www.example.com/image.png\" Intent downloadIntent = new Intent(this, DownloadService.class); downloadIntent.setData(Uri.parse(fileUrl)); startService(downloadIntent); 2.3 IMPLICIT INTENTS It does not name a specific component, but instead declare a general action to perform, which allows a component from another app to handle it. For example, if you want to show the user a location on a map, you can use an implicit intent to request that another capable app show a specified location on a map. When you use an implicit intent, the Android system finds the appropriate component to start by comparing the contents of the intent to the intent filters declared in the manifest file of other apps on the device. If the intent matches an intent filter, the system starts that component and delivers it the Intent object. If multiple intent filters are compatible, the system displays a dialog so the user can pick which app to use. For example, you may write the following code to view the webpage. Intent intent=new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(\"http://www.javatpoint.com\")); startActivity(intent); 20 CU IDOL SELF LEARNING MATERIAL (SLM)

2.4 SERVICE LIFE CYCLE A service is a application component that run in the background to perform long running operation without needing to interact with the user. Service can run in the background indefinitely, even if component that started the service is destroyed. A service run in the main thread of the application instance.It does’t create its own thread. Service always performing a single operation and stop itself one intended task is completed. Service can essentially take two forms: Started service-A service is started when the application is (like Activity) start it by calling startService() method.It is stopped by stopService() method.The service can stop itself by calling the stopSelf() method. Bound service-A service is bound when an application component bind to its by calling bindService() method. The client can unbind the service by calling the unBindService() method. Figure 2.1 Service Life Cycle 21 CU IDOL SELF LEARNING MATERIAL (SLM)

onStartCommand() This method is called when the service be started,by calling startService().onece this method executes, the service is started and can run in the background indefinitely onBind() This metod is called when another component wants to bind with the service by calling bindService(). onUnbind() This method is called when the all clients have disconnected from a particular interface. onCreate() This method is called while the service is first created.Here all the service initialization is done.This method is never called again. onDestroy() The system call this method when the service is no longer used and being destroyed. 2.5 OPTION MENU Android Option Menus are the primary menus of android. They can be used for settings, search, delete item etc. Here, we are going to see two examples of option menus. First, the simple option menus and second, options menus with images. Here, we are inflating the menu by calling the inflate() method of MenuInflater class. To perform event handling on menu items, you need to override onOptionsItemSelected() method of Activity class. <menu xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" tools:context=\"menuexample.myproject.com.optionmenu.MainActivity\"> <item android:id=\"@+id/item1\" android:title=\"Mumbai\"/> <item android:id=\"@+id/item2\" android:title=\"Pune\"/> <item android:id=\"@+id/item3\" android:title=\"Nagpur\" 22 CU IDOL SELF LEARNING MATERIAL (SLM)

app:showAsAction=\"withText\"/> </menu> 2.6 CONTEXT MENU Android context menu appears when user press long click on the element. It is also known as floating menu. It affects the selected content while doing action on it. It doesn't support item shortcuts and icons. public class MainActivity extends AppCompatActivity { ListView listView; String contacts[]={\"New Delhi\", \"Mumbai\", \"Bengaluru\", \"Chennai\", \"Nagpur\"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView=(ListView)findViewById(R.id.listView); ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,contacts); listView.setAdapter(adapter); // Register the ListView for Context menu registerForContextMenu(listView); } 2.7 POPUP MENU Android Popup Menu displays the menu below the anchor text if space is available otherwise above the anchor text. It disappears if you click outside the popup menu. The android.widget.PopupMenu is the direct subclass of java.lang.Object class. <?xml version=\"1.0\" encoding=\"utf-8\"?> <menu xmlns:android=\"http://schemas.android.com/apk/res/android\"> <item 23 CU IDOL SELF LEARNING MATERIAL (SLM)

android:id=\"@+id/one\" android:title=\"Copy Ctrl+C\" /> <item android:id=\"@+id/two\" android:title=\"Cut Ctrl+X\"/> <item android:id=\"@+id/three\" android:title=\"Paste Ctrl+V\"/> </menu> public class MainActivity extends AppCompatActivity { Button button; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Creating the instance of PopupMenu PopupMenu popup = new PopupMenu(MainActivity.this, button); //Inflating the Popup using xml file popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu()); //registering popup with OnMenuItemClickListener popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { 24 CU IDOL SELF LEARNING MATERIAL (SLM)

public boolean onMenuItemClick(MenuItem item) { Toast.makeText(MainActivity.this,\"You Clicked : \" + item.getTitle(), Toast.LENGTH_SHORT).show(); return true; } }); popup.show();//showing popup menu } });//closing the setOnClickListener method } } 2.8 ANDROID ALAR MANAGER Android AlarmManager allows you to access system alarm. By the help of Android AlarmManager in android, you can schedule your application to run at a specific time in the future. It works whether your phone is running or not. The Android AlarmManager holds a CPU wake lock that provides guarantee not to sleep the phone until broadcast is handled. activity_main.xml <?xml version=\"1.0\" encoding=\"utf-8\"?> <RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\"example.javatpoint.com.alarmmanager.MainActivity\"> <Button 25 android:id=\"@+id/button\" CU IDOL SELF LEARNING MATERIAL (SLM)

android:layout_width=\"wrap_content\" 26 android:layout_height=\"wrap_content\" android:text=\"Start\" android:layout_alignParentBottom=\"true\" android:layout_centerHorizontal=\"true\" android:layout_marginBottom=\"103dp\" /> <EditText android:id=\"@+id/time\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentTop=\"true\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"22dp\" android:ems=\"10\" /> </RelativeLayout> Activity class package example.javatpoint.com.alarmmanager; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; CU IDOL SELF LEARNING MATERIAL (SLM)

public class MainActivity extends AppCompatActivity { Button start; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); start= findViewById(R.id.button); start.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startAlert(); } }); } public void startAlert(){ EditText text = findViewById(R.id.time); int i = Integer.parseInt(text.getText().toString()); Intent intent = new Intent(this, MyBroadcastReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast( this.getApplicationContext(), 234324243, intent, 0); AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (i * 1000), pendingIntent); Toast.makeText(this, \"Alarm set in \" + i + \" seconds\",Toast.LENGTH_LONG).show(); } } Let's create BroadcastReceiver class that starts alarm. 27 CU IDOL SELF LEARNING MATERIAL (SLM)

MyBroadcastReceiver.java 28 package example.javatpoint.com.alarmmanager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.media.MediaPlayer; import android.widget.Toast; public class MyBroadcastReceiver extends BroadcastReceiver { MediaPlayer mp; @Override public void onReceive(Context context, Intent intent) { mp=MediaPlayer.create(context, R.raw.alarm); mp.start(); Toast.makeText(context, \"Alarm....\", Toast.LENGTH_LONG).show(); } } AndroidManifest.xml <receiver android:name=\"MyBroadcastReceiver\" > </receiver> <?xml version=\"1.0\" encoding=\"utf-8\"?> <manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"example.javatpoint.com.alarmmanager\"> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" CU IDOL SELF LEARNING MATERIAL (SLM)

android:supportsRtl=\"true\" android:theme=\"@style/AppTheme\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> <receiver android:name=\"MyBroadcastReceiver\" > </receiver> </application> </manifest> Output: 29 CU IDOL SELF LEARNING MATERIAL (SLM)

30 CU IDOL SELF LEARNING MATERIAL (SLM)

2.9 SUMMARY  There are three fundamental use cases of intent which are : i. Starting an activity ii. Starting a service iii. Delivering a broadcast  Explicit intents specify which application will satisfy the intent, by supplying either the target app's package name or a fully-qualified component class name. You'll typically use an explicit intent to start a component in your own app, because you know the class name of the activity or service you want to start. For example, you might start a new activity within your app in response to a user action, or start a service to download a file in the background.  Implicit intents do not name a specific component, but instead declare a general action to perform, which allows a component from another app to handle it. For example, if you want to show the user a location on a map, you can use an implicit intent to request that another capable app show a specified location on a map.  Android context menu appears when user press long click on the element. It is also known as floating menu.  Android Popup Menu displays the menu below the anchor text if space is available otherwise above the anchor text. It disappears if you click outside the popup menu. 2.10 KEYWORDS  Android Emulator: The Android Emulator simulates Android devices on your computer so that you can test your application on a variety of devices and Android API levels without needing to have each physical device.The emulator provides almost all of the capabilities of a real Android device.  Intent: Intent is to perform an action on the screen. It is mostly used to start activity, send broadcast receiver, start services and send message between two activities. There are two intents available in android as Implicit Intents and Explicit Intents.  Intent:It is a class which is used to connect activities.  EditText:It is used to take the input from the user.  Toast:It is a class which is used to display message for short period of time. 2.11 LEARNING ACTIVITY 1. Explain implicit intent with syntax. ___________________________________________________________________________ ___________________________________________________________________________ 31 CU IDOL SELF LEARNING MATERIAL (SLM)

2. Explain external implicit with syntax ___________________________________________________________________________ ___________________________________________________________________________ 2.12 UNIT END QUESTIONS A. Descriptive Questions Short Questions 1. Explain how we can start activity and service. 2. What is intent? Explain different types of intent with suitable example. 3. Explain in detail service life cycle. 4. With a suitable example explain option menu. 5. With a suitable example explain context menu. Long Questions 1. With a suitable example explain popup menu. 2. With a suitable example explain android alarm manager. 3. Draw the diagram of service life cycle and explain its each phase in detail 4. Write a program of activity class for option menu. B. Multiple Choice Questions 1. An Intent is a ________object you can use to request an action from another app component. a. messaging b. internal c. external d. implicit 2. With Android 5.0 (API level 21) and later, you can start a service with __________ a. JobScheduler b. GetScheduler c. AlarmScheduler d. All of these 3. A broadcast is a message that any app can ___________ 32 a. stop b. receive c. hold d. block CU IDOL SELF LEARNING MATERIAL (SLM)

4. A service is a application component that run in the ___________ a. class b. object c. background d. scheduler 5. Android Option Menus are the ________menus of android. a. secondary b. popup c. primary d. tertiary Answers 1-a, 2-a, 3-b, 4-c, 5-c 2.13 REFERENCES References book  Professional Android 4 Application Development” by Reto Meier  “Programming Android Java Programming for the New Generation of Mobile Devices” by Zigurd Mennieks  “Android Cookbook” by Ian F Darwin  “Android Programming: The Big Nerd Ranch Guide” by Bill Phillips and Chris Stewart Textbook references  “Professional Android 4 Application Development” by Reto Meier  “Programming Android Java Programming for the New Generation of Mobile Devices” by Zigurd Mennieks  “Android Cookbook” by Ian F Darwin  “Android Programming: The Big Nerd Ranch Guide” by Bill Phillips and Chris Stewart Website  Introduction to Android: http://developer.android.com/guide/index.html.  Android API: http://developer.android.com/reference/packages.html  Java 6 API: http://docs.oracle.com/javase/6/docs/api/ 33 CU IDOL SELF LEARNING MATERIAL (SLM)

 Android Fundamentals: http://developer.android.com/guide/components/fundamentals.html 34 CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT - 3: ANDRIOD TAB ACTIVITIES STRUCTURE 3 Learning Objectives 3.11 Introduction 3.12 Creation of Tab layout 3.13 Tab Activity 3.14 Drag and Drop 3.4.1 Drag and Drop Process 3.15 Drag Event Class 3.16 Summary 3.17 Keywords 3.18 Learning Activity 3.19 Unit End Questions 3.20 References 3.0 LEARNING OBJECTIVES After studying this unit, you will be able to:  Define different layout associated with android  Create a layout a tab layout and prepare a game event  Explain the concept of drag and drop.  Create an event using drag and drop 3.1 INTRODUCTION TabLayout is used to implement horizontal tabs. TabLayout is released by Android after the deprecation of ActionBar.TabListener (API level 21). TabLayout is introduced in design support library to implement tabs. Tabs are created using newTab() method of TabLayout class. The title and icon of Tabs are set through setText(int) and setIcon(int) methods of TabListener interface respectively. Tabs of layout are attached over TabLayout using the method addTab(Tab) method. TabLayout tabLayout = (TabLayout)findViewById(R.id.tabLayout); tabLayout.addTab(tabLayout.newTab().setText(\"Personal Details\")); 35 CU IDOL SELF LEARNING MATERIAL (SLM)

tabLayout.addTab(tabLayout.newTab().setText(\"Educational Details\")); tabLayout.addTab(tabLayout.newTab().setText(\"Family Details\")); 3.2 CREATION OF TAB LAYOUT Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 – Add the following dependency to create a tab layout implementation 'com.android.support:design:28.0.0' Step 3 − Add the following code to res/layout/activity_main.xml. <?xml version=\"1.0\" encoding=\"utf-8\"?> <RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <android.support.design.widget.TabLayout android:id=\"@+id/tabLayout\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:background=\"#1db995\"> </android.support.design.widget.TabLayout> <android.support.v4.view.ViewPager android:id=\"@+id/viewPager\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/tabLayout\" android:layout_centerInParent=\"true\" android:layout_marginTop=\"100dp\" tools:layout_editor_absoluteX=\"8dp\" /> 36 CU IDOL SELF LEARNING MATERIAL (SLM)

</RelativeLayout> Step 4 − Add the following code to src/MainActivity.java import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; public class MainActivity extends AppCompatActivity { TabLayout tabLayout; ViewPager viewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tabLayout = findViewById(R.id.tabLayout); viewPager = findViewById(R.id.viewPager); tabLayout.addTab(tabLayout.newTab().setText(\"Football\")); tabLayout.addTab(tabLayout.newTab().setText(\"Cricket\")); tabLayout.addTab(tabLayout.newTab().setText(\"NBA\")); tabLayout.setTabGravity(TabLayout.GRAVITY_FILL); final MyAdapter adapter = new MyAdapter(this,getSupportFragmentManager(), tabLayout.getTabCount()); viewPager.setAdapter(adapter); viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { viewPager.setCurrentItem(tab.getPosition()); } @Override 37 CU IDOL SELF LEARNING MATERIAL (SLM)

public void onTabUnselected(TabLayout.Tab tab) { 38 } @Override public void onTabReselected(TabLayout.Tab tab) { } }); } } Step 5 – Create a java class(MyAdapter.java) and add the following code – import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentManager; class MyAdapter extends FragmentPagerAdapter { Context context; int totalTabs; public MyAdapter(Context c, FragmentManager fm, int totalTabs) { super(fm); context = c; this.totalTabs = totalTabs; } @Override public Fragment getItem(int position) { switch (position) { case 0: Football footballFragment = new Football(); return footballFragment; case 1: Cricket cricketFragment = new Cricket(); return cricketFragment; CU IDOL SELF LEARNING MATERIAL (SLM)

case 2: NBA nbaFragment = new NBA(); return nbaFragment; default: return null; } } @Override public int getCount() { return totalTabs; } } Step 6 – Now create the fragments and the layouts (Right click on the project >> New >> Fragment >> Blank – Example : FootBall.java import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class Football extends Fragment { public Football() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_football, container, false); } } 39 CU IDOL SELF LEARNING MATERIAL (SLM)

Step 7 - Add the following code to androidManifest.xml <?xml version=\"1.0\" encoding=\"utf-8\"?> <manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\"> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/AppTheme\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> </application> </manifest> 40 CU IDOL SELF LEARNING MATERIAL (SLM)

3.3 TABACTIVITY For apps developing against HONEYCOMB or later, tabs are typically presented in the UI using the new ActionBar.newTab() and related APIs for placing tabs within their action bar area. It’s a subclass of ActivityGroup. Methods available in TabHost getTabHost() Returns the TabHost the activity is using to host its tabs. TabWidget getTabWidget() Returns the TabWidget the activity is using to draw the actual tabs. Void onContentChanged() Updates the screen state (current list and other views) when the content changes. Void setDefaultTab(String tag) Sets the default tab that is the first tab highlighted. Void setDefaultTab(int index) Sets the default tab that is the first tab highlighted. Syntax and flow of Tab Activity: public class TabActivity extends ActivityGroup java.lang.Object 41 ↳ android.content.Context ↳ android.content.ContextWrapper ↳ android.view.ContextThemeWrapper ↳ android.app.Activity ↳ android.app.ActivityGroup ↳ android.app.TabActivity CU IDOL SELF LEARNING MATERIAL (SLM)

3.4 DRAG AND DROP With the Android drag/drop framework, you can allow your users to move data using a graphical drag and drop gesture. This can be from one View to another in your own app, or between your app and another when multi-window mode is enabled. The framework includes a drag event class, drag listeners, and helper methods and classes. Although the framework is primarily designed for data movement, you can use it for other UI actions. For example, you could create an app that mixes colors when the user drags a color icon over another icon. The rest of this topic, however, describes the framework in terms of data movement. A drag and drop operation starts when the user makes some gesture that you recognize as a signal to start dragging data. In response, your application tells the system that the drag is starting. The system calls back to your application to get a representation of the data being dragged. As the user's finger moves this representation (a \"drag shadow\") over the current layout, the system sends drag events to the drag event listener objects and drag event callback methods associated with the View objects in the layout. Once the user releases the drag shadow, the system ends the drag operation. When you start a drag, you include both the data you are moving and metadata describing this data as part of the call to the system. During the drag, the system sends drag events to the drag event listeners or callback methods of each View in the layout. The listeners or callback methods can use the metadata to decide if they want to accept the data when it is dropped. If the user drops the data over a View object, and that View object's listener or callback method has previously told the system that it wants to accept the drop, then the system sends the data to the listener or callback method in a drag event. You can call startDrag() for any attached View in the current layout. The system only uses the View object to get access to global settings in your layout. Once your application calls startDrag(), the rest of the process uses events that the system sends to the View objects in your current layout. 3.4.1 The drag/drop process : There are basically four steps or states in the drag and drop process: 1. Started : In response to the user's gesture to begin a drag, your application calls startDrag() to tell the system to start a drag. The arguments startDrag() provide the data to be dragged, metadata for this data, and a callback for drawing the drag shadow. The system first responds by calling back to your application to get a drag shadow. It then displays the drag shadow on the device. 42 CU IDOL SELF LEARNING MATERIAL (SLM)

Next, the system sends a drag event with action type ACTION_DRAG_STARTED to the drag event listeners for all the View objects in the current layout. To continue to receive drag events, including a possible drop event, a drag event listener must return true. This registers the listener with the system. Only registered listeners continue to receive drag events. At this point, listeners can also change the appearance of their View object to show that the listener can accept a drop event. If the drag event listener returns false, then it will not receive drag events for the current operation until the system sends a drag event with action type ACTION_DRAG_ENDED. By sending false, the listener tells the system that it is not interested in the drag operation and does not want to accept the dragged data. 2. Continuing : The user continues the drag. As the drag shadow intersects the bounding box of a View object, the system sends one or more drag events to the View object's drag event listener (if it is registered to receive events). The listener may choose to alter its View object's appearance in response to the event. For example, if the event indicates that the drag shadow has entered the bounding box of the View (action type ACTION_DRAG_ENTERED), the listener can react by highlighting its View. 3. Dropped The user releases the drag shadow within the bounding box of a View that can accept the data. The system sends the View object's listener a drag event with action type ACTION_DROP. The drag event contains the data that was passed to the system in the call to startDrag() that started the operation. The listener is expected to return boolean true to the system if code for accepting the drop succeeds. Note that this step only occurs if the user drops the drag shadow within the bounding box of a View whose listener is registered to receive drag events. If the user releases the drag shadow in any other situation, no ACTION_DROP drag event is sent. 4. Ended After the user releases the drag shadow, and after the system sends out (if necessary) a drag event with action type ACTION_DROP, the system sends out a drag event with action type ACTION_DRAG_ENDED to indicate that the drag operation is over. This is done regardless of where the user released the drag shadow. The event is sent to every listener that is registered to receive drag events, even if the listener received the ACTION_DROP event. Each of these four steps is described in more detail in the section Designing a Drag and Drop Operation. 43 CU IDOL SELF LEARNING MATERIAL (SLM)

3.5 DRAGEVENT CLASS The DragEvent represents an event that is sent out by the system at various times during a drag and drop operation. This class provides few Constants and important methods which we use during Drag/Drop process. Syntax : public class DragEvent extends Object implements Parcelable java.lang.Object 44 ↳ android.view.DragEvent Constants: CU IDOL SELF LEARNING MATERIAL (SLM)

Following are all constants integers available as a part of DragEvent class. Sr.No Constants & Description 1 ACTION_DRAG_STARTED Signals the start of a drag and drop operation. 2 ACTION_DRAG_ENTERED Signals to a View that the drag point has entered the bounding box of the View. 3 ACTION_DRAG_LOCATION Sent to a View after ACTION_DRAG_ENTERED if the drag shadow is still within the View object's bounding box. 4 ACTION_DRAG_EXITED Signals that the user has moved the drag shadow outside the bounding box of the View. 5 ACTION_DROP Signals to a View that the user has released the drag shadow, and the drag point is within the bounding box of the View. 6 ACTION_DRAG_ENDED Signals to a View that the drag and drop operation has concluded. Table 3.1 Methods Following are few important and most frequently used methods available as a part of DragEvent class. Sr.No Constants & Description 1 int getAction() Inspect the action value of this event. 2 ClipData getClipData() Returns the ClipData object sent to the system as part of the call to startDrag(). 3 ClipDescription getClipDescription() Returns the ClipDescription object contained in the ClipData. 45 CU IDOL SELF LEARNING MATERIAL (SLM)

4 boolean getResult() Returns an indication of the result of the drag and drop operation. 5 float getX() Gets the X coordinate of the drag point. 6 float getY() Gets the Y coordinate of the drag point. 7 String toString() Returns a string representation of this DragEvent object. Table 3.2 Listening for Drag Event If you want any of your views within a Layout should respond Drag event then your view either implements View.OnDragListener or setup onDragEvent(DragEvent) callback method. When the system calls the method or listener, it passes to them a DragEvent object explained above. You can have both a listener and a callback method for View object. If this occurs, the system first calls the listener and then defined callback as long as listener returns true. The combination of the onDragEvent (DragEvent) method and View.OnDragListener is analogous to the combination of the onTouchEvent () and View.OnTouchListener used with touch events in old versions of Android. Starting a Drag Event You start with creating a ClipData and ClipData.Item for the data being moved. As part of the ClipData object, supply metadata that is stored in a ClipDescription object within the ClipData. For a drag and drop operation that does not represent data movement, you may want to use null instead of an actual object. Next either you can extend extend View.DragShadowBuilder to create a drag shadow for dragging the view or simply you can use View.DragShadowBuilder(View) to create a default drag shadow that's the same size as the View argument passed to it, with the touch point centered in the drag shadow. 46 CU IDOL SELF LEARNING MATERIAL (SLM)

3.6 SUMMARY  TabLayout is used to implement horizontal tabs. TabLayout is released by Android after the deprecation of ActionBar.TabListener (API level 21).  For apps developing against HONEYCOMB or later, tabs are typically presented in the UI using the new ActionBar.newTab () and related APIs for placing tabs within their action bar area.  With the Android drag/drop framework, you can allow your users to move data using a graphical drag and drop gesture. This can be from one View to another in your own app, or between your app and another when multi-window mode is enabled. The framework includes a drag event class, drag listeners, and helper methods and classes.  There are basically four steps or states in the drag and drop process: 1. Started 2. Continuing 3. Dropped 4. Ended  The DragEvent represents an event that is sent out by the system at various times during a drag and drop operation. This class provides few Constants and important methods which we use during Drag/Drop process. Syntax : public class DragEvent extends Object implements Parcelable 3.7 KEYWORDS  Constant -the fixed values that are used in a program, and its value remains the same during the entire execution of the program.  DragEvent – an event that is sent out by the system at various times during a drag and drop operation. It is a data structure that contains several important pieces of data about the operation and the underlying data.  Syntax – the arrangement of words and phrases to create well-formed sentences in a language.The structure of statements in a computer language.  Activity– the condition in which things are happening or being done.  Fragment; A fragment is a small piece that's come off a larger whole, and to fragment is to break. If your teacher writes \"frag\" on your paper, you've got an incomplete sentence. Fragment, meaning \"a tiny, brittle shard,\" first appeared as a noun and later as a verb. 47 CU IDOL SELF LEARNING MATERIAL (SLM)

3.8LEARNING ACTIVITY 1. Create fragment layout for an event cricket.java ___________________________________________________________________________ ___________________________________________________________________________ 2. Define syntax and flow of tab activity ___________________________________________________________________________ ___________________________________________________________________________ 3.9 UNIT END QUESTIONS A. Descriptive Questions Short Questions 1. Explain in short tab layout 2. Explain in brief what you mean by tab activity. 3. Explain the meaning of drag and drop in connection with mobile programming. 4. Explain the process of drag and drop. 5. Explain the method in drag event Long Questions 1. List and explain constants of drag event 2. Explain creation of tab layout with steps involved in it. 3. Write in detail about drag event class. 4. Explain the following a. Listening for Drag Event b. Starting a Drag Event. 5. Create fragment layout for an event cricket.java and hockey.java B. Multiple Choice Questions 1. The user releases the ______ shadow within the bounding box of a View that can accept the data a. drag b. drop c. create d. All of these 48 CU IDOL SELF LEARNING MATERIAL (SLM)

2. After the user releases the drag shadow, and after the system sends out (if necessary) a drag event with action type ACTION_DROP, the system sends out a drag event with action type _________ to indicate that the drag operation is over string a. ACTION_DROP_ENDED b. ACTION_DRAG_ENDED c. ACTION_CREATE_ENDED d. None of these 3. There are basically ______steps or states in the drag and drop process a. 5 b. 6 c. 4 d. 2 4. TabLayout is used to implement _______ tabs a. vertical Layout only b. horizontal and vertical layout. c. Horizontal tab only d. Column 5. With the Android drag/drop framework, you can allow your users to move data using a _________ a. graphical drag b. manual drag c. click drag d. automatic drag Answers 1-a, 2-b, 3-c, 4-c, 5-a 3.10 REFERENCES References book  Wei - Meng Le, “Beginning Android 4 Applications Development”, John Wiley & Sons, Inc. , 2012.  Reto Meier, “Professional Android 4 Applications Development”, John Wiley & Sons, Inc., 2012 49 CU IDOL SELF LEARNING MATERIAL (SLM)

 Zigurd Mednieks, Laird Dornin, Blake Meike G, and Masumi Nakamura, “Programming Android”, O’Reily books, 2011. Website  https://developer.android.com/training/articles/security-tips  https://www.javatpoint.com/  https://developer.android.com/reference/android/media/MediaRecorder  https://android-developers.googleblog.com/2020/02/Android-11-developer- preview.html 50 CU IDOL SELF LEARNING MATERIAL (SLM)


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook