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-BCA-SEM-V-Mobile Application Development-Second Draft

CU-BCA-SEM-V-Mobile Application Development-Second Draft

Published by Teamlease Edtech Ltd (Amita Chitroda), 2022-02-26 01:58:23

Description: CU-BCA-SEM-V-Mobile Application Development-Second Draft

Search

Read the Text Version

<TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Hello World by AbhiAndroid!\" android:textSize=\"20sp\" android:layout_centerInParent=\"true\"/> </RelativeLayout> Step 3: Create a new XML file splashfile.xml for Splash screen and paste the following code in it. This layout contains your app logo or other product logo that you want to show on splash screen. <?xml version=\"1.0\" encoding=\"utf-8\"?> <RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center\" android:background=\"@color/splashBackground\"> <ImageView android:id=\"@+id/logo_id\" android:layout_width=\"250dp\" android:layout_height=\"250dp\" android:layout_centerInParent=\"true\" android:src=\"@drawable/abhiandroid\"/> <TextView 151 android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/logo_id\" android:layout_centerHorizontal=\"true\" CU IDOL SELF LEARNING MATERIAL (SLM)

android:text=\"Splash Screen\" android:textSize=\"30dp\" android:textColor=\"@color/blue\"/> </RelativeLayout> Step 4: Now open app -> java -> package -> MainActivity.java and add the below code. package abhiandroid.com.splashscreen; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } } Step 5: For Splash Screen we will create a separate splash activity. Create a new class in your java package and name it as SplashActivity.java. Step 6: Add this code in SplashActivity.java activity. In this code handler is used to hold the screen for specific time and once the handler is out, our main Activity will be launched. We are going to hold the Splash screen for three second’s. We will define the seconds in millisecond’s after Post Delayed(){} method. 1 second =1000 milliseconds. 152 CU IDOL SELF LEARNING MATERIAL (SLM)

Post Delayed method will delay the time for 3 seconds. After the delay time is complete, then your main activity will be launched. SplashActivity.java package abhiandroid.com.splashscreen; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; /** * Created by AbhiAndroid */ public class SplashActivity extends Activity { Handler handler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.splashfile); handler=new Handler(); 153 handler.postDelayed(new Runnable() { @Override public void run() { Intent intent=new Intent(SplashActivity.this,MainActivity.class); CU IDOL SELF LEARNING MATERIAL (SLM)

startActivity(intent); finish(); } },3000); } } Step 7: Open AndroidManifest.xml file and make your splashactivity.java class as Launcher activity and mention the Main Activity as another activity. AndroidManifest.xml <?xml version=\"1.0\" encoding=\"utf-8\"?> <manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"abhiandroid.com.splashscreen\"> <application android:allowBackup=\"true\" android:icon=\"@drawable/abhiandroid\" android:label=\"@string/app_name\" android:supportsRtl=\"true\" android:theme=\"@style/AppTheme\"> <activity android:name=\"abhiandroid.com.splashscreen.SplashActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> 154 </intent-filter> </activity> <activity android:name=\"abhiandroid.com.splashscreen.MainActivity\"/> CU IDOL SELF LEARNING MATERIAL (SLM)

</application> </manifest> Output: Now run the App and you will see Splash screen before the main layout loads. 7.5 SUMMARY  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. Here is a sample example to start new activity with old activity.  An implicit Intent is a mechanism that lets anonymous application components service action requests. That means you can ask the system to start an Activity to perform an action without knowing which application, or Activity, will be started.  Explicit Intent in Android Although it does not look very complex through the eyes of a user, there are hundreds of operations taking place in an Android application as the user continues using it. Out of a large population, only a few curious users would know that there are tons of interactions occurring within a single Android app at a time. If you are a newly curious user looking for information on interactions within a single app, you came to the right place.  The Android system tests an implicit Intent against an Intent filter by comparing the parts of that Intent to each of the three Intent filter elements (action, category, and data). The Intent must pass all three tests or the Android system won't deliver the Intent to the component. However, because a component may have multiple Intent filters, an Intent that does not pass through one of a component's filters might make it through on another filter.  An Activity registers itself with the system as being able to handle an implicit Intent with Intent filters, declared in the AndroidManifest.xml file. For example, the main Activity for your app has Intent filter that declares it the main Activity for the launcher category. This Intent filter is how the Android system knows to start that specific Activity in your app when the user taps the icon for your app on the device home screen.  Toasts are transient notifications that remain visible for only a few seconds before fading out. Toasts don’t steal focus and are non-modal, so they don’t interrupt the active application. Toasts are perfect for informing your users of events without forcing them to open an Activity or read a Notification. 155 CU IDOL SELF LEARNING MATERIAL (SLM)

 The most common use of Intents is to bind your application components and communicate between them. Intents are used to start Activities, allowing you to create a workflow of different screens.  A splash screen is mostly the first screen of the app when it is opened. It is a constant screen which appears for a specific amount of time, generally shows for the first time when the app is launched. The Splash screen is used to display some basic introductory information such as the company logo, content, etc just before the app loads completely. 7.6 KEYWORDS  Intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and Context start Service(Intent) or Context bindService to communicate with a background Service.  Implicit intent specifies an action that can invoke any app on the device able to perform the action. Using an implicit intent is useful when your app cannot perform the action, but other apps probably can and you'd like the user to pick which app to use.  Explicit Intent in Android Although it does not look very complex through the eyes of a user, there are hundreds of operations taking place in an Android application as the user continues using it.  Toasts are transient notifications that remain visible for only a few seconds before fading out. Toasts don’t steal focus and are non-modal, so they don’t interrupt the active application. Toasts are perfect for informing your users of events without forcing them to open an Activity or read a Notification.  Splash screen is mostly the first screen of the app when it is opened. It is a constant screen which appears for a specific amount of time, generally shows for the first time when the app is launched. The Splash screen is used to display some basic introductory information such as the company logo, content, etc just before the app loads completely. 7.7 LEARNING ACTIVITY 1. It has been said, “you cannot teach a person anything; but a person can learn”. Discuss the implication of this for training methodology. 156 CU IDOL SELF LEARNING MATERIAL (SLM)

___________________________________________________________________________ __________________________________________________________________________ 2. In education sector which types of training are used for the development of employees? Explain one type of training with examples. ___________________________________________________________________________ __________________________________________________________________________ 7.8 UNIT END QUESTIONS A. Descriptive Questions Short Questions 1. Explain Intents 2. What do you understand by Toast? 3. What is Splash Screen? 4. Describe Implicit Intents. 5. Explain Explicit Intents. Long Questions 1. What arethe Intents Explain? 2. Explain Implicit Intents. 3. Explain Explicit Intents? 4. Explain Splash Screen. 5. What is Toast? Explain. B. Multiple Choice Questions 1. What is Toast class? a. The Toast class is used to display notifications on the device's status bar b. The Toast class is used to display notifications on the device's status bar and disappears after a few seconds c. The Toast class is used to display alerts to the user and disappears when user click on OK button d. The Toast class is used to display alerts to the user and disappears after a few seconds 2. What is an abstract description of an operation to be performed. It can be used with start Activity to launch an Activity. 157 CU IDOL SELF LEARNING MATERIAL (SLM)

a. Filters b. Intent c. Service d. Broadcast Receiver 3. What code you will write suppose that there are two activities in an application named ActivityOne and ActivityTwo. You want to invoke ActivityTwo from ActivityOne.? a. Intent intent=new Intent start Activity b. StartActivity c. Option A and B are correct. d. None of these. 4. What are the types of intents in android is\\are? a. Explicit intents b. Implicit intents c. Start intents d. Option A and B are correct. 5. What is splash screen in android? a. Initial activity of an application b. Initial service of an application c. Initial method of an application d. Initial screen of an application Answers: 1-d, 2- b, 3-c, 4- d, 5- d 7.9 REFERENCES Reference  Zigurd Mednieks, Laird Dornin, Blake Meike G, and Masumi Nakamura, 2011 “Programming Android”, O’Reilly books.  Dave Smith, 2015, Android Recipes.  Josh Juneau, Matt Arena, 2012, Oracle and PL/SQL Recipes Textbooks  Spring 5 Recipes Deinum, 2017, Daniel Rubio, Josh Long. 158 CU IDOL SELF LEARNING MATERIAL (SLM)

 Wei - Meng Le, 2012, Beginning Android 4 Application Development”, John Wiley & Sons, Inc.  Reto Meier, 2012 Professional Android 4 Application Development”, John Wiley & Sons, Inc. Websites  https://en.wikipedia.org/  https://www.tutlane.com/  https://www.geeksforgeeks.org/  https://www.tutorialspoint.com/ 159 CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT 8: OTHER ANDROID COMPONENTS 160 STRUCTURE 8.0 Learning Objectives 8.1 Introduction 8.2 Services 8.2.1 How to Create a Service That Runs in the Background 8.2.2 How to Perform Long-Running Tasks in a Separate Thread 8.2.3 How to Perform Repeated Tasks in a Service 8.2.4 How an Activity and a Service Communicate 8.3 Broadcast Receivers 8.3.1Using Intents to Broadcast Events 8.3.2 Broadcasting Events with Intents 8.3.3 Listening for Broadcasts with Broadcast Receivers 8.3.4 Broadcasting Ordered Intents 8.3.5 Broadcasting Sticky Intents 8.3.6 Introducing the Local Broadcast Manager 8.3.7 Creating Intent Filters and Broadcast Receivers 8.4 Content Providers 8.4.1 What are Content Providers? 8.4.2 How to use a Content Provider in Android 8.4.3 How to Create and use your Own Content Provider 8.5 Summary 8.6 Keywords 8.7 Learning Activity 8.8 Unit End Questions 8.9 References 8.0 LEARNING OBJECTIVES After studying this unit, student will be able to: CU IDOL SELF LEARNING MATERIAL (SLM)

 Identify content providers.  Explain Services.  Examine the Broadcast Receivers.  Learn How to use a content provider in Android  Learn How to perform long-running tasks in a separate thread 8.1 INTRODUCTION A service is an application in Android that runs in the background without needing to interact with the user. For example, while using an application, you may want to play some background music at the same time. In this case, the code that is playing the background music has no need to interact with the user, and hence it can be run as a service. Services are also ideal for situations in which there is no need to present a UI to the user. A good example of this scenario is an application that continually logs the geographical coordinates of the device. In this case, you can write a service to do that in the background. In this chapter, you will learn how to create your own services and use them to perform background tasks asynchronously. A Service is an application component that can perform long-running operations in the background. It does not provide a user interface. Once started, a service might continue running for some time, even after the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication. For example, a service can handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background. This Module looks at Intents probably the most unique and important concept in Android development. You’ll learn how to use Intents to broadcast data within and between applications and how to listen for them to detect changes in the system state. You’ll also learn how to define implicit and explicit Intents to start Activities or Services using late runtime binding. Using implicit Intents, you’ll learn how to request that an action be performed on a piece of data, enabling Android to determine which application components can best service that request. Broadcast Intents are used to announce events systemwide. You’ll learn how to transmit these broadcasts and receive those using Broadcast Receivers. Broadcast Receivers simply respond to broadcast messages from other applications or from the system itself. These messages are sometime called events or intents. 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. Content providers can help an application manage access to data stored by it, stored by other apps, and provide a way to share data with other apps. They encapsulate the data and provide mechanisms for defining data security. Content providers are the standard interface that 161 CU IDOL SELF LEARNING MATERIAL (SLM)

connects data in one process with code running in another process. Implementing a content provider has many advantages. 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. A content provider can use different ways to store its data and the data can be stored in a database, in files, or even over a network.Content providers let you centralize content in one place and have many different applications access it as needed. A content provider behaves very much like a database where you can query it, edit its content, as well as add or delete content using insert,update, delete, and query methods. In most cases this data is stored in an SQlite database. A content provider is implemented as a subclass of ContentProvider class and must implement a standard set of APIs that enable other applications to perform transactions. 8.2 SERVICES 8.2.1 How to Create a Service that Runs in the Background The best way to understand how a service works is by creating one. The following Try It Out shows you the steps to create a simple service. Subsequent sections add more functionality to this service. For now, you will learn how to start and stop a service. 1. Using Eclipse, create a new Android project and name its Services. 2. Add a new Java Class file to the project and name it MyService. Populate the MyService.java file with the following code: package net.learn2develop.Services; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.widget.Toast; public class MyService extends Service { @Override public IBinder onBind(Intent arg0) { return null; } @Override public int onStartCommand(Intent, int flags, int startId) { 162 CU IDOL SELF LEARNING MATERIAL (SLM)

// We want this service to continue running until it is explicitly 163 // stopped, so return sticky. Toast.makeText(this, “Service Started”, Toast LENGTH_LONG).show(); return START_STICKY; @Override public void onDestroy() { super.onDestroy(); Toast.makeText(this, “Service Destroyed”, Toast.LENGTH_LONG).show(); 3. In the AndroidManifest.xml file, add the following statement in bold: <?xml version=”1.0” encoding=”utf-8”?> <manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”net.learn2develop.Services” android:versionCode=”1” android:versionName=”1.0” > <uses-sdk android:minSdkVersion=”14” /> <application android:icon=”@drawable/ic_launcher” android:label=”@string/app_name” > <activity android:label=”@string/app_name” android:name=”.ServicesActivity” > <intent-filter > <action android:name=”android.intent.action.MAIN” /> <category android:name=”android.intent.category.LAUNCHER” /> </intent-filter> </activity> <service android:name=”.MyService” /> </application> </manifest> CU IDOL SELF LEARNING MATERIAL (SLM)

4. In the main.xml file, add the following statements in bold, replacing TextView: <?xml version=”1.0” encoding=”utf-8”?> <LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android” android:layout_width=”fill_parent” android:layout_height=”fill_parent” android:orientation=”vertical” > <Button android:id=”@+id/btnStartService” android:layout_width=”fill_parent” android:layout_height=”wrap_content” android:text=”Start Service” android:onClick=”startService”/> <Button android:id=”@+id/btnStopService” android:layout_width=”fill_parent” android:layout_height=”wrap_content” android:text=”Stop Service” android:onClick=”stopService” /> </LinearLayout> 5. Add the following statements in bold to the ServicesActivity.java fi le: package net.learn2develop.Services; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; public class ServicesActivity extends Activity /** Called when the activity is first created. @Override public void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); setContentView(R.layout.main); 164 CU IDOL SELF LEARNING MATERIAL (SLM)

public void startService(View view) startService(new Intent(getBaseContext(), MyService.class)); public void stopService(View view) stopService(new Intent(getBaseContext(), MyService.class)); 6. Press F11 to debug the application on the Android emulator. 7. Clicking the Start Service button will start the service To stop the service, click the Stop Service button Figure 8.1: SERVICES 8.2.2 How to Perform Long-running Tasks in a Separate Thread Because the service you created in the previous section does not do anything useful, in this section you will modify it so that it performs a task. In the following Try It Out, you will simulate the service of downloading a fi le from the Internet. 1. Using the Services project created in the first example, add the following statements in bold to the ServicesActivity.java file: package net.learn2develop.Services; import java.net.MalformedURLException; import java.net.URL; import android.app.Service; import android.content.Intent; import android.os.IBinder; 165 CU IDOL SELF LEARNING MATERIAL (SLM)

import android.widget.Toast; public class MyService extends Service { @Override public IBinder onBind(Intent arg0) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { // We want this service to continue running until it is explicitly // stopped, so return sticky. //Toast.makeText(this, “Service Started”, Toast.LENGTH_LONG).show(); try { int result = DownloadFile(new URL(“http://www.amazon.com/somefile.pdf”)); Toast.makeText(getBaseContext(), “Downloaded “ + result + “ bytes”, Toast.LENGTH_LONG).show(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return START_STICKY; } private int DownloadFile(URL url) { try { //---simulate taking some time to download a file--- Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } //---return an arbitrary number representing 166 CU IDOL SELF LEARNING MATERIAL (SLM)

// the size of the file downloaded--- return 100; } @Override public void onDestroy() { super.onDestroy(); Toast.makeText(this, “Service Destroyed”, Toast.LENGTH_LONG).show(); Figure 8.2: SERVICES 2 2. Press F11 to debug the application on the Android emulator. 3. Click the Start Service button to start the service to download the file. Note that the activity is frozen for a few seconds before the Toast class displays the “Downloaded 100 bytes” message How it Works? In this example, your service calls the Download File method to simulate downloading a file from a given URL. This method returns the total number of bytes downloaded . To simulate the delays experienced by the service when downloading the file, you used the Thread. Sleep method to pause the service for five seconds,as you start the service, note that the activity is suspended for about five seconds, which is the time taken for the file to be downloaded from the Internet. During this time, the entire activity is not responsive, demonstrating a very important point: The service runs on the same thread as your activity. In this case, because the service is suspended for five seconds, so is the activity. 8.2.3 How to Perform Repeated Tasks in a Service In addition to performing long-running tasks in a service, you might also perform some repeated tasks in a service. For example, you may write an alarm clock service that runs persistently in the background. In this case, your service may need to periodically execute some code to check whether a prescheduled time has been reached so that an alarm can be 167 CU IDOL SELF LEARNING MATERIAL (SLM)

sounded. To execute a block of code to be executed at a regular time interval, you can use the Timer class within your service. For the scheduleAtFixed Rate method, your code is executed at fixed time intervals, regardless of how long each task takes. For example, if the code within your run method takes two seconds to complete, then your second task will start immediately after the first task has ended. Similarly, if your delay is set to three seconds and the task takes two seconds to complete, then the second task will wait for one second before starting. Also, observe that you call the doSomething Repeatedly method directly in the onStart Command method, without needing to wrap it in a subclass of the AsyncTask class. This is because the TimerTask class itself implements the unable interface, which allows it to run on a separate thread. 8.2.4 How an Activity and a Service Communicate Often a service simply executes in its own thread, independently of the activity that calls it. This doesn’t pose any problem if you simply want the service to perform some tasks periodically and the activity does not need to be notified about the service’s status. For example, you may have a service that periodically logs the geographical location of the device to a database. In this case, there is no need for your service to interact with any activities, because its main purpose is to save the coordinates into a database. However, suppose you want to monitor for a particular location. When the service logs an address that is near the location you are monitoring, it might need to communicate that information to the activity. If so, you need to devise a way for the service to interact with the activity. The following Try It Out demonstrates how a service can communicate with an activity using a BroadcastReceiver. 8.3 BROADCAST RECEIVERS Broadcast receiver is an Android component which allows you to send or receive Android system or application events. All the registered application is notified by the Android runtime once event happens. It works likethepublishsubscribe design pattern and used for asynchronous inter-process communication. 8.3.1 Using Intents to Broadcast Events So far, you’ve looked at using Intents to start new application components, but you can also use Intents to broadcast messages anonymously between components via the sendBroadcast method. As a system-level message-passing mechanism, Intents are capable of sending structured messages across process boundaries. As a result, you can implement Broadcast Receivers to listen for, and respond to, these Broadcast Intents within your applications. Broadcast Intents are used to notify applications of system or application events, extending the event-driven programming model between applications. Broadcasting Intents helps make 168 CU IDOL SELF LEARNING MATERIAL (SLM)

your application more open; by broadcasting an event using Intent, you let yourself and third- party developers react to events without having to modify your original application. Within your applications you can listen for Broadcast Intents to react to device state changes and third-party application events. Android uses Broadcast Intents extensively to broadcast system events, such as changes in network connectivity, docking state, and incoming calls. 8.3.2 Broadcasting Events with Intents Within your application, construct the Intent you want to broadcast and call sendBroadcast to send it. Set the action, data, and category of your Intent in a way that lets Broadcast Receivers accurately determine their interest. In this scenario, the Intent action string is used to identify the event being broadcast, so it should be a unique string that identifies the event. By convention, action strings are constructed using the same form as Java package names. 8.3.3 Listening for Broadcasts with Broadcast Receivers Broadcast Receivers are used to listen for Broadcast Intents. For a Receiver to receive broadcasts, it must be registered, either in code or within the application manifest the latter case is referred to as a manifest Receiver. In either case, use an Intent Filter to specify which Intent actions and data your Receiver is listening for. In the case of applications that include manifest Receivers, the applications don’t have to be running when the Intent is broadcast for those receivers to execute; they will be started automatically when a matching Intent is broadcast. This is excellent for resource management, as it lets you create event-driven applications that will still respond to broadcast events even after they’ve been closed or killed. The ON Receive method will be executed on the main application thread when a Broadcast Intent is received that matches the Intent Filter used to register the Receiver. The ON Receive handler must complete within five seconds; otherwise, the Force Close dialog will be displayed. Typically, Broadcast Receivers will update content, launch Services, update Activity UI, or notify the user using the Notification Manager. The five-second execution limit ensures that major processing cannot, and should not, be done within the Broadcast Receiver itself. Listing 5-11 shows how to implement a Broadcast Receiver that extracts the data and several extras from the broadcast Intent and uses them to start a new Activity. In the following sections you will learn how to register it in code or in your application manifest. 8.3.4 Broadcasting Ordered Intents When the order in which the Broadcast Receivers receive the Intent is important Particularly where you want to allow Receivers to affect the Broadcast Intent received by future Receivers you can use sendOrderedBroadcast, as follows: String requiredPermission = “com.paad.MY_BROADCAST_PERMISSION”; SendOrderedBroadcast (intent, requiredPermission); 169 CU IDOL SELF LEARNING MATERIAL (SLM)

Using this method, your Intent will be delivered to all registered Receivers that hold the required permission in the order of their specified priority. You can specify the priority of a Broadcast Receiver using the android priority attribute within its Intent Filter manifest node, where higher values are considered higher priority. 8.3.5 Broadcasting Sticky Intents Sticky Intents are useful variations of Broadcast Intents that persist the values associated with their last broadcast, returning them as Intent when a new Receiver is registered to receive the broadcast. When you call registerReceiver, specifying an Intent Filter that matches a sticky Broadcast Intent, the return value will be the last Intent broadcast, such as the battery-level changed broadcast. 8.3.6 Introducing the Local Broadcast Manager The Local Broadcast Manager was introduced to the Android Support Library to simplify the process of registering for, and sending, broadcast Intents between components within your application. Because of the reduced broadcast scope, using the LocalBroadcast Manager is more efficient than sending a global broadcast. It also ensures that the Intent you broadcast cannot be received by any components outside your application, ensuring that there is no risk of leaking private or sensitive data, such as location information. Similarly, other applications can’t transmit broadcasts to your Receivers, negating the risk of these Receivers becoming vectors for security exploits. 8.3.7 Creating Intent Filters and Broadcast Receivers Having learned to use Intents to start Activities/Services and to broadcast events, it’s important to understand how to create the Broadcast Receivers and Intent Filters that listen for Broadcast Intents and allow your application to respond to them. In the case of Activities and Services, Intent is a request for an action to be performed on a set of data, and an Intent Filter is a declaration that a particular application component can perform an action on a type of data. Intent Filters are also used to specify the actions a Broadcast Receiver is interested in receiving. 8.4 CONTENT PROVIDERS In this section, you will learn Android’s way of sharing data through the use of content providers. You will learn how to use the built-in content providers, as well as implement your own content providers to share data across packages. 8.4.1 What are Content Providers? A content provider manages access to a central repository of data. A provider is part of an Android application, which often provides its own UI for working with the data. However, content providers are primarily intended to be used by other applications, which access the 170 CU IDOL SELF LEARNING MATERIAL (SLM)

provider using a provider client object. Together, providers and provider clients offer a consistent, standard interface to data that also handles inter-process communication and secure data access. Typically, you work with content providers in one of two scenarios; you may want to implement code to access an existing content provider in another application, or you may want to create a new content provider in your application to share data with other applications. This topic covers the basics of working with existing content providers. To learn more about implementing content providers in your own applications, see creating a content provider. Content providers can help an application manage access to data stored by itself, stored by other apps, and provide a way to share data with other apps. They encapsulate the data and provide mechanisms for defining data security. Content providers are the standard interface that connects data in one process with code running in another process. Implementing a content provider has many advantages. Most importantly you can configure a content provider to allow other applications to securely access and modify your app data as illustrated. Figure 8.3: Content providers 171 CU IDOL SELF LEARNING MATERIAL (SLM)

Overview diagram of how content providers manage access to storage. Use content providers if you plan to share data. If you don’t plan to share data, you may still use them because they provide a nice abstraction, but you don’t have to. This abstraction allows you to make modifications to your application data storage implementation without affecting other existing applications that rely on access to your data. In this scenario only your content provider is affected and not the applications that access it. For example, you might swap out a SQLite database for alternative storage as illustrated. Figure 8.4: Content providers 2 Illustration of migrating content provider storage. A number of other classes rely on the ContentProvider class:  AbstractThreadedSyncAdapter  CursorAdapter  CursorLoader If you are making use of any of these classes you also need to implement a content provider in your application. Note that when working with the sync adapter framework you can also create a stub content provider as an alternative. For more information about this topic, see creating a stub content provider. In addition, you need your own content provider in the following cases:  You want to implement custom search suggestions in your application  You need to use a content provider to expose your application data to widgets 172 CU IDOL SELF LEARNING MATERIAL (SLM)

 You want to copy and paste complex data or files from your application to other applications The Android framework includes content providers that manage data such as audio, video, images, and personal contact information. You can see some of them listed in the reference documentation for the android provider package. With some restrictions, these providers are accessible to any Android application. A content provider can be used to manage access to a variety of data storage sources, including, both structured data such as a SQLITE relational database, or unstructured data such as image files. For more information on the types of storage available on Android, see Storage options, as well as Designing data storage. 8.4.2 How to Use a Content Provider in Android The best way to understand content providers is to actually use one. The following Try It Out shows how you can use a content provider from within your Android application. 1. Using Eclipse, create a new Android project and name it Provider. 2. Add the following statements in bold to the main.xml fi le: <?xml version=”1.0” encoding=” utf-8”?> <LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android” android:layout_width=”fill_parent” android:layout_height=”fill_parent” android:orientation=”vertical” > <ListView android:id=”@+id/android:list” android:layout_width=”fill_parent” android:layout_height=”wrap_content” android:layout_weight=”1” android:stackFromBottom=”false” android:transcriptMode=”normal” /> <TextView 173 android:id=”@+id/contactName” android:textStyle=”bold” android:layout_width=”wrap_content” android:layout_height=”wrap_content” /> CU IDOL SELF LEARNING MATERIAL (SLM)

<TextView 174 android:id=”@+id/contactID” android:layout_width=”fill_parent” android:layout_height=”wrap_content” /> </LinearLayout> 3. In the ProviderActivity.java class, code the following: package net.learn2develop.Provider; import android.app.ListActivity; import android.content.CursorLoader; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.ContactsContract; import android.widget.CursorAdapter; import android.widget.SimpleCursorAdapter; public class ProviderActivity extends ListActivity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Uri allContacts = Uri.parse(“content://contacts/people”); Cursor c; if (android.os.Build.VERSION.SDK_INT <11) { //---before Honeycomb--- c = managedQuery(allContacts, null, null, null, null); } else { //---Honeycomb and later--- CursorLoader cursorLoader = new CursorLoader( this, CU IDOL SELF LEARNING MATERIAL (SLM)

allContacts, 175 null, null, null , null); c = cursorLoader.loadInBackground(); } String[] columns = new String[] { ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts._ID}; int[] views = new int[] {R.id.contactName, R.id.contactID}; SimpleCursorAdapter adapter; if (android.os.Build.VERSION.SDK_INT <11) { //---before Honeycomb--- adapter = new SimpleCursorAdapter( this, R.layout.main, c, columns, views); } else { //---Honeycomb and later--- adapter = new SimpleCursorAdapter( this, R.layout.main, c, columns, views, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); } this.setListAdapter(adapter); } } 4. Add the following statements in bold to the AndroidManifest.xml fi le: <?xml version=“1.0“ encoding=“utf-8“?> <manifest xmlns:android=“http://schemas.android.com/apk/res/android“ package=”net.learn2develop.Provider” android:versionCode=”1” android:versionName=”1.0” > CU IDOL SELF LEARNING MATERIAL (SLM)

<uses-sdk android:minSdkVersion=”14” /> <uses-permission android:name=”android.permission.READ_CONTACTS”/> <application android:icon=”@drawable/ic_launcher” android:label=”@string/app_name” > <activity android:label=”@string/app_name” android:name=”.ProviderActivity” > <Intent-filter> <action android:name=”android.intent.action.MAIN” /> <category android:name=”android.intent.category.LAUNCHER” /> </intent-filter> </activity> </application> </manifest> 5. Launch an AVD and create a few contacts in the Android Emulator. To add a contact, go to the Phone application and click the Star icon at the top. Click the MENU button on the emulator and click the new contact menu item. You will be warned about backing up your contacts. Click the Keep Local button and enter the name, phone number, and e-mail address of a few people. 6. Press F11 to debug the application on the Android emulator. Figure 8.5: Content Provider 176 CU IDOL SELF LEARNING MATERIAL (SLM)

Figure 8.6: Content Provider 8.4.3 How to Create and Use your own Content Provider Creating your own content provider in Android is relatively simple. All you need to do is extend the abstract ContentProvider class and override the various methods defined within it. In this section, you will learn how to create a simple content provider that stores a list of books. Extending from Android’s Content Provider class ensures that the new Content Provider will be recognized as a valid provider. In addition, it will override all the necessary methods for manipulating data. The on Create method is called to initialize the provider. Inside the class you can see 6 methods: on Create, insert, query, delete, update, and get Type. All these methods are required to build a complete Content Provider. OnCreateis where we should initialize anything we need to setup and access our underlying data source. For now, we work with SQLITE database. So, it’s a good place to give it a way to open that database. We do it by the following steps:  Declaring a private member variable of the DBHelper class  In on Create we will assign it to a new DB Helper class passing in the context  on Create should now return TRUE 8.5 SUMMARY  A service is an application in Android that runs in the background without needing to interact with the user. For example, while using an application, you may want to play 177 CU IDOL SELF LEARNING MATERIAL (SLM)

some background music at the same time. In this case, the code that is playing the background music has no need to interact with the user, and hence it can be run as a service.  The best way to understand how a service works is by creating one. The following Try It Out shows you the steps to create a simple service. Subsequent sections add more functionality to this service. For now, you will learn how to start and stop a service.  So far, you’ve looked at using Intents to start new application components, but you can also use Intents to broadcast messages anonymously between components via the send Broadcast method. As a system-level message-passing mechanism, Intents are capable of sending structured messages across process boundaries.  If you want an Activity in your app to respond to an implicit Intent (from your own app or other apps), declare one or more Intent filters in the AndroidManifest.xml file. Each Intent filter specifies the type of Intent it accepts based on the action, data, and category for the Intent. The system will deliver an implicit Intent to your app component only if that Intent can pass through one of your Intent filters.  To find an Activity or other component that can handle your Intent requests, the Android system matches your implicit Intent with an Activity whose Intent filters indicate that they can perform that action. If there are multiple apps installed that match, the user is presented with an app chooser that lets them select which app they want to use to handle that Intent.  A splash screen is mostly the first screen of the app when it is opened. It is a constant screen which appears for a specific amount of time, generally shows for the first time when the app is launched. Android 12 ads the Splash Screen API, which enables a new app, launch animation for all apps. This includes an into-app motion at launch, a splash screen showing your app icon, and a transition to your app itself.  A more flexible use of Intent is the implicit intent. You don't specify the exact activity (or other component) to run instead, you include just enough information in the intent about the task you want to perform. The Android system matches the information in your request intent with any activity available on the device that can perform that task. If there's only one activity that matches, that activity is launched. If more than one activity matches the intent, the user is presented with an app chooser and picks which app they would like to perform the task.  The Local Broadcast Manager was introduced to the Android Support Library to simplify the process of registering for, and sending, broadcast Intents between components within your application. Because of the reduced broadcast scope, using the Local Broadcast Manager is more efficient than sending a global broadcast. 178 CU IDOL SELF LEARNING MATERIAL (SLM)

 A content provider manages access to a central repository of data. A provider is part of an Android application, which often provides its own UI for working with the data. However, content providers are primarily intended to be used by other applications, which access the provider using a provider client object. Together, providers and provider clients offer a consistent, standard interface to data that also handles inter- process communication and secure data access. 8.6 KEYWORDS  Services in Android are a special component that facilitates an application to run in the background in order to perform long-running operation tasks. A service can run continuously in the background even if the application is closed or the user switches to another application.  Broadcast receiver (receiver) is an Android component which allows you to register for system or application events. All registered receivers for an event are notified by the Android runtime once this event happens.  Content provider manages access to a central repository of data. A provider is part of an Android application, which often provides its own UI for working with the data. However, content providers are primarily intended to be used by other applications, which access the provider using a provider client object. Together, providers and provider clients offer a consistent, standard interface to data that also handles inter- process communication and secure data access.  Intent filter is an expression in an app's manifest file that specifies the type of intents that the component would like to receive. For instance, by declaring an intent filter for an activity, you make it possible for other apps to directly start your activity with a certain kind of intent.  Sticky Intent is also a type of Intent which allows communication between a function and a service sendSticky Broadcast performs a send Broadcast known as sticky, the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of register Receiver. In all other ways, this behaves the same as sendBroadcast(Intent). 8.7 LEARNING ACTIVITY 1. Which are the services you are using an application in background? ___________________________________________________________________________ __________________________________________________________________________ 2. Find the use of Broadcast receivers. 179 CU IDOL SELF LEARNING MATERIAL (SLM)

___________________________________________________________________________ __________________________________________________________________________ 8.8 UNIT END QUESTIONS A. Descriptive Questions Short Questions 1. Explain the Broadcasting Events with Intents. 2. Write a note on Services. 3. What are content providers? 4. Elaborate Broadcasting Ordered Intents. 5. How to create a service that runs in the background? Long Questions 1. Explain Services 2. What is Broadcast Receivers? Explain Introducing the Local Broadcast Manager. 3. Explain Broadcasting Ordered Intents and Broadcasting Sticky Intents. 4. Discuss Using Intents to Broadcast Events and Broadcasting Events with Intents. 5. What are content providers? How to use a content provider in Android? B. Multiple Choice Questions 1. What is a service is started when component calls? a. On Create b. OnStart Command c. Start Service d. Start 2. What is a service that is bound when another component calls? a. Bind Service b. bind c. Both a and b d. None of these 3. What is broadcast receiver in android? 180 a. It will react on broadcast announcements. CU IDOL SELF LEARNING MATERIAL (SLM)

b. It will do background functionalities as services. c. It will pass the data between activities. d. None of these 4. To query a content provider, you specify the query string in the form of a URI. The format of the query URI is as follows: <standard_prefix>://<authority>/<data_path>/<id> What you will write in place of <standard_prefix> ? a. content b. object c. ContentProvider d. None of these. 5. Which component handle background processing associated with an application? a. Activities b. Services c. Broadcast Receivers d. Content Providers Answers 1-c, 2- a, 3-a, 4- a, 5- b 8.9REFERENCES Reference  Zigurd Mednieks, Laird Dornin, Blake Meike G, and Masumi Nakamura, 2011, “Programming Android”, O’Reilly books.  Raju Kumar Mishra, 2017, PySpark Recipes.  John Ciliberti, 2013, ASP.NET MVC 4 Recipes. Textbooks  Chris F.A Johnson · 2007, Shell Scripting Recipes.  Wei - Meng Le, 2012, Beginning Android 4 Application Development”, John Wiley & Sons, Inc. 181 CU IDOL SELF LEARNING MATERIAL (SLM)

 Reto Meier, 2012, Professional Android 4 Application Development”, John Wiley & Sons, Inc. Websites  https://www.raywenderlich.com/  https://developer.android.com/  https://www.geeksforgeeks.org/  https://medium.com/ 182 CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT 9: ANDROID FRAGMENTS STRUCTURE 9.0 Learning Objectives 9.1 Introduction 9.2 Fragment and its Life Cycle 9.3 Tabbed Activity with Fragments 9.4 Summary 9.5 Keywords 9.6 Learning Activity 9.7 Unit End Questions 9.8 References 9.0 LEARNING OBJECTIVES After studying this unit, you will be able to:  Learn the Fragment.  Comprehend Fragment Life Cycle.  Explain the Tabbed Activity with Fragments. 9.1 INTRODUCTION Fragments enable you to divide your Activities into fully encapsulated reusable components, each with its own lifecycle and UI. The primary advantage of Fragments is the ease with which you can create dynamic and flexible UI designs that can be adapted to suite a range of screen sizes from small-screen smartphones to tablets. Each Fragment is an independent module that is tightly bound to the Activity into which it is placed. Fragments can be reused within multiple activities, as well as laid out in a variety of combinations to suit multilane tablet UIs and added to, removed from, and exchanged within a running Activity to help build dynamic UIs. Fragments provide a way to present a consistent UI optimized for a wide variety of Android device types, screen sizes, and device densities. Although it is not necessary to divide your Activities (and their corresponding layouts) into Fragments, doing so will drastically improve the flexibility of your UI and make it easier for you to adapt your user experience for new device configurations. 183 CU IDOL SELF LEARNING MATERIAL (SLM)

A Fragment is a piece of an activity which enable more modular activity design. A fragment encapsulates functionality so that it is easier to reuse within activities and layouts. Android devices exist in a variety of screen sizes and densities. Fragments simplify the reuse of components in different layouts and their logic. You can build single-pane layouts for handsets and multi-pane layouts for tablets. You can also use fragments also to support different layout for landscape and portrait orientation on a smartphone. A fragment can be used in multiple activities. Fragment life cycle is closely related to the life cycle of its host activity which means when the activity is paused all the fragments available in the activity will also be stopped. A fragment can implement a behaviour that has no user interface component. A Fragment represents a reusable portion of your app's UI. A fragment defines and manages its own layout, has its own lifecycle, and can handle its own input events. Fragments cannot live on their own they must be hosted by an activity or another fragment.According to the Android documentation, a fragment is a part of applications user interface that is bound to an activity. Fragments have their lifecycle and layouts or UI components. Fragments help enrich your UI design, pass data between different screens, and adapt to different device configurations. A Fragment is a combination of an XML layout file and a java class much like an Activity. Using the support library, fragments are supported back to all relevant Android versions. Fragments encapsulate views and logic so that it is easier to reuse within activities.When a user navigates and interacts with your app, your fragments transition through various states in their lifecycle as they are added, removed, and enters or exits the screen. To manage lifecycle, Fragment implements LifecycleOwner, exposing a Lifecycle object that you can access through the getLifecycle method. Figure: 9.1: Fragmentation of Tablet and Handset 184 CU IDOL SELF LEARNING MATERIAL (SLM)

9.2 FRAGMENT AND ITS LIFE CYCLE The lifecycle events of a Fragment mirror those of its parent Activity; however, after the containing Activity is in its active resumedstate adding or removing a Fragment will affect its lifecycle independently. Fragments include a series of event handlers that mirror those in the Activity class. They are triggered as the Fragment is created, started, resumed, paused, stopped, and destroyed. Fragments also include several additional call-backs that signal binding and unbinding the Fragment from its parent Activity, creation (and destruction) of the Fragment’s View hierarchy, and the completion of the creation of the parent Activity. Figure: 9.2: Fragment lifecycle The skeleton code in listing 4-5 shows the stubs for the lifecycle handlers available in a Fragment. Comments within each stub describe the actions you should consider taking on each state change event. LISTING 4-5: Fragment lifecycle event handlers  Package com PAAD fragments; 185  Import android app Activity;  Import android app Fragment;  Import android OS Bundle;  Import android view LayoutIn flatter;  Import android. View;  Import android view Group;  public class MySkeletonFragment extends Fragment // called when the Fragment is attached to its parent Activity. CU IDOL SELF LEARNING MATERIAL (SLM)

@Override 186 Public void on Attach (Activity activity) { Super. OnAttach (activity); // Get a reference to the parent Activity. } // called to do the initial creation of the Fragment. @Override Public void onCreate(Bundle savedInstance State) Super. On Create // Initialize the Fragment. } // called once the Fragment has been created in order for it to // create its user interface. @Override Public View onCreateView ViewGroup container, Bundle savedInstanceState) { // create, or inflate the Fragment’s UI, and return it. // If this Fragment has no UI then return null. Returninflater.inflate(R.layout.my_fragment, container, false); } // called once the parent Activity and the Fragment’s UI have // been created. @Override Public void onActivity Created super.onActivityCreated(savedInstanceState); CU IDOL SELF LEARNING MATERIAL (SLM)

// complete the Fragment initialization – particularly anything 187 // that requires the parent Activity to be initialized or the // Fragment’s view to be fully inflated. } // called at the start of the visible lifetime. @Override Public void onStart () { Super. OnStart (); // apply any required UI change now that the Fragment is visible. } // called at the start of the active lifetime. @Override Public void on Resume () { Super. On Resume (); // Resume any paused UI updates, threads, or processes required // by the Fragment but suspended when it became inactive. } // Called at the end of the active lifetime. @Override Public void onPause(){ // suspend UI updates, threads, or CPU intensive processes // that don’t need to be updated when the Activity isn’t // the active foreground activity. // persist all edits or state changes // as after this call the process is likely to be killed. Super. On Pause (); CU IDOL SELF LEARNING MATERIAL (SLM)

} 188 // called to save UI state changes at the // end of the active lifecycle. @Override Public void onSaveInstanceState(Bundle savedInstanceState) { // Save UI state changes to the savedInstanceState. // this bundle will be passed to onCreate, onCreateView, and // onCreateView if the parent Activity is killed and restarted. Super.onSaveInstanceState} // called at the end of the visible lifetime. @Override Public void on Stop () { // suspend remaining UI updates, threads, or processing // that aren’t required when the Fragment isn’t visible. Super. On Stop(); } // called when the Fragment’s View has been detached. @Override Public void onDestroyView() { // clean up resources related to the View. Super. on DestroyView(); } // called at the end of the full lifetime. @Override Public void onDestroy(){ // clean up any resources including ending threads, CU IDOL SELF LEARNING MATERIAL (SLM)

// closing database connections etc. Super onDestroy(); } // called when the Fragment has been detached from its parent Activity. @Override Public void on Detach () { Super. On Detach(); } } Figure 9.3: Output of fragment example 189 Fragment-Specific Lifecycle Events CU IDOL SELF LEARNING MATERIAL (SLM)

Most of the Fragment lifecycle events correspond to their equivalents in the Activity class. Those that remain are specific to Fragments and the way in which they’re inserted into their parent Activity. Attaching and Detaching Fragments from the Parent Activity The full lifetime of your Fragment begins when it’s bound to its parent Activity and ends when it’s been detached. These events are represented by the calls to onAttach and onDetach, respectively. As with any handler called after a Fragment/Activity has become paused, it’s possible that onDetach will not be called if the parent Activity’s process is terminated without completing its full lifecycle. The onAttach event is triggered before the Fragment’s UI has been created, before the Fragment itself or its parent Activity have finished their initialization. Typically, the onAttach event is used to gain a reference to the parent Activity in preparation for further initialization tasks. Creating and Destroying Fragments The created lifetime of your Fragment occurs between the first call to on Create and the final call to onDestroy. As it’s not uncommon for an Activity’s process to be terminated without the corresponding onDestroy method being called, so a Fragment can’t rely on its onDestroy handler being triggered. As with Activities, you should use the onCreate method to initialize your Fragment. Its good practice to create any class scoped objects here to ensure they’re created only once in the Fragment’s lifetime. Creating and Destroying User Interfaces A Fragment’s UI is initialized within a new set of event handlers: onCreateView and onDestroy View, respectively Use the onCreateView method to initialize your Fragment: Inflate the UI, get references the Views it contains, and then create any required Services and Timers. Once you have inflated your View hierarchy, it should be returned from this handler: If your Fragment needs to interact with the UI of its parent Activity, wait until the onActivityCreated event has been triggered. This signifies that the containing Activity has completed its initialization and its UI has been fully constructed. Fragment States The fate of a Fragment is inextricably bound to that of the Activity to which it belongs. As a result, Fragment state transitions are closely related to the corresponding Activity state transitions. Like Activities, Fragments are active when they belong to an Activity that is focused and in the foreground. When an Activity is paused or stopped, the Fragments it contains are also paused and stopped, and the Fragments contained by an inactive Activity are also inactive. When an Activity is finally destroyed, each Fragment it contains is likewise destroyed. As the 190 CU IDOL SELF LEARNING MATERIAL (SLM)

Android memory manager nondeterministically closes applications to free resources, the Fragments within those Activities are also destroyed. While Activities and their Fragments are tightly bound, one of the advantages of using Fragments to compose your Activity’s UI is the flexibility to dynamically add or remove Fragments from an active Activity. As a result, each Fragment can progress through its full, visible, and active lifecycle several times within the active lifetime of its parent Activity. Whatever the trigger for a Fragment’s transition through its lifecycle, managing its state transitions is critical in ensuring a seamless user experience. There should be no difference in a Fragment moving from a paused, stopped, or inactive state back to active, so it’s important to save all UI state and persist all data when a Fragment is paused or stopped. Like an Activity, when a Fragment becomes active again, it should restore that saved state. Introducing the Fragment Manager Each Activity includes a Fragment Manager to manage the Fragments it contains. You can access the Fragment Manager using the getFragmentManager Method: FragmentManager FragmentManager = getFragmentManager. The Fragment Manager provides the methods used to access the Fragments currently added to the Activity, and to perform Fragment Transaction to add, remove, and replace Fragments. Adding Fragments to Activities The simplest way to add a Fragment to an Activity is by including it within the Activity’s layout using the fragment tag, as shown in listing 4-6. LISTING 4-6: Adding Fragments to Activities using XML layouts <?xml version=”1.0” encoding=”utf-8”?> <LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android” android:orientation=”horizontal” android:layout_width=”match_parent” android:layout_height=”match_parent”> <fragment android:name=”com.paad.weatherstation.MyListFragment” android:id=”@+id/my_list_fragment” android:layout_width=”match_parent” android:layout_height=”match_parent” android:layout_weight=”1” /> <fragment android:name=”com.paad.weatherstation.DetailsFragment” 191 CU IDOL SELF LEARNING MATERIAL (SLM)

android:id=”@+id/details_fragment” android:layout_width=”match_parent” android:layout_height=”match_parent” android:layout_weight=”3” /> </LinearLayout> Once the Fragment has been inflated, it becomes a View Group, laying out and managing its UI within the Activity. This technique works well when you use Fragments to define a set of static layouts based on various screen sizes. If you plan to dynamically modify your layouts by adding, removing, and replacing Fragments at run time, a better approach is to create layouts that use container Views into which Fragments can be placed at runtime, based on the current application state. Listing 4-7 shows an XML snippet that you could use to support this latter approach. LISTING 4-7: Specifying Fragment layouts using container views <?xml version=”1.0” encoding=”utf-8”?> <LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android” android:orientation=”horizontal” android:layout_width=”match_parent” android:layout_height=”match_parent”> <FrameLayout android:id=”@+id/ui_container” android:layout_width=”match_parent” android:layout_height=”match_parent” android:layout_weight=”1” /> <FrameLayout android:id=”@+id/details_container” android:layout_width=”match_parent” android:layout_height=”match_parent” android:layout_weight=”3” /> 192 CU IDOL SELF LEARNING MATERIAL (SLM)

</LinearLayout> You then need to create and add the corresponding Fragments to their appropriate parent containers within the onCreate handler of your Activity using Fragment Transactions, as described in the next section. Using Fragment Transactions Fragment Transactions can be used to add, remove, and replace Fragments within an Activity at run time. Using Fragment Transactions, you can make your layouts dynamic that is, they will adapt and change based on user interactions and application state. Each Fragment Transaction can include any combination of supported actions, including adding, removing, or replacing Fragments. They also support the specification of the transition animations to display and whether to include the Transaction on the back stack. A new Fragment Transaction is created using the beginTransaction method from the Activity’s Fragment Manager. Modify the layout using the add, remove, and replace methods, as required, before setting the animations to display, and setting the appropriate back-stack behaviour. When you are ready to execute the change, call commit to add the transaction to the UI queue. FragmentTransaction fragmentTransaction = fragment Manager begin Transaction // add, remove, and/or replace Fragments. // specify animations. // add to back stack if required. Fragment Transaction commit; Each of these transaction types and options will be explored in the following sections. Adding, Removing, and Replacing Fragments When adding a new UI Fragment, specify the Fragment instance to add, along with the container View into which the Fragment will be placed. Optionally, you can specify a tag that can later be used to find the Fragment by using the findFragment by Tag method: FragmentTransaction fragmentTransaction = fragment Manager begin Transaction; FragmentTransaction. Add Fragment Transaction. Commit; To remove a Fragment, you first need to find a reference to it, usually using either the Fragment Manager’s findFragment by Id or findFragment by Tag methods. Then pass the found Fragment instance as a parameter to the remove method of a Fragment Transaction: FragmentTransaction fragmentTransaction = fragmentManager. Begin Transaction; 193 CU IDOL SELF LEARNING MATERIAL (SLM)

Fragment = fragment Manager findFragment by Id Fragment Transaction removes FragmentTransaction.commit You can also replace one Fragment with another. Using the replace method, specify the container ID containing the Fragment to be replaced, the Fragment with which to replace it, and a tag to identify the newly inserted Fragment. FragmentTransaction fragment Transaction = fragment Manager beginTransaction; FragmentTransaction. Replace New DetailFragment Fragment Transaction. Commit; Using the Fragment Manager to Find Fragments To find Fragments within your Activity, use the Fragment Manager’s finds FragmentById method. If you have added your Fragment to the Activity layout in XML, you can use the Fragment’s resource identifier: MyFragment myFragment = Fragment Manager fineFragmentbyId; If you’ve added a Fragment using a Fragment Transaction, you should specify the resource identifier of the container View to which you added the Fragment you want to find. Alternatively, you can use the findFragmentByTag method to search for the Fragment using the tag you specified in the Fragment Transaction: MyFragment mFragment = Fragment Manager FragmentbyTag(MY_FRAGMENT_TAG); Later in this chapter you’ll be introduced to Fragments that don’t include a UI. The find FragmentbyTag method is essential for interacting with these Fragments. Because they’re not part of the Activity’s View hierarchy, they don’t have a resource identifier or a container resource identifier to pass in to the findFragmentById method. Populating Dynamic Activity Layouts with Fragments If you’re dynamically changing the composition and layout of your Fragments at run time, it’s good practice to define only the parent containers within your XML layout and populate it exclusively using Fragment Transactions at run time to ensure consistency when configuration changes cause the UI to be re-created. Listing 4-8 shows the skeleton code used to populate an Activity’s layout with Fragments at run time. 194 CU IDOL SELF LEARNING MATERIAL (SLM)

LISTING 4-8: Populating Fragment layouts using container views Public void on Create (Bundle saved Instance State) Super onCreate(savedInstanceState); // inflate the layout containing the Fragment containers SetContentView FragmentManager fm = getFragmentManager; // Check to see if the Fragment back stack has been populated // If not, create and populate the layout. DetailsFragment detailsFragment = (DetailsFragment)fm.findFragmentById(R.id.details_container); if (detailsFragment == null) { FragmentTransaction ft = fm.beginTransaction; ft.add(R.id.details_container, new DetailsFragment; ft.add(R.id.ui_container, new MyLis tFragment ft.commit; You should first check if the UI has already been populated based on the previous state. To ensure a consistent user experience, Android persist the Fragment layout and associated back stack when an Activity is restarted due to a configuration change. For the same reason, when creating alternative layouts for run time configuration changes, it’s considered good practice to include any view containers involved in any transactions in all the layout variations. Failing to do so may result in the Fragment Manager attempting to restore Fragments to containers that don’t exist in the new layout. To remove a Fragment container in each orientation layout, simply mark its visibility attribute as gone in your layout definition, as shown in Listing 4-9. LISTING 4-9: Hiding Fragments in layout variations <?xml version=”1.0” encoding=”utf-8”?> <LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android” android:orientation=”horizontal” android:layout_width=”match_parent” android:layout_height=”match_parent”> <FrameLayout android:id=”@+id/ui_container” 195 CU IDOL SELF LEARNING MATERIAL (SLM)

android:layout_width=”match_parent” android:layout_height=”match_parent” android:layout_weight=”1” /> <FrameLayout android:id=”@+id/details_container” android:layout_width=”match_parent” android:layout_height=”match_parent” android:layout_weight=”3” android:visibility=”gone” /> </LinearLayout> Fragments and the Back Stack The logical stacking of Activities that is no longer visible which allow users to navigate back to previous screens using the back button. Fragments enable you to create dynamic Activity layouts that can be modified to present significant changes in the UIs. In some cases, these changes could be considered a new screen in which case a user may reasonably expect the back button to return to the previous layout. This involves reversing previously executed Fragment Transactions. Android provides a convenient technique for providing this functionality. To add the Fragment Transaction to the back stack, call addsToBackStack on a Fragment Transaction before calling commit. Fragment Transaction fragmentTransaction = fragmentManager. BeginTransaction FragmentTransaction.Add (R.id.ui_container, new MyList Fragment; Fragment = fragmentManager.findFragmentById(R.id.details_fragment); FragmentTransaction. Remove (fragment); String tag = null; FragmentTransaction. AddtoBackStack (tag); FragmentTransaction.commit; Pressing the Back button will then reverse the previous Fragment Transaction and return the UI to the earlier layout. When the Fragment Transaction shown above is committed, the Details Fragment is stopped and moved to the back stack, rather than simply destroyed. If the Transaction is reversed, the List Fragment is destroyed, and the Details Fragment is restarted. 196 CU IDOL SELF LEARNING MATERIAL (SLM)

Animating Fragment Transactions To apply one of the default transition animations, use the setTransition method on any Fragment Transaction, passing in one of the FragmentTransaction.TRANSIT_FRAGMENT constants.transaction.setTransition (FragmentTransaction.TRANSIT_FRAGMENT_OPEN); You can also apply custom animations to Fragment Transactions by using the setCustom Animations method. This method accepts two animation XML resources: one for Fragments that are being added to the layout by this transaction and another for Fragments being removed: fragment Transaction. Set CustomAnimations This is a particularly useful way to add seamless dynamic transitions when you are replacing Fragments within your layout. Interfacing Between Fragments and Activities Use the getActivity method within any Fragment to return a reference to the Activity within which it’s embedded. This is particularly useful for finding the current Context, accessing other Fragments using the Fragment Manager, and finding Views within the Activity’s View hierarchy. TextView textView = (TextView)getActivity().findViewById(R.id.textview); Although it’s possible for Fragments to communicate directly using the host Activity’s Fragment Manager, it’s generally considered better practice to use the Activity as an intermediary. This allows the Fragments to be as independent and loosely coupled as possible, with the responsibility for deciding how an event in one Fragment should affect the overall UI falling to the host Activity, Where your Fragment needs to share events with its host Activity, its good practice to create a call-back interface within the Fragment that a host Activity must implement. Listing 4-10 shows a code snippet from within a Fragment class that defines a public event listener interface. The onAttach handler is overridden to obtain a reference to the host Activity, confirming that it implements the required interface. Fragments Without User Interfaces In most circumstances, Fragments are used to encapsulate modular components of the UI; however, you can also create a Fragment without a UI to provide background behaviour that persists across Activity restarts. This is particularly well suited to background tasks that regularly touch the UI or where it’s important to maintain state across Activity restarts caused by configuration changes. You can choose to have an active Fragment retain its current instance when its parent Activity is recreated using the setRetainInstance method. After you call this method, the Fragment’s lifecycle will change. Rather than being destroyed and re- created with its parent Activity, the same Fragment instance is retained when the Activity restarts. It will receive the onDetach event when the parent Activity is destroyed, followed by 197 CU IDOL SELF LEARNING MATERIAL (SLM)

the onAttach, onCreateView, and onActivityCreated events as the new parent Activity is instantiated. Android Fragment Classes The Android SDK includes several Fragment subclasses that encapsulate some of the most CommonFragment implementations,some of the more useful ones are listed here:  DialogFragment — A Fragment that you can use to display a floating Dialog over the parent Activity. You can customize the Dialog’s UI and control its visibility directly via the Fragment API. “Expanding the User Experience.”  ListFragment — a wrapper class for Fragments that feature a ListView bound to a data source as the primary UI metaphor. It provides methods to set the Adapter to use and exposes the event handlers for list item selection. The List Fragment is used as part of the To-Do List example in the next section.  WebViewFragment — A wrapper class that encapsulates a WebView within a Fragment. The child WebView will be paused and resumed when the Fragment is paused and resumed. 9.3 TABBED ACTIVITY WITH FRAGMENTS Create a new android application using android studio and give names as TabsExample. In case if you are not aware of creating an app in android studio check this article Android Hello World App. To start creating the tabs layout in our android application, we need to add the following libraries in dependencies section of build grade file in Module section like as shown below. Dependencies  compile 'com.android.support:appcompat-v7:25.3.1'  compile 'com.android.support:design:25.3.1' Here we are going to show the tabs using android ToolBar and TabLayout so we need to remove the actionbar from a layout using styles, for that open styles.xml file from /res/values folder and that should contain the code like as shown below. styles.xml <resources> <!-- Base application theme. --> <style name=\"AppTheme\" parent=\"Theme.AppCompat.Light.DarkActionBar\"> <!-- Customize your theme here. --> 198 CU IDOL SELF LEARNING MATERIAL (SLM)

<item name=\"colorPrimary\">@color/colorPrimary</item> <item name=\"colorPrimaryDark\">@color/colorPrimaryDark</item> <item name=\"colorAccent\">@color/colorAccent</item> <item name=\"windowActionBar\">false</item> <item name=\"windowNoTitle\">true</item> </style> </resources> To show the different tabs using fragments and ViewPager in our android application, we need to create different fragments and layouts like as shown below. Now create layout resource file homelayout.xml in \\res\\layout path, for that right-click on your layout folder à Go to New à select Layout Resource File and give name as homelayout.xml. Once we create a new layout resource file homelayout.xml, open it and write the code like as shown below homelayout.xml <?xml version=\"1.0\" encoding=\"utf-8\"?> <RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\"> <TextView android:id=\"@+id/textView\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:text=\"Homw Tab\" android:textAppearance=\"?android:attr/textAppearanceLarge\"/> </RelativeLayout> Now we need to create fragment file HomeFragment.java in \\java\\com.tutlanetabsexample path, for that right click on your application folder à Go to New à select Java Class and give name as HomeFragment.java. 199 CU IDOL SELF LEARNING MATERIAL (SLM)

9.4 SUMMARY  Fragments enable you to divide your Activities into fully encapsulated reusable components, each with its own lifecycle and UI. The primary advantage of Fragments is the ease with which you can create dynamic and flexible UI designs that can be adapted to suite a range of screen sizes from small-screen smartphones to tablets.  The lifecycle events of a Fragment mirror those of its parent Activity; however, after the containing Activity is in its active resumed state adding or removing a Fragment will affect its lifecycle independently. Fragments include a series of event handlers that mirror those in the Activity class.  The full lifetime of your Fragment begins when it’s bound to its parent Activity and ends when it’s been detached. These events are represented by the calls to onAttach and onDetach, respectively. As with any handler called after a Fragment/Activity has become paused, it’s possible that onDetach will not be called if the parent Activity’s process is terminated without completing its full lifecycle. The onAttach event is triggered before the Fragment’s UI has been created before the Fragment itself or its parent Activity have finished their initialization. Typically, the onAttach event is used to gain a reference to the parent Activity in preparation for further initialization tasks.  The fate of a Fragment is inextricably bound to that of the Activity to which it belongs. As a result, Fragment state transitions are closely related to the corresponding Activity state transitions.  Like Activities, Fragments are active when they belong to an Activity that is focused and in the foreground. When an Activity is paused or stopped, the Fragments it contains are also paused and stopped, and the Fragments contained by an inactive Activity are also inactive. When an Activity is finally destroyed, each Fragment it contains is likewise destroyed. As the Android memory manager nondeterministically closes applications to free resources, the Fragments within those Activities are also destroyed.  In most circumstances, Fragments are used to encapsulate modular components of the UI; however, you can also create a Fragment without a UI to provide background behaviour that persists across Activity restarts.  Create a new android application using android studio and give names as TabsExample. In case if you are not aware of creating an app in android studio check this article Android Hello World App.  The logical stacking of Activities that is no longer visible which allow users to navigate back to previous screens using the back button. Fragments enable you to create dynamic Activity layouts that can be modified to present significant changes in 200 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