Unit4 Android Programming
Unit4 Android Programming
Screen Orientation:
The screenOrientation is the attribute of activity element. The orientation of android activity can be portrait,
landscape, sensor, unspecified etc. You need to define it in the AndroidManifest.xml file.
Syntax:
<activity android:name="package_name.Your_ActivityName"
android:screenOrientation="orientation_type">
</activity>
Example:
<activity android:name=" com.screenorientation.MainActivity"
android:screenOrientation="portrait">
</activity>
<activity android:name=".SecondActivity"
android:screenOrientation="landscape">
</activity>
The common values for screenOrientation attribute are as follows:
Value Description
unspecified It is the default value. In such case, system chooses the orientation.
portrait taller not wider
landscape wider not taller
sensor orientation is determined by the device orientation sensor.
Example:
In AndroidManifest.xml file add the screenOrientation attribute in activity and provides its orientation. In this
example, we provide "portrait" orientation for MainActivity and "landscape" for SecondActivity.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.screenorientation">
<application
……..
<activity
android:name="com.screenorientation.MainActivity"
android:screenOrientation="portrait">
UNIT-4 ANDROID & ITS APPLICATIONS
</activity>
<activity android:name=".SecondActivity"
android:screenOrientation="landscape">
</activity>
</application>
</manifest>
RESOURCES
Resources in Android refer to the external files that hold the information, such as strings, images, layouts, and
audio, to be supplied to an Android application. Because resources are external, we can maintain and modify
them whenever we want without disturbing the code. For example, the strings resource keeps the strings used in
an Android application. Changing the string content in the resource file is easier when compared to applying
changes to hard-coded strings that are scattered in the application code. Also, by creating several resource files,
each supporting different hardware, we can make our applications applicable to diverse hardware systems. For
example, we can have several layouts for screen size and orientation and use them dynamically when we want.
Resources are broadly divided into three categories—values, drawable, and layout—and are stored in the
res folder of our project hierarchy. The values resources in turn represent resources such as strings, colors,
dimensions, styles, and string or integer arrays. All resource types have a respective subfolder in the res folder.
The ADT Wizard automatically creates a res folder that contains subfolders for the values, drawable, and layout
resources, as shown in Figure 4.1.
Utilizing Resources:
Resources include text data, bitmaps, audio, videos, and other items used by the Android application. Most
commonly resources are kept separately in XML files and accessed in Java code through the IDs assigned to
them. We will see how to access media too, that is, access and use images, audio, and video in Android
applications
Types of Resources
A brief outline of the three folders is provided here:
• drawable folder—Depending on the target platform chosen, our application can have either a single
directory, drawable, or four directories, drawable-ldpi, drawable-mdpi, drawable-hdpi, and drawable-xhdpi,
where we can store the images used in our application. If our application has a single directory, drawable, then
the images to be used in our application, regardless of resolution, are stored in it. If our application has four
directories, then the images with different screen resolutions are stored in the respective directories. That is, the
images of low, medium, high, and extra high resolutions are stored in the drawable-ldpi, drawable-mdpi,
drawable-hdpi, and drawable-xhdpi directories, respectively. Android chooses the image(s) from the respective
directory, depending on the density of the device used to run the application.
• layout folder—This folder contains a layout file automatically created for us. The default name assigned to
this file is activity_main.xml, but we can assign any name to it. we know how to use this file to lay out Views in
the desired format.
UNIT-4 ANDROID & ITS APPLICATIONS
menu folder—This folder contains XML file(s) that represent application menus. Again, the default name
assigned to the menu file that is automatically created for us is activity_main.xml, but we can change the name
if we want.
• values folder—This folder by default contains a strings.xml file that we can use to define values resources
that include strings, colors, dimensions, styles, and string or integer arrays. We can also create individual XML
files for each of these resources instead. The folder also contains the styles.xml file that declares the standard
platform’s default light theme. The following is a list of some XML files that we can create in the values folder:
• arrays.xml—For defining arrays resources
• colors.xml—For defining color resources that define color values
• dimens.xml—For defining dimension resources to standardize certain application measurements
• strings.xml—For defining string resources
• styles.xml—For defining styles resources to format or change the appearance of our views and application
There are many Android devices with different Android versions, and managing themes across them is a critical
task. To manage themes for different Android versions, different values folders in the /res folder containing
individual themes are maintained. The idea is that on the basis of the platform version, the desired theme will be
automatically selected from the respective folder.
• values-v11—The folder contains the styles.xml file that declares the holographic theme, which is used when
the application runs on Android 3.0 (API Level 11) or higher. That is, if the API level of the device is 11 or
higher, the styles.xml file present in this folder overrides the styles.xml file present in the res/values folder.
• values-v14—The folder contains the styles.xml file that declares the DeviceDefault theme, which is used
when the application runs on Android 4.0 (API Level 14) or higher.
Besides these default subdirectories automatically created by ADT, there are several subdirectories that we can
manually create in the res folder to categorize and keep our resources tidy. Table 4.1 shows the list of supported
subdirectories in the res folder.
arrays.xml for resource arrays, and accessed from the R.array class.
integers.xml for resource integers, and accessed from the R.integer class.
bools.xml for resource boolean, and accessed from the R.bool class.
colors.xml for color values, and accessed from the R.color class.
dimens.xml for dimension values, and accessed from the R.dimen class.
strings.xml for string values, and accessed from the R.string class.
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
UNIT-4 ANDROID & ITS APPLICATIONS
android:text="Hello, I am a TextView" />
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a Button" />
</LinearLayout>
This application code will load this layout for an Activity, in the onCreate() method as follows −
2 incrementProgressBy(int diff) This method increments the progress bar by the difference of value
passed as a parameter.
4 setMax(int max) This method sets the maximum value of the progress dialog.
5 setProgress(int value)
This method is used to update the progress dialog with some specific value.
6 show(Context context, CharSequence title, CharSequence message) This is a static method, used to
display progress dialog.
UNIT-4 ANDROID & ITS APPLICATIONS
Example
This example demonstrates the horizontal use of the progress dialog which is in fact a progress bar. It display a
progress bar on pressing the button.
To experiment with this example, you need to run this on an actual device after developing the application
according to the steps below.
Steps Description
1 You will use Android studio to create an Android application under a package
com.example.sairamkrishna.myapplication.
2 Modify src/MainActivity.java file to add progress code to display the progress dialog.
3 Modify res/layout/activity_main.xml file to add respective XML code.
4 Run the application and choose a running android device and install the application on it and verify the
results.
public void download(View view){
progress=new ProgressDialog(this);
progress.setMessage("Downloading Music");
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setIndeterminate(true);
progress.setProgress(0);
progress.show();
In order to use AndroidManager class, you have to first create an object of AudioManager class by calling the
getSystemService() method. Its syntax is given below.
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
The method setRingerMode takes an integer number as a parameter. For each mode , an integer number is
assigned that will differentiate between different modes. The possible modes are.
Once you have set the mode , you can call the getRingerMode() method to get the set state of the system. Its
syntax is given below.
UNIT-4 ANDROID & ITS APPLICATIONS
3 getStreamMaxVolume(int streamType) This method returns the maximum volume index for a
particular stream
4 getStreamVolume(int streamType) This method returns the current volume index for a particular
stream
Example
The below example demonstrates the use of AudioManager class. It creates a application that allows you to set
different ringer modes for your device.
To experiment with this example , you need to run this on an actual device.
Steps Description
1 You will use Android studio IDE to create an Android application under a package
com.example.sairamkrishna.myapplication.
2 Modify src/MainActivity.java file to add AudioManager code
3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required.
UNIT-4 ANDROID & ITS APPLICATIONS
4 Modify res/values/string.xml file and add necessary string components.
5 Modify AndroidManifest.xml to add necessary permissions.
6 Run the application and choose a running android device and install the application on it and verify the
results.
Android Media Player Example
We can play and control the audio files in android by the help of MediaPlayer class.
Here, we are going to see a simple example to play the audio file. In the next page, we will see the example to
control the audio playback like start, stop, pause etc.
MediaPlayer class
The android.media.MediaPlayer class is used to control the audio or video files.
VideoView class
The android.widget.VideoView class provides methods to play and control the video player. The commonly
used methods of VideoView class are as follows:
Method Description
public void setMediaController(MediaController controller) sets the media controller to the video view.
public void setVideoURI (Uri uri) sets the URI of the video file.
public void start() starts the video view.
public void stopPlayback() stops the playback.
public void pause() pauses the playback.
public void suspend() suspends the playback.
public void resume() resumes the playback.
public void seekTo(int millis)seeks to specified time in miliseconds.
Steps.
1.Drag the VideoView from the pallete,
2. Write necessary changes in MainActivity.java file
package com.ebookfrenzy.videoplayer;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.VideoView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_player);
UNIT-4 ANDROID & ITS APPLICATIONS
videoView.setVideoPath(
"http://www.ebookfrenzy.com/android_book/movie.mp4");
videoView.start();
}
Arrays
An array in Java is a type of variable that can store multiple values. It stores these values based on a key that
can be used to subsequently look up that information.
Arrays can be useful for developers to store, arrange, and retrieve large data sets. Whether you are keeping track
of high scores in a computer game, or storing information about clients in a database, an array is often the best
choice.
The word “array” is defined as a data structure, consisting of a collection of elements. These elements must be
identified by at least one “index” or “key.” This is the easiest way to think about a Java array: as a list of
sequential values. Here, a key is automatically assigned to each value in the sequence based on its relative
position. The first index is always “0” and from there, the number will increase incrementally with each new
item.
To create this type of array in Java, simply create a new variable of your chosen data type with square brackets
to indicate that it is indeed an array. We then enter each value inside curly brackets, separated by commas.
Values are subsequently accessed by using the index based on the order of this list.
String listOfFruit[] = {"apple", "orange", "lemon", "pear", "grape"};
System.out.println(listOfFruit[2]);
ArrayLists
If you need to use arrays in Java that can be resized, then you might opt for the ArrayList. An ArrayList is not
as fast, but it will give you more flexibility at runtime.
To build an array list, you need to initialize it using our chosen data type, and then we can add each element
individually using the add method. We also need to import ArrayList from the Java.util package.
import java.util.ArrayList;
class Main {
}
Now, at any point in our code, we will be able to add and remove elements. But keep in mind that doing so will
alter the positions of all the other values and their respective keys. Thus, were I to do this:
System.out.println(arrayListOfFruit.get(3));
arrayListOfFruit.add(2, "Lemon");
System.out.println(arrayListOfFruit.get(3));
How to create an array in Java using maps
Another type of array in Java is the map. A map is an associative array that uses key/value pairs that do not
change.
This is a perfect way to store phone numbers, for example. Here, you might use the numbers as the values and
the names of the contacts as the index. So “197701289321” could be given the key “Jeff.” This makes it much
easier for us to quickly find the data we need, even as we add and remove data from our list!