Homework Assignments: Lesson 7 & 8

Contents:

7.1: Create an AsyncTask

Build and run an app

Open the SimpleAsyncTask app that you created in the Create an AsyncTask lesson. Add a ProgressBar that displays the percentage of sleep time completed. The progress bar fills up as the AsyncTask thread sleeps from a value of 0 to 100 (percent).

Hint: Break up the sleep time into chunks.

AsyncTask reference: developer.android.com/reference/android/os/AsyncTask.html Progress bar updates as the task progresses

Answer these questions

Question 1

For a ProgressBar:

  1. How do you determine the range of values that a ProgressBar can show?
  2. How do you change how much of the progress bar is filled in?

Question 2

If an AsyncTask is defined as follows:

 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long>
  1. What is the type of the value that is passed to doInBackground() in the AsyncTask?
  2. What is the type of the value that is passed to the callback that reports the progress of the task?
  3. What is the type of the value that is passed to the callback that is executed when the task completes?

Question 3

To report progress of the work executed by an AsyncTask, what callback method do you implement, and what method do you call in your AsyncTask subclass?

  • Implement publishProgress(). Call publishProgress().
  • Implement publishProgress(). Call onProgressUpdate().
  • Implement onProgressUpdate(). Call publishProgress().
  • Implement onProgressUpdate(). Call onProgressUpdate().

Submit your app for grading

Guidance for graders

Check that the app has the following features:

  • The layout includes a ProgressBar that sets the appropriate attributes to determine the range of values.
  • The AsyncTask breaks the total sleep time into chunks and updates the progress bar after each chunk.
  • The AsyncTask calls the appropriate method and implements the appropriate callback to update the progress bar.
  • The AsyncTask needs to know which views to update. Depending on whether the AsyncTask is implemented as an inner class or not, the views can either be passed to the constructor of the AsyncTask or defined as member variables on the Activity.

7.2: Connect to the Internet

Build and run an app

Create an app that retrieves and displays the contents of a web page at a URL. The app displays:

  • A field where the user enters a URL
  • A field such as a menu or spinner that allows the user to choose the protocol (HTTP or HTTPS)
  • A button that executes the task when clicked
  • A scrolling display of the source code of the web page at the URL

Use an AsyncTaskLoader to retrieve the source code of the web page at the URL. You need to implement a subclass of AsyncTaskLoader.

If connection to the Internet is not available when the user clicks the button, the app must show the user an appropriate response. For example, it might display a message such as "Check your Internet connection and try again."

The display must contain a TextView in a ScrollView that displays the source code, but the exact appearance of the interface is up to you. Your screen can look different from the screenshots below. You can use a pop-up menu, spinner, or checkboxes to allow the user to select HTTP or HTTPS.

The image on the left shows the starting screen, with a pop-up menu for the protocol. The image on the right shows an example of the results of retrieving the page source for given URL. Retrieve and show the page source for a URL

Answer these questions

Question 1

What permissions does your app need to connect to the Internet?

  • android.permission.CONNECTIVITY
  • android.permission.INTERNET
  • It doesn't need any special permissions; all apps are allowed to connect to the Internet.

Question 2

How does your app check that Internet connectivity is available?

In the manifest:

  • request ACCESS_NETWORK_STATE permission
  • request ALL_NETWORK_STATE permission
  • request NETWORK_CONNECT permission

In the code:

  • Wrap the code to connect to the Internet in a try/catch block, and catch NO_NETWORK errors.
  • Use ConnectivityManager to check for an active network before connecting to the network.
  • Present a dialog to the user reminding them to make sure that Internet connectivity is available before attempting to connect to the Internet.

Question 3

Where do you implement the loader callback method that's triggered when the loader finishes executing its task?

  • In the AsyncTaskLoader subclass. The AsyncTaskLoader must implement LoaderManager.LoaderCallbacks.
  • In the Activity that displays the results of the task. The Activity must implement LoaderManager.LoaderCallbacks.
  • In a Utility class that extends Object and implements LoaderManager.LoaderCallbacks.

Question 4

When the user rotates the device, how do AsyncTask and AsyncTaskLoader behave differently if they are in the process of running a task in the background?

  • Option 1
    • A running AsyncTask becomes disconnected from the Activity even though it keeps executing.
    • A running AsyncTaskLoader becomes disconnected from the Activity but stops running, preserving system resources.
  • Option 2
    • A running AsyncTask becomes disconnected from the Activity but stops running, preserving system resources.
    • A running AsyncTaskLoader automatically restarts execution of its task from the beginning. The Activity displays the results.
  • Option 3
    • A running AsyncTask becomes disconnected from the Activity even though it keeps executing.
    • A running AsyncTaskLoader automatically reconnects to the Activity after the device rotation. The Activity displays the results.

Question 5

How do you initialize an AsyncTaskLoader to perform the steps, such as initializing variables, that must be done before the loader starts performing its background task?

  • In onCreateLoader() in the Activity, create an instance of the AsyncTaskLoader subclass. In the loader's constructor perform initialization tasks.
  • In onCreateLoader() in the Activity, create an instance of the AsyncTaskLoader subclass. In the loader's init() method, perform initialization tasks.
  • In the Activity, implement initLoader() to initialize the loader.
  • Perform initialization tasks for the loader at the start of loadInBackgroud() in the Loader.

Question 6

What methods must an AsyncTaskLoader implement?

Submit your app for grading

Guidance for graders

Check that the app has the following features:

  • The manifest includes requests for the appropriate permissions.
  • Uses a subclass of AsyncTaskLoader.
  • Responds appropriately if the device can't connect to the Internet.
  • Combines the protocol and the web page to create a valid URL that the app uses to connect to the Internet.
  • Implements the required Loader callback methods.
  • Displays the results of retrieving the source of the web page in TextView in a ScrollView. (It's OK to do it in the same Activity, or to start a new Activity.)

7.3: Broadcast Receivers

Build and run an app

  1. Create an app called BroadcastCounter using the Empty Activity template.
  2. Use a BroadcastReceiver to count how many times the ACTION_POWER_CONNECTED broadcast was received. Hint: Define your BroadcastReceiver as an inner class and register it dynamically.
  3. Display the count in a TextView view.

BroadcastReceiver power-connected counter

Answer these questions

Question 1

What are the differences between registering a broadcast receiver statically or dynamically?

  • Registering a broadcast receiver dynamically ties its operation to the lifecycle of your activity.
  • If you register your receiver to receive only local broadcasts, you must register it dynamically; static registration isn't an option.
  • Registering a broadcast receiver statically creates a new process to run your broadcast receiver if no processes associated with your application are running.
  • All of the above.

Question 2

True or false? If a broadcast receiver is registered statically, it responds to broadcast events even if your app is not running.

Question 3

Which class is used to mitigate the security risks of BroadcastReceivers when the broadcasts are not cross-application (that is, they are sent and received by the same app)?

  • SecureBroadcast
  • LocalBroadcastManager
  • OrderedBroadcast
  • SecureBroadcastManager

Submit your app for grading

Guidance for graders

Check that the app has the following features:

  • The broadcast receiver registers and unregisters dynamically in one of the following lifecycle method pairs: OnResume/OnPause, OnCreate/OnDestroy, or OnStart/OnStop.
  • The counter is displayed and is incremented when the phone is plugged in.

8.1: Notifications

Build and run an app

Open the NotifyMe app that you created in the Notifications lesson. Change the updated notification in the app to use the InboxStyle expanded layout instead of BigPictureStyle. Use fake string data for each line and summary text. InboxStyle notification

Note: The notification might look a little different, depending on the API level of the device.

Answer these questions

Question 1

Suppose you create an application that downloads a work of art every day. Once the artwork is available, the app shows a notification to the user, and the user can either download or skip the day's work of art. What PendingIntent method would you use to start a service to download the image?

  • Activity.startService()
  • PendingIntent.getBroadcast()
  • PendingIntent.getActivity()
  • PendingIntent.getService()

Submit your app for grading

Guidance for graders

Check that the app has the following features:

  • When the user taps the update button, the notification becomes an InboxStyle notification with several rows of text representing line items.
  • The screen has a summary and title text line, which changes its position depending on the API level. (See Notifications in the material design guidelines.)
  • Uses the NotificationCompat.InboxStyle class so that it's backwards compatible.

8.2: Alarm Manager

Build and run an app

Make an app that delivers a notification when the time is 11:11 (AM). The screen displays a toggle switch that turns the alarm on and off. AlarmManager delivers a notification at 11:11

Note: The notification might look a little different, depending on the API level of the device.

Answer these questions

Question 1

In which API level did inexact timing become the default for AlarmManager? (All set() methods use inexact timing, unless explicitly stated.)

  • API level 16
  • API level 18
  • API level 19
  • API level 17

Submit your app for grading

Guidance for graders

Check that the app has the following features:

  • The alarm uses exact timing. This means that the code includes a statement checking that the devices API level is > 19, and using the setExact() method if it is.
  • App shows a notification when the time is 11:11 AM.

8.3: JobScheduler

Build and run an app

Create an app that simulates a large download scheduled with battery and data consumption in mind. It contains a button that says "Download Now" and has the following features:

  • It delivers a notification in place of performing an actual download.
  • The "download" is performed once a day, when the phone is idle but connected to power and to WiFi, or when the button is pressed.
  • When the user taps the Download Now button, it triggers a "downloading" notification.
    Hint :Define the JobService class as an inner class. That way, the Download Now button and the JobService can call the same method to deliver the notification.

JobScheduler delivers a notification based on phone status

Note: The notification might look a little different, depending on the API level of the device.

Answer these questions

Question 1

What class do you use if you want features like the ones provided by JobScheduler, but you want the features to work for devices running API level 20 and below?

  • JobSchedulerCompat
  • FirebaseJobDispatcher
  • AlarmManager

Submit your app for grading

Guidance for graders

Check that the app has the following features:

  • The JobInfo object has 4 criteria set: setRequiresCharging(), setPeriodic(), setRequiresDeviceIdle(), setRequiredNetworkType()
  • The app crashes if the JobService class does not have an empty constructor.

results matching ""

    No results matching ""