Appendix C

Answers to Exercises

This appendix includes the answers to the end of chapter exercises.

CHAPTER 1 ANSWERS

1. An AVD is an Android Virtual Device. It represents an Android emulator, which emulates a particular configuration of an actual Android device.

2. The android:versionCode attribute is used to programmatically check whether an application can be upgraded. It should contain a running number (an updated application is set to a higher number than the older version). The android:versionName attribute is used mainly for displaying to the user. It is a string, such as "1.0.1".

3. The strings.xml file is used to store all string constants in your application. This enables you to easily localize your application by simply replacing the strings and then recompiling your application.

CHAPTER 2 ANSWERS

1. The Android OS will display a dialog from which users can choose which activity they want to use.

2. Use the following code:

        Intent i = new
            Intent(android.content.Intent.ACTION_VIEW,
              Uri.parse("http://www.amazon.com"));
        startActivity(i);                

3. In an intent filter, you can specify the following: action, data, type, and category.

4. The Toast class is used to display alerts to the user; it disappears after a few seconds. The NotificationManager class is used to display notifications on the device’s status bar. The alert displayed by the NotificationManager class is persistent and can only be dismissed by the user when selected.

5. You can either use the <fragment> element in the XML file, or use the FragmentManager and FragmentTransaction classes to dynamically add/remove fragments from an activity.

6. One of the main differences between activities and fragments is that when an activity goes into the background, the activity is placed in the back stack. This allows an activity to be resumed when the user presses the Back button. Conversely, fragments are not automatically placed in the back stack when they go into the background.

CHAPTER 3 ANSWERS

1. The dp unit is density independent and 1dp is equivalent to one pixel on a 160 dpi screen. The px unit corresponds to an actual pixel on screen. You should always use the dp unit because it enables your activity to scale properly when run on devices of varying screen size.

2. With the advent of devices with different screen sizes, using the AbsoluteLayout makes it difficult for your application to have a consistent look and feel across devices.

3. The onPause() event is fired whenever an activity is killed or sent to the background. The onSaveInstanceState() event is like the onPause() event, except that it is not always called, such as when the user presses the back button to kill the activity.

4. The three events are onPause(), onSaveInstanceState(), and onRetainNonConfigurationInstance(). You generally use the onPause() method to preserve the activity’s state because the method is always called when the activity is about to be destroyed. However, for screen orientation changes, it is easier to use the onSaveInstanceState() method to save the state of the activity (such as the data entered by the user) using a Bundle object. The onRetainNonConfigurationInstance() method is useful for momentarily saving data (such as images or files downloaded from a web service) which might be too large to fit into a Bundle object.

5. Adding action items to the Action Bar is similar to creating menu items for an options menu — simply handle the onCreateOptionsMenu() and onOptionsItemSelected() events.

CHAPTER 4 ANSWERS

1. You should check the isChecked() method of each RadioButton to determine whether it has been checked.

2. You can use the getResources() method.

3. The code snippet to obtain the current date is as follows:

        //—-get the current date—-
        Calendar today = Calendar.getInstance();
        yr = today.get(Calendar.YEAR);
        month = today.get(Calendar.MONTH);
        day = today.get(Calendar.DAY_OF_MONTH);
        showDialog(DATE_DIALOG_ID);

4. The three specialized fragments are ListFragment, DialogFragment, and PreferenceFragment. The ListFragment is useful for displaying a list of items, such as an RSS listing of news items. The DialogFragment allows you to display a dialog window modally and is useful to get a response from the user before allowing him to continue with your application. The PreferenceFragment displays a window containing your application’s preferences and allows the user to edit them directly in your application.

CHAPTER 5 ANSWERS

1. The ImageSwitcher enables images to be displayed with animation. You can animate the image when it is being displayed, as well as when it is being replaced by another image.

2. The two methods are onCreateOptionsMenu() and onOptionsItemSelected().

3. The two methods are onCreateContextMenu() and onContextItemSelected().

4. To prevent launching the device’s web browser, you need to implement the WebViewClient class and override the shouldOverrideUrlLoading() method.

CHAPTER 6 ANSWERS

1. You can do so using the PreferenceActivity class.

2. The method name is getExternalStorageDirectory().

3. The permission is WRITE_EXTERNAL_STORAGE.

CHAPTER 7 ANSWERS

1. The code is as follows:

        Cursor c; 
        if (android.os.Build.VERSION.SDK_INT <11) {
            //---before Honeycomb---
            c = managedQuery(allContacts, projection, 
                    ContactsContract.Contacts.DISPLAY_NAME + " LIKE ?",
                    new String[] {"%jack"}, 
                    ContactsContract.Contacts.DISPLAY_NAME + " ASC");            
        } else {
            //---Honeycomb and later---
            CursorLoader cursorLoader = new CursorLoader(
                    this, 
                    allContacts, 
                    projection, 
                    ContactsContract.Contacts.DISPLAY_NAME + " LIKE ?",
                    new String[] {"%jack"}, 
                    ContactsContract.Contacts.DISPLAY_NAME + " ASC");
            c = cursorLoader.loadInBackground();            
        }

2. The methods are getType(), onCreate(), query(), insert(), delete(), and update().

3. The code is as follows:

        <provider android:name="BooksProvider"
                android:authorities="net.learn2develop.provider.Books" />

CHAPTER 8 ANSWERS

1. You can either programmatically send an SMS message from within your Android application or invoke the built-in Messaging application to send it on your application’s behalf.

2. The two permissions are SEND_SMS and RECEIVE_SMS.

3. The Broadcast receiver should fire a new intent to be received by the activity. The activity should implement another BroadcastReceiver to listen for this new intent.

CHAPTER 9 ANSWERS

1. The likely reasons are as follows:

  • No Internet connection
  • Incorrect placement of the <uses-library> element in the AndroidManifest.xml file
  • Missing INTERNET permission in the AndroidManifest.xml file

2. Geocoding is the act of converting an address into its coordinates (latitude and longitude). Reverse geocoding converts a pair of location coordinates into an address.

3. The two providers are as follows:

  • LocationManager.GPS_PROVIDER
  • LocationManager.NETWORK_PROVIDER

4. The method is addProximityAlert().

CHAPTER 10 ANSWERS

1. The permission is INTERNET.

2. The classes are JSONArray and JSONObject.

3. The class is AsyncTask.

CHAPTER 11 ANSWERS

1. A separate thread should be used because a service runs on the same process as the calling activity. If a service is long-running, you need to run it on a separate thread so that it does not block the activity.

2. The IntentService class is similar to the Service class, except that it runs the tasks in a separate thread and automatically stops the service when the task has finished execution.

3. The three methods are doInBackground(), onProgressUpdate(), and onPostExecute().

4. The service can broadcast an intent, and the activity can register an intent using an IntentFilter class.

5. The recommended method is to create a class that subclasses the AsyncTask class. This will ensure that the UI is updated in a thread-safe manner.

CHAPTER 12 ANSWERS

1. You specify the minimum Android version required using the minSdkVersion attribute in the AndroidManifest.xml file.

2. To generate a certificate, you can either use the keytool.exe utility from the Java SDK or use Eclipse’s Export feature.

3. Go to the Settings application and select the Security item. Check the “Unknown sources” item.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.147.20