Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
22 views

Unit4 Android Programming

Uploaded by

lavanyasujat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Unit4 Android Programming

Uploaded by

lavanyasujat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

UNIT-4 ANDROID & ITS APPLICATIONS

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.

Table 4.1. Supported Subdirectories of the res Folder


UNIT-4 ANDROID & ITS APPLICATIONS
Image
When our application is built, all resources are compiled and included in our application package. On
compilation, an R class file is created that contains references to all the resources created and hence enables us
to reference them in the Java code. For each of the resource types, the R class contains static subclasses for
string, drawable, and layout resource types. The subclasses created are R.string, R.drawable, and R.layout,
respectively. Through these subclasses, we can access their associated resources in Java code.
Note
Don’t edit the R.java file, as it is regenerated every time something gets changed, added, or deleted in the /res/*
subdirectory.

CREATING VALUES RESOURCES


The resources in the values directory include different types, such as strings, colors, dimensions, and string or
integer arrays. All the values are stored in XML files in the res/values folder. It is preferred to have a separate
XML file for each type of resource in the values directory. The filename can be anything, but most commonly,
the string resources file is named strings.xml. Remember, the resource filenames should contain only lowercase
letters, numbers, period (.), and underscore (_) symbols.
values/
XML files that contain simple values, such as strings, integers, and colors. For example, here are some filename
conventions for resources you can create in this directory −

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.

styles.xml for styles, and accessed from the R.style class.


Accessing Resources
During your application development you will need to access defined resources either in your code, or in your
layout XML files. Following section explains how to access your resources in both the scenarios −
UNIT-4 ANDROID & ITS APPLICATIONS

Accessing Resources in Code


When your Android application is compiled, a R class gets generated, which contains resource IDs for all the
resources available in your res/ directory. You can use R class to access that resource using sub-directory and
resource name or directly resource ID.
Example
To access res/drawable/myimage.png and set an ImageView you will use following code −
ImageView imageView = (ImageView) findViewById(R.id.myimageview);
imageView.setImageResource(R.drawable.myimage);
Here first line of the code make use of R.id.myimageview to get ImageView defined with id myimageview in a
Layout file. Second line of code makes use of R.drawable.myimage to get an image with name myimage
available in drawable sub-directory under /res.
Example
Consider next example where res/values/strings.xml has following definition −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello, World!</string>
</resources>
Now you can set the text on a TextView object with ID msg using a resource ID as follows −

TextView msgTextView = (TextView) findViewById(R.id.msg);


msgTextView.setText(R.string.hello);
Example
Consider a layout res/layout/activity_main.xml with the following definition −
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<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 −

public void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Accessing Resources in XML
Consider the following resource XML res/values/strings.xml file that includes a color resource and a string
resource −

<?xml version="1.0" encoding="utf-8"?>


<resources>
<color name="opaque_red">#f00</color>
<string name="hello">Hello!</string>
</resources>
Now you can use these resources in the following layout file to set the text color and text string as follows −

<?xml version="1.0" encoding="utf-8"?>


<EditText xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textColor="@color/opaque_red"
android:text="@string/hello" />
UNIT-4 ANDROID & ITS APPLICATIONS
Now if you will go through previous chapter once again where I have explained Hello World! example, and I'm
sure you will have better understanding on all the concepts explained in this chapter. So I highly recommend to
check previous chapter for working example and check how I have used various resources at very basic level.
Using Progress Bar:
Progress bars are used to show progress of a task. For example, when you are uploading or downloading
something from the internet, it is better to show the progress of download/upload to the user.
In android there is a class called ProgressDialog that allows you to create progress bar. In order to do this, you
need to instantiate an object of this class. Its syntax is.

ProgressDialog progress = new ProgressDialog(this);


Now you can set some properties of this dialog. Such as, its style, its text etc.

progress.setMessage("Downloading Music :) ");


progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setIndeterminate(true);
Apart from these methods, there are other methods that are provided by the ProgressDialog class

Sr. No Title & description


1 getMax() This method returns the maximum value of the progress.

2 incrementProgressBy(int diff) This method increments the progress bar by the difference of value
passed as a parameter.

3 setIndeterminate(boolean indeterminate) This method sets the progress indicator as determinate or


indeterminate.

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

final int totalProgressTime = 100;


final Thread t = new Thread() {
@Override
public void run() {
int jumpTime = 0;

while(jumpTime < totalProgressTime) {


try {
sleep(200);
jumpTime += 5;
progress.setProgress(jumpTime);
UNIT-4 ANDROID & ITS APPLICATIONS
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
t.start();
}
You can easily control your ringer volume and ringer profile i-e:(silent,vibrate,loud e.t.c) in android. Android
provides AudioManager class that provides access to these controls.

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.

private AudioManager myAudioManager;


myAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
Once you instantiate the object of AudioManager class, you can use setRingerMode method to set the audio or
ringer profile of your device. 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.

Sr.No Mode & Description


1 RINGER_MODE_VIBRATE This Mode sets the device at vibrate mode.

2 RINGER_MODE_NORMAL This Mode sets the device at normal(loud) mode.

3 RINGER_MODE_SILENT This Mode sets the device at silent mode.

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

int mod = myAudioManager.getRingerMode();


Apart from the getRingerMode method, there are other methods available in the AudioManager class to control
the volume and other modes. They are listed below.

Sr.No Method & description


1 adjustVolume(int direction, int flags) This method adjusts the volume of the most relevant stream

2 getMode() This method returns the current audio mode

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

5 isMusicActive() This method checks whether any music is active.

6 startBluetoothSco() This method Start bluetooth SCO audio connection

7 stopBluetoothSco() This method stop bluetooth SCO audio connection.

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.

Methods of MediaPlayer class


There are many methods of MediaPlayer class. Some of them are as follows:
Method Description
public void setDataSource(String path) sets the data source (file path or http url) to use.
public void prepare() prepares the player for playback synchronously.
public void start() it starts or resumes the playback.
public void stop() it stops the playback.
public void pause() it pauses the playback.
public boolean isPlaying() checks if media player is playing.
public void seekTo(int millis)seeks to specified time in miliseconds.
public void setLooping(boolean looping) sets the player for looping or non-looping.
public boolean isLooping() checks if the player is looping or non-looping.
public void selectTrack(int index) it selects a track for the specified index.
public int getCurrentPosition() returns the current playback position.
public int getDuration() returns duration of the file.
public void setVolume(float leftVolume,float rightVolume) sets the volume on this player.
Android Video Player Example
By the help of MediaController and VideoView classes, we can play the video files in android.
UNIT-4 ANDROID & ITS APPLICATIONS
MediaController class
The android.widget.MediaController is a view that contains media controls like play/pause, previous, next, fast-
forward, rewind etc.

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;

public class VideoPlayerActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_player);
UNIT-4 ANDROID & ITS APPLICATIONS

final VideoView videoView =


(VideoView) findViewById(R.id.videoView1);

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 {

public static void main(String[] args) {


UNIT-4 ANDROID & ITS APPLICATIONS

ArrayList&lt;String&gt; arrayListOfFruit = new ArrayList&lt;String&gt;();


arrayListOfFruit.add("Apple");
arrayListOfFruit.add("Orange");
arrayListOfFruit.add("Mango");
arrayListOfFruit.add("Banana");
System.out.println(arrayListOfFruit);

}
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!

We do this like so:


import java.util.HashMap;
import java.util.Map;

Map&lt;String, String&gt; phoneBook = new HashMap&lt;String, String&gt;();


phoneBook.put("Adam", "229901239");
phoneBook.put("Fred", "981231999");
phoneBook.put("Dave", "123879122");
System.out.println("Adam's Number: " + phoneBook.get("Adam"));
UNIT-4 ANDROID & ITS APPLICATIONS
Multi-dimensional Arrays.
int[][] twoDimensions = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
};
int[][][] threeDimensions = {
{
{1, 2, 3},
{4, 5, 6}
},
{
{-1, -2, -3},
{-4, -5. -61},
}
};

You might also like