Android Flashcards

1
Q

What are the four Java classes related to the use of sensors on the Android platform, and what is the purpose of each

A

The four Java classes related to the use of sensors on the Android platform are:

Sensor: Provides methods to identify which capabilities are available for a specific sensor.

SensorManager: Provides methods for registering sensor event listeners and calibrating sensors.

SensorEvent: Provides raw sensor data, including information regarding accuracy.

SensorEventListener: Interface that defines callback methods that will receive sensor event notifications.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is a Content Provider, and what is it used for

A

A ContentProvider manages access to a structured set of data. It encapsulates the data and provide mechanisms for defining data security. ContentProvider is the standard interface that connects data in one process with code running in another process.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Under what condition could the code sample below crash your application? How would you modify the code to avoid this potential problem? Explain your answer.

Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, textMessage);
sendIntent.setType(HTTP.PLAIN_TEXT_TYPE); // "text/plain" MIME type
startActivity(sendIntent);
A

An 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. If there is more than one application registered that can handle this request, the user will be prompted to select which one to use.

However, it is possible that there are no applications that can handle your intent. In this case, your application will crash when you invoke startActivity(). To avoid this, before calling startActivity() you should first verify that there is at least one application registered in the system that can handle the intent. To do this use resolveActivity() on your intent object:

    // Verify that there are applications registered to handle this intent
    // (resolveActivity returns null if none are registered)
if (sendIntent.resolveActivity(getPackageManager()) != null) {
    startActivity(sendIntent);
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Describe a scenario where onPause() and onStop() would not be invoked

A

onPause() and onStop() will not be invoked if finish() is called from within the onCreate() method. This might occur, if you detect an error during onCreate() and call finish() as a result. Any cleanup you expected to be done in onPause() and onStop() will not be executed.

Although onDestroy() is the last callback in the lifecycle of an activity, but this callback may not always be called and should not be relied upon to destroy resources. It is better have the resources created in onStart() and onResume(), and have them destroyed in onStop() and onPause(), respectively.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How is the presence of Compass sensor checked?

A
PackageManager m = getPackageManager();
    if (!m.hasSystemFeature(PackageManager.FEATURE_SENSOR_COMPASS)) {
        // This device does not have a compass, turn off the compass feature
    }

Android defines feature IDs, in the form of ENUMs, for any hardware or software feature that may be available on a device. For instance, the feature ID for the compass sensor is FEATURE_SENSOR_COMPASS.

If your application cannot work without a specific feature being available on the system, you can prevent users from installing your app with a element in your app’s manifest file to specify a non-negotiable dependency.

However, if you just want to disable specific elements of your application when a feature is missing, you can use the PackageManager class. PackageManager is used for retrieving various kinds of information related to the application packages that are currently installed on the device.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are three common use cases for an Intent

A

To start an activity: You can start a new instance of an Activity by passing an Intent to startActivity() method.

To start a service: You can start a service to perform a one-time operation (such as download a file) by passing an Intent to startService().

To deliver a broadcast: You can deliver a broadcast to other apps by passing an Intent to sendBroadcast(), sendOrderedBroadcast(), or sendStickyBroadcast().

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What issue might occur if MyService accesses a remote server via an Internet connection, and the Activity is showing a progress indicator animation. How could the issue be addressed?

Intent service = new Intent(context, MyService.class);             
startService(service);
A

The remote service can be slow, and the animation in the activity could freeze because the service was started on the main UI thread. The problem can be avoided by performing remote requests on a background through or by using an asynchronous response mechanism.

Note:
Accessing the network from the UI thread throws a runtime exception in newer Android versions which causes the app to crash.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What might cause a view’s value to not be restored after a screen reorientation

A

The view might not have a valid id. Each view must have a unique ID which is supplied by the android: id attribute.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is DDMS?

A

DDMS is the Dalvik Debug Monitor Server that ships with Android. It provides debugging features including:

  • port-forwarding services
  • screen capture
  • thread and heap information
  • network traffic tracking
  • incoming call and SMS spoofing
  • simulating network state, speed, and latency
  • location data spoofing
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the relationship between the life cycle of an AsyncTask and an Activity? What problems can result, and how can they be avoided?

A

An AsyncTask is not tied to the life cycle of the Activity that contains it. If the Activity is destroyed (and a new one is created), the AsyncTask will not die. When the AsyncTask completes, it will have a reference to the former instance of the Activity which can cause an IllegalArgumentException: View not attached to window manager. This can also result in a memory leak. For long-running tasks, use something else such as a service.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is an Intent, and can it be used to provide data to a ContentProvider?

A

The Intent object is a common mechanism for starting new activity and transferring data from one activity to another. You cannot start a ContentProvider using an Intent.

When you want to access data in a ContentProvider, you must instead use the ContentResolver object in your application’s Context to communicate with the provider as a client. The ContentResolver object communicates with the provider object, an instance of a class that implements ContentProvider. The provider object receives data requests from clients, performs the requested action, and returns the results.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is the difference between a Fragment and an Activity?

A

An activity is typically a single, focused operation that a user can perform (such as dial a number, take a picture, send an email, view a map, etc.).

Activity implementations can optionally make use of the Fragment class for purposes such as producing more modular code, building more sophisticated user interfaces for larger screens, helping scale applications between small and large screens, and so on. Multiple fragments can be combined within a single activity and, conversely, the same fragment can often be reused across multiple activities. This structure is largely intended to foster code reuse and facilitate economies of scale.

A fragment is essentially a modular section of an activity, with its own lifecycle and input events, and which can be added or removed at will. A fragment’s lifecycle is directly affected by its host activity’s lifecycle; i.e., when the activity is paused, so are all fragments in it, and when the activity is destroyed, so are all of its fragments.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is the difference between Serializable and Parcelable?

A

Serializable is a standard Java interface. You simply mark a class Serializable by implementing the interface, and Java will automatically serialize it in certain situations.

Parcelable is an Android specific interface where you implement the serialization yourself. It was created to be far more efficient than Serializable, and to get around some problems with the default Java serialization scheme.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What are launch modes?

A

A “launch mode” is the way in which a new instance of an activity is to be associated with the current task.

Launch modes may be defined using one of two mechanisms:

Manifest file. When declaring an activity in a manifest file, you can specify how the activity should associate with tasks when it starts. Supported values include:

standard (default). Multiple instances of the activity class can be instantiated and multiple instances can be added to the same task or different tasks. This is the common mode for most of the activities.

singleTop. The difference from standard is, if an instance of the activity already exists at the top of the current task and the system routes the intent to this activity, no new instance will be created because it will fire off an onNewIntent() method instead of creating a new object.

singleTask. A new task will always be created and a new instance will be pushed to the task as the root. However, if any activity instance exists in any tasks, the system routes the intent to that activity instance through the onNewIntent() method call. In this mode, activity instances can be pushed to the same task. This mode is useful for activities that act as the entry points.

singleInstance. Same as singleTask, except that the no activities instance can be pushed into the same task of the singleInstance’s. Accordingly, the activity with launch mode is always in a single activity instance task. This is a very specialized mode and should only be used in applications that are implemented entirely as one activity.

Intent flags. Calls to startActivity() can include a flag in the Intent that declares if and how the new activity should be associated with the current task. Supported values include:

FLAG_ACTIVITY_NEW_TASK. Same as singleTask value in Manifest file (see above).
FLAG_ACTIVITY_SINGLE_TOP. Same as singleTop value in Manifest file (see above).
FLAG_ACTIVITY_CLEAR_TOP. If the activity being started is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it are destroyed and this intent is delivered to the resumed instance of the activity (now on top), through onNewIntent(). There is no corresponding value in the Manifest file that produces this behavior.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is the difference between Service and IntentService?

A

Service is the base class for Android services. A class that directly extends Service runs on the main thread so it will block the UI and should therefore either be used only for short tasks or should make use of other threads for longer tasks.

IntentService is a subclass of Service that handles asynchronous requests (expressed as “Intents”) on demand. Clients send requests through startService(Intent) calls. The service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work. To use, extend the IntentService class and override the onHandleIntent(Intent intent) method where you can manage all incoming requests.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How do you supply construction arguments into a Fragment?

A

Construction arguments for a Fragment are passed via Bundle using the Fragment#setArgument(Bundle) method. The passed-in Bundle can then be retrieved through the Fragment#getArguments() method in the appropriate Fragment lifecycle method.

It is a common mistake to pass in data through a custom constructor. Non-default constructors on a Fragment are not advisable because the Fragment may be destroyed and recreated due to a configuration change (e.g. orientation change). Using #setArguments()/getArguments() ensures that when the Fragment needs to be recreated, the Bundle will be appropriately serialized/deserialized so that construction data is restored.

17
Q

What is ANR, and why does it happen?

A

‘ANR’ in Android is ‘Application Not Responding.’ It means when the user is interacting with the activity, and the activity is in the onResume() method, a dialog appears displaying “application not responding.”

It happens because a heavy and long running task like downloading data was started in the main UI thread. The solution of the problem is to start heavy tasks in the background using the AsyncTask class.

18
Q

Which method is called only once in a fragment life cycle?

A

onAttached()

19
Q

Is it possible to create an activity in Android without a user interface ?

A

Yes, these activities are treated as abstract activities

20
Q

What is a broadcast receiver?

A

The broadcast receiver communicates with the operation system messages such as “check whether an internet connection is available,” what the battery label should be, etc.

21
Q

What is the difference between an implicit and an explicit intent?

A

Explicit intents tell the system which Activity or system component it should use to respond to this intent.

Implicit intents allow the declaration of the action to be performed. The Android system will then check which components are registered to handle that action.

22
Q

When should a Fragment be used?

A
  • when the entire screen does not need to be swapped
  • when working with UI components across multiple activities
  • when using navigational methods such as swipe views
  • when seeing two different layouts side-by-side would be beneficial
  • when data needs to be persisted across activity restarts (need to use retained fragments)
23
Q

How to ensure the back button will return to the previous fragment

A
  • save each fragment transaction to the back stack by calling addToBackStack() before calling commit() on that transaction
  • never try to commit a FragmentTransaction after calling onSaveInstanceState() because that can result in an exception
24
Q

How is data accessed in a ContentProvider?

A
  • have the necessary read access permissions
  • call getContentResolver() on the Context object
  • construct a query using ContentResolver.query
  • ContentResolver.query() returns a Cursor
  • retrieve data from each column using Cursor methods
  • perform data queries on a separate thread
25
Q

What is an Adapter?

A
  • a component that acts as a bridge between an AdapterView (such as ListView or GridView) and an external data source
  • responsible for converting each data entry into a View that can then be added to the AdapterView
26
Q

How is a custom View created?

A
  • subclass the View that most closely resembles the custom component (rarely extend the View class)
  • create a res/values/attrs.xml file and declare the attributes to use with the custom View
  • In the View class, add a constructor method, instantiate the Paint object, and retrieve the custom attributes
  • override either onSizeChanged90 or onMeasure()
  • draw the View by overriding onDraw()
27
Q

What is Handler used for?

A

used to communicate between threads, most commonly to pass an action from a background thread to Android’s main thread

28
Q

What is the difference between onCreate() and onStart()?

A

onCreate() is called once during the Activity lifecycle either when the application starts or when the Activity has been destroyed and then recreated

onStart() is called whenever the Activity becomes visible, typically after onStart() or onRestart()

29
Q

When might you use a FrameLayout?

A

FrameLayouts are designed to contain a single item, so they are a good choice when a single view needs to be displayed

FrameLayouts stack multiple views one above the other, so they are also useful for overlapping views