Android Introduction: 1 Android Activity, Intents and Fragments 2



Download 108.51 Kb.
Date30.06.2017
Size108.51 Kb.
#22033

Android Introduction: 1

Android Activity, Intents and Fragments 2

Android User Interface 7

Android Storage 10

Android Networking 12

Android Location Services 12

Android Services: 13

Android Publishing: 15

Android Media Management: 16

Android Sensors: 16



Others: 16



Android Introduction:


  1. What is an AVD?

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

  1. [1 Mark] Which tool is used to convert a class file into a dex file?

dx

  1. What is the difference between the android:versionCode and android:versionName attributes in the AndroidManifest.xml file?

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”.

  1. What is the use of the strings.xml file?

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

  1. What is SQLite?

SQLite is a lightweight relational database for data storage, used by Android.

  1. What is the use of Davlik Virtual machine?

The Android runtime also includes the Dalvik virtual machine, which enables every Android application to run in its own process, with its own instance of the Dalvik virtual machine (Android applications are compiled into Dalvik executables).

  1. Which file is used to generate R.java file?

AndroidManifest.xml file.

  1. What is the use of assets folder?

The assets folder holds files used by the application, such as HTML, text files, databases, etc.

  1. Usage of strings directly in AndroidManifest.xml is not welcomed. So, what is the solution?

@string is used to refer to res/values/strings.xml

  1. What is the use of android:versionCode attribute?

Used programmatically whether the application needs upgrade or not.





Android Activity, Intents and Fragments


  1. The use of android:onClick in the layout xml file is to __________________.

Invoke a method defined in the java code.

  1. What is the use of Intent?

Intent is used to glue activities or glue an activity with an application.

  1. How to specify the procedure to invoke an activity in AndroidManifest.xml?

This is done using intent-filter in AndroidManifest.xml, with

  1. In specifying an activity in the manifest file, you have two entries for android:name, one within the intent-filter tag and the other within the activity tag. What is the use of both?

android:name in activity is the name that indicates the actual class.

android:name in intent-filter is the name using which the class has to be invoked. If someone calls this name, the class mentioned in the other android:name will be invoked.



  1. What is the difference between startActivity() and startActivityForResult()?

startActivity just invokes an activity and will not acquire any return from the activity. The startActivityForResult obtains a result from the activity. startActivityForResult returns a code: RESULT_OK & RESULT_CANCELLED.

  1. What is findViewById() used for?

In order to access any field in the view, we can use this method. Note that the android:id (written as @+id/idname) specified in the layout xml file is used to access the field.

  1. How to pass data using an Intent Object?

To put and read data: putExtra(), getExtra() using Name/value pair

getStringExtra() method to get the string value set using the putExtra() method;

getExtra()

Bundle: putString() or put with putExtras(), getExtras() using Name/value pair

//---get the Bundle object passed in---

Bundle bundle = getIntent().getExtras();



  1. How is fragment different from an activity? Give three differences.

Fragment is a mini-activity. During runtime, an activity can contain one or more of these mini-activities. This is to cater for various screens. Fragments cannot work alone. They need activity to work upon. When a back button is pressed, fragments will not be placed in back stack automatically. But activity will be placed in back stack automatically.

  1. onCreate() method is used to display the activity. What about the fragment?

onCreateView() method is overridden to draw the fragment.

  1. Lifecycle of a fragment:

When a fragment is being created, it goes through the following states: onAttach(), onCreate(), onCreateView(), onActivityCreated()

When the fragment becomes visible, it goes through these states: onStart(), onResume(),

When the fragment goes into the background mode, it goes through these states: onPause(), onStop()

When the fragment is destroyed (when the activity it is currently hosted in is destroyed), it goes through the following states:onPause(), onStop(), onDestroyView(), onDestroy(), onDetach()

Like activities, you can restore an instance of a fragment using a Bundle object, in the following states: onCreate(), onCreateView(), onActivityCreated()


  1. Which components can you specify in an intent filter?

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

  1. What is the difference between the Toast class and the NotificationManager class?

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

  1. Name the two ways to add fragments to an activity.

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

  1. How to perform an action on behalf of an application at a later time?

Using PendingIntent.

  1. Name one key difference between a fragment and an activity.

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

  1. A layout could be generated both using an XML or programmatically. Given the following snippet, write the alternative equivalent of it.

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState); TextView tv = new TextView(this);

tv.setText("Hello, World!"); setContentView(tv);

}



android:layout_width="fill_parent" android:layout_height="fill_parent"

android:text="@string/hello"/>


  1. What is the use of getApplicationContext()?

Get the current context.

  1. Updation of the UI should be done only via UI thread (True/False). Justify your answer.

  2. Given a View v, the call v.getId() will return ______________.

The ID of the entry in the view.

  1. Given the following snippet, explain the use of this snippet.

View v;

switch(v.getId()) {

case R.id.accept: text = "accept pushed!"; break;

case R.id.cancel: text = "cancel pushed!"; break;

default: text="text pressed!";

}


  1. Given the following code snippet, the call is made when the button is clicked. Explain the sequence of the execution in this code. Indicate about the impact due to the presence or absence of a line of code.

public class test extends Activity {

public void onCreate(Bundle savedInstanceState) {

// certain part of the code is omitted.

Button accept = (Button)findViewById(R.id.accept);

accept.setOnClickListener(respondToClick);

}

private OnClickListener respondToClick = new OnClickListener() {



// certain part of the code is omitted.

public void onClick(View v) { … }

}

}


  1. In the given layout snippet, @+id and @ id used. Justify the reason for this difference.

android:id="@+id/numberStudents"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:layout_below="@id/myLabel"

/>


  1. What is the difference between OnClickListener and OnLongClickListener?

  2. OnClickListener provides a method named onClick(View v). Similarly, OnLongClickListener provides a method named __________________.

onLongClick(View v).

  1. Having two folders namely values-en and values-es inside the res folder means there are two files that contains values there. Which file is used by the android device or emulator and when?

Based on the language settings, the appropriate language file is loaded.

  1. Give two ways to add an image to the ImageView.

The setImageResource() method is used to set the image in the ImageView.



  1. What is use of OnCompletionListener in the case of playing media in android?

To do certain task when playing of the media is complete. This is performed in onCompletion() method.

  1. Show with an example how to invoke different applications using an Intent.

Intent data = new Intent();

// activities require an action to perform and data to act on

data.setAction(Intent.ACTION_VIEW); data.setData(Uri.parse("http://www.cs76.net"));

data.setAction(Intent.ACTION_DIAL); data.setData(Uri.parse("tel:(234) 567-8901"));

data.setAction(Intent.ACTION_VIEW); data.setData(Uri.parse("geo:0,0?q=el+paso,+tx"));

data.setAction(Intent.ACTION_VIEW);

/* Query fields for the URI:

* cbll=latitude,longitude

* cbp= street view window details

* See: http://mapki.com/index.php?title=Google_Map_Parameters

*/

data.setData(Uri.parse("google.streetview:cbll=42.379069,-71.116564&cbp=12,60,,0,-1.21&mz=18"));



data.setAction(Intent.ACTION_VIEW); data.setData(Uri.parse("sms:(234) 567-8901"));

data.putExtra(Intent.EXTRA_TEXT, "Hello from "+getResources().getString(R.string.app_name));


data.setAction(Intent.ACTION_SEND); data.setType("text/plain");

data.putExtra(Intent.EXTRA_EMAIL, new String[] {"danallan@mit.edu"});

data.putExtra(Intent.EXTRA_SUBJECT, "Hello!");

data.putExtra(Intent.EXTRA_TEXT, "Message body.\n--Dan");



  1. requestWindowFeature() is present in which class? What are the various settings that we could do using it?

  2. What if I don’t want to have the activity cover the whole screen of the mobile? Instead, I want it to just a popup?

Hint: Theme

  1. When is onCreateDialog() method invoked?

  2. What is CharSequence data type in Android?

  3. What is the use of AlertDialog.Builder()?

  4. If an application is targeted to SDK 17 and the minimum SDK is 8 and you run the application on a mobile which is of SDK 18, what will happen?

  5. What is the use of final in the statement final ProgressDialog dialog = ProgressDialog.show(this, "Doing something", "Please wait...", true);?

  6. What is the use of setPositiveButton and others in AlertDialog?

  7. Why do you need these statements in fragments?

fragmentTransaction.addToBackStack(null); fragmentTransaction.commit();

  1. Bringing in a fragment onto the screen is possible using fragmentTransaction.replace(android.R.id.content, fragment2);. Elaborate the use of replace() method here.

  2. Write about the methods that are used in the lifecycle of activity but not in the fragments? Elaborate for the vice versa also.

  3. When do you use @+id in the layout file?

  4. What does android.R.id.content refer to in fragmentTransaction?

  5. What is the use of these methods in an activity? onSaveInstanceState, onRestoreInstanceState, onRetainNonConfigurationInstance

  6. Use of android.intent.category.LAUNCHER in category in Manifest file?

android.intent.category.LAUNCHER is to indicate that activity that the activity should be the main activity. This activity will be the first activity to be started. The launcher present in the android will start the first activity.

  1. When do you use android.intent.category.DEFAULT instead of LAUNCHER in the manifest file? What is the difference between them?

android.intent.category.DEFAULT is given to the activity that is not the main activity. This activity is to invoked based on the default application for the respective activity.

  1. While specifying an activity that is to be invoked from another activity, in the manifest file, what should be android:name field in and tags? Why do we need android:name entry twice?

The android:name in the is used to indicate about the name of the activity in the manifest file.

The android:name in the is the name using which another activity can invoke this specific activity.



  1. @dimen in main.xml refers to?

Refers to res/values/dimens.xml

  1. What is the difference between Log.d and Log.e?

Log.d is used to store debug errors.

Log.e is used to indicate errors.



  1. What is the difference between wrap_content and fill_parent in the layout XML file?

wrap_content is used to make the view to the size of the content or the text.

fill_parent is used to make the view to the length and/or height of the parent view or layout.



  1. When is onActivityResult method called?

This method is called when an activity wants to call another activity but expects a result from the called activity.

  1. What is the difference between putExtra and putExtras methods in an Intent?

putExtra is used to add individual elements to the Intent.

putExtras is used to create Bundle, which could be added to the Intent.



  1. Do we specify about fragments in the manifest file?

No

  1. Is it necessary that the id of the fragments specified in the main layout file should be unique? Justify.

Yes they should be. Thus, we could dynamically load or unload the respective fragments.

  1. When is the onActivityResult() method invoked? How will you know which result is for which request in onActivityResult()?

onActivityResult() method is invoked when the activity wants to receive a result from the called activity. The request and the return contains the request_code which could be matched to find the respective result for the given request.

  1. What if we use setContentView() in Fragment classes?

This is a syntax error. setContentView() is for activity and not for fragment.

  1. When do you use @+id in the layout file?

@+id is used to add a new “id” in the layout file. The name that follows this is the identifier gives to the view.

Android User Interface


  1. What is the difference between wrap_content and fill_parent in the layout XML file?

  2. When do you use WebView tag in the layout xml file?

  3. Can we use android:orientation for RelativeLayout? Explain.

  4. What is the difference between View and ViewGroup?

A view is a widget that has an appearance on screen

A ViewGroup (which is itself a special type of view) provides the layout in which you can order the appearance and sequence of views



  1. What layout should I use to get the views arranged in a single column or a single row?

LinearLayout

  1. layout_weight is used to indicate _______________

how much of the extra space in the layout should be allocated to the View

  1. What is the difference between fill_parent and wrap_content?

wrap_content is based on the size of the content. fill_parent makes the view to be based on the size of the parent (screen).

  1. How to place views of FrameLayout based on previously existing views?

Use android:layout_below=”@+id/idname” with the idname of the previously existing view

  1. What is ScrollView?

ScrollView is a special type of FrameLayout. It enables users to scroll through a list of views that occupy more space than the physical layout.

  1. ScrollView can contain ___________ number of view(s) or ViewGroup(s).

only one

  1. Why is the AbsoluteLayout not recommended for use?

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

  1. The options available to handle screen orientation changes are __________ and __________.

Anchoring, Resizing and repositioning

  1. Anchoring can be achieved using ___________

RelativeLayout

  1. What are the two files you create to handle the views for both the orientations?

res/layout/main.xml and res/layout-land/main.xml

  1. What is the impact of using android:id in EditText view when you change the orientation?

Without android:id, the text in EditText view will be destroyed if orientation changes.

  1. A long list of items can be displayed using _______________ and _______________.

ListView, SpinnerView

  1. When a RadioButton is selected, ___________ method is fired.

onCheckedChanged()

  1. How do you access the string resource stored in the strings.xml file?

You can use the getResources() method

  1. Write the code snippet to obtain the current date.

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);


  1. Name the three specialized fragments you can use in your Android application and describe their uses.

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

  1. In TableLayout, the width of each column is determined by ___________________ width of each cell in that column.

Largest width

  1. Write the pros and cons of generating UI from xml and java?




  1. Interaction of users with the views is handled at _______________ and __________.

Activity level and view level

  1. Having a long list of items to display, we can use ______________ to display one item at a time.

SpinnerView

  1. To create an instance of a fragment, we can use ____________ method.

newInstance()

  1. Difference between SpinnerView and ListView.

SpinnerView can display one item at a time among a long list of items available. ListView is used to list of items only and thus cannot display one item at a time.

  1. Users can edit the preferences using _____________ base class.

PreferenceActivity or PreferenceFragment

  1. Subclasses if Fragment: ______________, ______________, and ______________.

ListFragment, DialogFragment, PreferenceFragment

  1. The _____________ object manages the array of strings that will be displayed by the ListView.

ArrayAdapter

  1. The GridView shows items in a _______________ grid.

Two-dimensional scrolling

  1. The GridView shows items in a ____________ scrolling grid.

Two-dimensional

  1. In a ListView, multiple elements are displayed in the layout. For this purpose, how to generate the layout file. Is it that multiple entries of TextView should be present in the layout file? Justify your answer.

Only one TextView is needed in the layout file. ListView is use it multiple times to generate the layout.

setListAdapter(new ArrayAdapter(this, R.layout.custom_list_item, ARRAYLISTNAME));

// obtain the ListView that was created by setListAdapter()

ListView myList = getListView();



  1. A could be generated both using an XML or programmatically. Given the following snippet, write the alternative equivalent of it.

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState); TextView tv = new TextView(this);

tv.setText("Hello, World!"); setContentView(tv); }


android:layout_width="fill_parent" android:layout_height="fill_parent"

android:text="@string/hello"/>


  1. [2 Marks] Write about various menus supported by the Android platform.

Options, Context and SubMenus

  1. What is the difference between GridView and ImageView in layout file?

  2. What is the use of MenuInflater in the case of menus in android? How is it done programmatically?

MenuInflater is used to inflate the menu into the layout.

public boolean onCreateOptionsMenu(Menu menu) {

// can also use the add() method to programmatically create a menu

MenuInflater inflater = getMenuInflater();

inflater.inflate(R.menu.options_menu, menu);

return true;

}



android:id="@+id/tortoise"

android:title="Tortoise"

android:icon="@android:drawable/ic_menu_gallery" />





  1. [2 Marks] Give appropriate examples when you would prefer one over the others: AlertDialog and Toast.

AlertDialog: Battery goes off in 5 minutes; also this blocks other activities until ok is pressed.

Toast: short messages.



  1. [1 Mark] What is the use of invalidate() method in View class?

It tells the system that some or all of the View needs to be redrawn. Calling an invalidation method will cause the View’s onDraw() method to be called.

Android Storage


  1. ____________ is a light-weight storage mechanism to save small chunks of data.

Shared preferences

  1. In shared preferences, data is stored in ___________ pair.

Name/value

  1. SQLite database is a ___________ database management system.

relational

  1. The default name of the preferences xml file is ___________.

_preferences



  1. ________ mode is used to enable an internal file to be readable by all other applications.

MODE_WORLD_READABLE

  1. The openRawResource() method is used to open the file present in the _____ folder.

res/raw

  1. The __________ constant indicates that the preference file can only be opened by the application that created it.

MODE_PRIVATE

  1. The ___________ method of ____________ class is used to open a file.

openFileOutput(), FileOutputStream

  1. Preferences can be retrieved programmatically using ___________ attribute.

android:key

  1. Write the query to retrieve all contacts from the Contacts application that contain the word “jack.”

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(); }


  1. Name the methods that you need to override in your own implementation of a content provider.

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

  1. How do you register a content provider in your AndroidManifest.xml file?

The code is as follows:


  1. The URI format used to query a content provider is _______________.

:////

  1. Explain the operation of the given code snippet.

// build our preferences object with our data to save

SharedPreferences prefs = getPreferences(MODE_PRIVATE);

// recall the saved car value, or use R.id.hare as the default if preference does not exist

int savedCar = prefs.getInt("defaultCar", R.id.test);

SharedPreferences.Editor editor = prefs.edit();

int selection = 1;

editor.putInt("defaultCar", selection);


  1. Explain the operation of the given code snippet.

// get our SharedPreferences object

SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);

// load data from it or use some defaults if values don't exist

boolean boldedText = prefs.getBoolean("boldedText", false);

String welcomeText = prefs.getString("welcomeText", getString(R.string.hello));


  1. Why is that Cursor is used as the return of database queries in android?

Cursor is used to iterate over the outcome of the database query.

  1. [2 Marks] Why should we use Environment.getExternalStorageDirectory() in the following code?

File sdCard = Environment.getExternalStorageDirectory();

File directory = new File (sdCard.getAbsolutePath() + "/MyFiles");



  1. [2 Marks] What is the use of execSQL method?

  2. [2 Marks] What is the use of ContentValues and how are the values inserted into the database?

ContentValues initialValues = new ContentValues();

initialValues.put(KEY_NAME, name);

initialValues.put(KEY_EMAIL, email);

return db.insert(DATABASE_TABLE, null, initialValues);



  1. [2 Marks] What and when do you use android.os.Build.VERSION.SDK_INT in your android code?

  2. [2 Marks] Discuss the use of the following line in your code.

SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder();

  1. [2 Marks] Given the following code, explain the need of each line.

SharedPreferences appPrefs = getSharedPreferences("package_name.class_name", MODE_PRIVATE);

SharedPreferences.Editor prefsEditor = appPrefs.edit();

prefsEditor.putString("editTextPref", ((EditText) findViewById(R.id.txtString)).getText().toString());

prefsEditor.commit();



  1. [2 Marks] Describe the use of each entity in the following code snippet.

DatabaseHelper DBHelper = new DatabaseHelper(context);

SQLiteDatabase db = DBHelper.getWritableDatabase();


Android Networking


  1. The ___________ class could be used to send an SMS message programmatically.

SmsManager

  1. The ____________ method of SmsManager class can be used to obtain the content of the message.

createFromPdu()

  1. The ____________ method of SmsManager class can be used to obtain the number of the message sender.

getOriginatingAddress()

  1. Document (DOM) object can be obtained from a XML file using __________ and ___________ objects.

DocumentBuilderFactory, DocumentBuilder

  1. Persistent connections can be setup using ________ programming.

sockets

  1. Client TCP socket is provided using _________ object.

Socket

  1. The drawbacks of DOM in parsing an XML file are ____________.

Traverse the tree for the document you want.

Build the entire document in memory as a tree structure before you can traverse.

Thus, it is CPU and memory intensive


  1. To decode the downloaded data into a Bitmap object, __________ method is used.

decodeStream() method of BitmapFactory class

  1. The publishProgress() method invokes ____________ method.

onProgressUpdate()

  1. Name the classes used for dealing with JSON messages.

The classes are JSONArray and JSONObject

  1. Name the class for performing background asynchronous tasks.

The class is AsyncTask

  1. [2 Marks] Networking tasks ought to be performed in a separate thread as that of the GUI. Discuss the alternative option available to permit networking tasks within the same thread as that of the GUI.

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

StrictMode.setThreadPolicy(policy);



Android Location Services


  1. The _____________ application of the JDK installation is needed to extract the MD5 fingerprint.

keytool

  1. To display the route on the map, you should use ____________ method.

isRouteDisplayed() with return true

  1. If you have embedded the Google Maps API into your Android application but it does not show the map when the application is loaded, what could be the likely reasons?

The likely reasons are as follows:

No Internet connection

Incorrect placement of the element in the AndroidManifest.xml file

Missing INTERNET permission in the AndroidManifest.xml file



  1. Geocoding is used to obtain the ____________ of a location.

Latitude and longitude

  1. The ___________ class is used to obtain periodic updates about the geographic location of the device.

LocationManager

  1. The __________ method of MapOverlay class is used to add an overlay to the map when a map is touched.

onTouchEvent()

  1. [4 Marks] Explain the operation of the following code snippet indicating the line numbers:


ArrayList locationVisited;

double distance;

location location1;

  1. public void onLocationChanged(Location location) {

  2. if (locationVisited.size() > 0)

  3. distance = location.distanceTo(location1);

  4. locationVisited.add(location1);

  5. textview.setText(textview.getText() + “ “ + location.getLatitude());

}



  1. Upon a new location update from the GPS or Cell towers.

  2. If more than one location is visited.

  3. Compute the difference between the previous and currently visited locations.

  4. Add the new location to the list of visited locations.

  5. The current location is printed on the device.

Android Services:


  1. Can we run multiple background threads in AsyncTask?

No.

  1. What is the difference from AsyncTask and Service?

AsyncTasks are designed for once-off time-consuming tasks that cannot be run of the UI thread. A common example is fetching/processing data when a button is pressed.

Services are designed to be continually running in the background. In the example above of fetching data when a button is pressed, you could start a service, let it fetch the data, and then stop it, but this is inefficient. It is far faster to use an AsyncTask that will run once, return the data, and be done.

If you need to be continually doing something in the background, though, a Service is your best bet. Examples of this include playing music, continually checking for new data, etc.

Also, as Sherif already said, services do not necessarily run off of the UI thread.

For the most part, Services are for when you want to run code even when your application's Activity isn't open. AsyncTasks are designed to make executing code off of the UI thread incredibly simple.

Services are completely different.!

Services are not threads!

Your Activity binds to a service and the service contains some functions that when called, blocks the calling thread!

Maybe your service is used to change temperature from celcius to degrees. Any activity that binds can get this service.

However AsyncTask is a Thread that does some work in the background and at the same time has the ability to report results back to the calling thread.

Just a thought: A service may have a AsyncTask object!


  1. The ___________ class enables background execution without needing to manually handle threads and handlers.

AsyncTask

  1. Creating a new service is possible by extending ___________ class.

Service

  1. Starting and stopping of service is done using _______ and ________ methods.

startService(), stopService() or stopSelf()

  1. [2 Marks] What is the callback method that is used by the broadcast receiver? What is the use of that method?

onReceive(). It is used to act on the broadcast receiver and handle the incoming event.

  1. The _________ class is used within your service to execute a block of code to be executed at a regular time interval.

Timer

  1. To bind an activity to a service, _________ method could be used.

onBind()

  1. Why do you need to bind an activity to a service?

By binding an activity to a service, an activity is enabled to directly access members and methods inside a service.

  1. When is the run() method invoked?

run() method is invoked when the start() method of the respective thread is called.

  1. The ___________ method is called when the activity is connected to the service.

onServiceConnected()

  1. The ___________ method is called when the service is disconnected from the activity.

onServiceDisconnected()

  1. The ___________ object is a reference to the service, and all the members and methods in the service can be accessed through this object.

serviceBinder

  1. Updating the UI from another thread is possible using ___________ and ____________.

Handler class, post() method

  1. The _______ method is used to broadcast an intent.

sendBroadcast()

  1. What is the use of three types specified in the class that extends AsyncTask class?

doInBackground() method uses the array of first type and returns the third type.

onProgressUpdate() method accepts the array of second type as input.

onPostExecute() method accepts the third type as input.


  1. How can a service notify an activity of an event happening?

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

  1. For threading, what is the recommended method to ensure that your code runs without tying up the UI of your application?

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

  1. Defining a Runnable object (as given below) causes the process to run at the background (True/False). Justify your answer.

private Runnable waitForS = new Runnable() { public void run() { … } }

False.


  1. The onPostExecute() method in the AsyncTask class is invoked in UI thread or background thread. Explain.

UI Thread. This is used to update entries in the UI view.

Android Publishing:


  1. What are the four attributes that ought to be added in the manifest file to publish an application on the Android Market?

android:versionCode, android:versionName, android:icon, android:label

  1. The adb command used to display the devices is _________.

adb devices

  1. The android:versionCode attribute could be obtained within a program using ____________.

getPackageInfo() method from the PackageManager class.

  1. How do you specify the minimum version of Android required by your application?

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

  1. How do you generate a self-signed certificate for signing your Android application?

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

  1. How do you configure your Android device to accept applications from non-Market sources?

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

Android Media Management:


  1. Is image scaling is done using setImageResource() method?

No.

  1. Discuss how image scaling is done to enhance the performance of the android?

ImageView imgView;

// see if we've stored a resized thumb in cache

if(cache[position] == null) {

// create a new Bitmap that stores a resized

// version of the image we want to display.

BitmapFactory.Options options = new BitmapFactory.Options();

options.inSampleSize = 4;

Bitmap thumb = BitmapFactory.decodeResource(myContext.getResources(), images[position], options);

// store the resized thumb in a cache so we don't have to re-generate it

cache[position] = thumb;

}

// use the resized image we have in the cache



imgView.setImageBitmap(cache[position]);

Android Sensors:


  1. [2 Marks] Views ought to be changed based on whether a user is facing the screen or the mobile is placed on a table. Which sensor will you use to handle this? Justify.

Gyroscope / Orientation

  1. [1 Mark] Some mobile devices do not allow access to the device during travel. Which sensor could be used to handle this? Justify.

Accelerometer, gives velocity recordings over time.



Others:


  1. What is the difference between Context and Activity in Android Programming?

  2. [2 Marks] Explain the use of “this” and “R.raw.textfile” in the following code snippet.

InputStream is = this.getResources().openRawResource(R.raw.textfile);

  1. [1 Mark] The ___________ class enables background execution without needing to manually handle threads and handlers.

  1. AsyncTask

  2. Broadcast Receiver

  3. Post

  4. All of the above







Download 108.51 Kb.

Share with your friends:




The database is protected by copyright ©ininet.org 2024
send message

    Main page