Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 20

MOBILE APPLICATION DEVELOPMENT

LAB REPORT # 13

Submitted To:

Sir Shahzad Arif

Submitted By:

Mirza Sultan Mehmood Baig

Reg No:

16-CS-024
Experiment # 13

Accessing Android Hardware

Objective
In this Lab, you’ll take a closer look at some of these hardware APIs..

Software Tool
1. Android Studio

Theory
The hardware APIs available in android include:
• ❑ A telephony package that provides access to calls and phone status.
• ❑ A multimedia playback and recording library.
• ❑ Access to the device camera for taking pictures and previewing video.
• ❑ Extensible support for sensor hardware.
• ❑ Accelerometer and compass APIs to monitor orientation and movement.
• ❑ Communications libraries for managing Bluetooth, network, and Wi-Fi hardware

Android provides many ways to control playback of audio/video files and streams. One of this way
is through a class called MediaPlayer.
Android is providing MediaPlayer class to access built-in mediaplayer services like playing
audio,video e.t.c. In order to use MediaPlayer, we have to call a static Method create() of this class.
This method returns an instance of MediaPlayer class. Its syntax is as follows –

MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);

The second parameter is the name of the song that you want to play. You have to make a new folder
under your project with name raw and place the music file into it.
Once you have created the Mediaplayer object you can call some methods to start or stop the music.
These methods are listed below.
mediaPlayer.start(); mediaPlayer.pause();

On call to start() method, the music will start playing from the beginning. If this method is called
again after the pause() method, the music would start playing from where it is left and not from the
beginning.
In order to start music from the beginning, you have to call reset() method. Its syntax is given below.–

mediaPlayer.reset();

Here is an example demonstrating the use of MediaPlayer class. It creates a basic media player that
allows you to forward, backward, play and pause a song. Procedure:

1. Creating a New project:


 Open Android Studio and then click on File -> New -> New project.

 Then select the Empty Activity and click Next.


 Then type the Application name i.e “My Application”. Select Java as language, then select the
Minimum API as shown below and click Finish.
 It will take some time to build and load the project.  After completion it will look as given below.

2. Designing layout for the Android Application:

Designing Layout for Main Activity:

 Click on app → src → main →res → layout → activity_main.xml.


 Now click on Text as shown below.


 Then delete the code which is there and type the code as given below.

MainActivity.XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="100dp"
android:text="Audio Video Player"
android:layout_centerHorizontal="true"
android:textColor="@color/colorAccent"
android:textSize="30dp"

/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="150dp"
android:layout_centerHorizontal="true"
android:text="Play MP3"
android:textSize="50dp"
android:textColor="@color/colorPrimaryDark"
android:id="@+id/but1"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="250dp"
android:layout_centerHorizontal="true"
android:text="Play MP4"
android:textSize="50dp"
android:textColor="@color/colorPrimaryDark"
android:id="@+id/but2"
/>

</RelativeLayout>

Main2_Activity.XML
<?xml version="1.0" encoding="utf-8"?> <Button
<RelativeLayout android:id="@+id/button4"
xmlns:android="http://schemas.android.com/apk/
android:layout_width="66dp"
res/android"
android:layout_height="wrap_content"
xmlns:tools="http://schemas.android.com/tools" android:layout_alignTop="@+id/button3"
android:layout_width="match_parent"
android:layout_marginStart="14dp"
android:layout_height="match_parent"
android:layout_marginLeft="14dp"
tools:context=".MainActivity">
android:layout_marginTop="0dp"
android:layout_marginEnd="0dp"
<TextView android:text="Music Palyer"
android:layout_width="wrap_content" android:layout_toEndOf="@+id/button3"

android:layout_height="wrap_content" android:layout_toRightOf="@+id/button3"

android:id="@+id/textview" android:text="@string/rewind" />

android:textSize="35dp"
android:layout_alignParentTop="true" <SeekBar
android:layout_centerHorizontal="true" /> android:layout_width="wrap_content"
android:layout_height="wrap_content"
<TextView android:id="@+id/seekBar"
android:layout_width="wrap_content" android:layout_alignLeft="@+id/textview"
android:layout_height="wrap_content" android:layout_alignStart="@+id/textview"
android:text="Enjoy the Music" android:layout_alignRight="@+id/textview"
android:id="@+id/textView" android:layout_alignEnd="@+id/textview"
android:layout_below="@+id/textview" android:layout_above="@+id/button" />
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24" <TextView
android:textSize="35dp" /> android:layout_width="wrap_content"
android:layout_height="wrap_content"
<ImageView
android:textAppearance="?android:attr/textAppeara
android:layout_width="wrap_content"
nceSmall"
android:layout_height="wrap_content"
android:text="Small Text"
android:id="@+id/imageView"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_above="@+id/seekBar"
android:layout_centerHorizontal="true"
android:layout_toLeftOf="@+id/textView"
android:src="@drawable/nokia"/>
android:layout_toStartOf="@+id/textView" />

<Button
<TextView
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_width="61dp"
android:layout_height="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true" android:textAppearance="?android:attr/textAppeara
nceSmall"
android:layout_alignParentLeft="true"
android:text="Small Text"
android:layout_alignParentBottom="true" android:id="@+id/textView3"
android:layout_marginStart="37dp" android:layout_above="@+id/seekBar"
android:layout_marginLeft="37dp" android:layout_alignRight="@+id/button4"
android:layout_marginBottom="3dp" android:layout_alignEnd="@+id/button4" />
android:text="@string/forward" />
<TextView
<Button android:layout_width="wrap_content"
android:id="@+id/button2" android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textAppearance="?android:attr/textAppeara
android:layout_height="wrap_content"
nceMedium"
android:text="Medium Text"
android:layout_alignStart="@+id/imageView"
android:id="@+id/textView4"
android:layout_alignLeft="@+id/imageView"
android:layout_alignBaseline="@+id/textView2"
android:layout_alignParentBottom="true"
android:layout_marginStart="110dp"
android:layout_alignBottom="@+id/textView2"
android:layout_marginLeft="110dp"
android:layout_centerHorizontal="true" />
android:layout_marginBottom="2dp"
android:text="@string/pause" />
</RelativeLayout>

<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/button2"
android:layout_marginStart="-1dp"
android:layout_marginLeft="-1dp"
android:layout_marginTop="-2dp"
android:layout_toEndOf="@+id/button2"
android:layout_toRightOf="@+id/button2"
android:text="@string/back" />

Main3Activity.XML
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<VideoView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/videoView"
android:layout_gravity="center" />

</FrameLayout>

 So now the designing part of Main Activity is completed.

3. Java Coding for the Android Application:

 Java Coding for Main Activity:

 Click on app -> java -> com.example.myapplication -> MainActivity.


 Then delete the code which is there and type the code as given below.

 Code for MainActivity.java:

package com.example.finalapp; b1.setOnClickListener(new


View.OnClickListener() {

@Override
import android.content.Intent;
public void onClick(View view) {
import
android.support.v7.app.AppCompatActiv Intent i = new
ity; Intent(MainActivity.this,Main2Activity.cla
ss);
import android.os.Bundle;
startActivity(i);
import android.view.View;
}
import android.widget.Button;
});

b2.setOnClickListener(new
public class MainActivity extends View.OnClickListener() {
AppCompatActivity {
@Override
Button b1,b2;
public void onClick(View view) {
@Override
Intent i = new
protected void onCreate(Bundle Intent(MainActivity.this,Main3Activity.cla
savedInstanceState) { ss);
super.onCreate(savedInstanceState); startActivity(i);

}
setContentView(R.layout.activity_main);
});
b1=(Button)
findViewById(R.id.but1); }

b2=(Button) }
findViewById(R.id.but2);

 Code for Main2Activity.java:

package com.example.finalapp; tx1.setText(String.format("%d min, %d


sec",
import android.media.MediaPlayer;
import android.os.Handler; TimeUnit.MILLISECONDS.toMinutes((long)
import startTime),
android.support.v7.app.AppCompatActivity;
import android.os.Bundle; TimeUnit.MILLISECONDS.toSeconds((long)
import android.view.View; startTime) -
import android.widget.Button;
import android.widget.ImageView; TimeUnit.MINUTES.toSeconds(TimeUnit.MILLI
import android.widget.SeekBar; SECONDS.toMinutes((long)
import android.widget.TextView; startTime)))
import android.widget.Toast; );

import java.util.concurrent.TimeUnit; seekbar.setProgress((int)startTime);

public class MainActivity extends myHandler.postDelayed(UpdateSongTime,100);


AppCompatActivity { b2.setEnabled(true);
private Button b1,b2,b3,b4; b3.setEnabled(false);
private ImageView iv; }
private MediaPlayer mediaPlayer; });

private double startTime = 0; b2.setOnClickListener(new


private double finalTime = 0; View.OnClickListener() {
@Override
private Handler myHandler = new Handler();; public void onClick(View v) {
private int forwardTime = 5000;
private int backwardTime = 5000; Toast.makeText(getApplicationContext(),
private SeekBar seekbar;
private TextView tx1,tx2,tx3; "Pausing
sound",Toast.LENGTH_SHORT).show();
public static int oneTimeOnly = 0; mediaPlayer.pause();
@Override b2.setEnabled(false);
protected void onCreate(Bundle b3.setEnabled(true);
savedInstanceState) { }
super.onCreate(savedInstanceState); });
setContentView(R.layout.activity_main2);
b1.setOnClickListener(new
b1 = (Button) findViewById(R.id.button); View.OnClickListener() {
b2 = (Button) findViewById(R.id.button2); @Override
b3 = (Button)findViewById(R.id.button3); public void onClick(View v) {
b4 = (Button)findViewById(R.id.button4); int temp = (int)startTime;
iv =
(ImageView)findViewById(R.id.imageView); if((temp+forwardTime)<=finalTime){
startTime = startTime + forwardTime;
tx1 = mediaPlayer.seekTo((int) startTime);
(TextView)findViewById(R.id.textView2);
tx2 = Toast.makeText(getApplicationContext(),"You
(TextView)findViewById(R.id.textView3); have Jumped forward 5
tx3 = seconds",Toast.LENGTH_SHORT).show();
(TextView)findViewById(R.id.textView4); }else{
tx3.setText("Song.mp3");
Toast.makeText(getApplicationContext(),"Cannot
mediaPlayer = MediaPlayer.create(this, jump forward 5
R.raw.s1); seconds",Toast.LENGTH_SHORT).show();
seekbar = }
(SeekBar)findViewById(R.id.seekBar); }
seekbar.setClickable(false); });
b2.setEnabled(false);
b3.setOnClickListener(new b4.setOnClickListener(new
View.OnClickListener() { View.OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
int temp = (int)startTime;
Toast.makeText(getApplicationContext(),
"Playing if((temp-backwardTime)>0){
sound",Toast.LENGTH_SHORT).show(); startTime = startTime -
mediaPlayer.start(); backwardTime;
mediaPlayer.seekTo((int) startTime);
finalTime = mediaPlayer.getDuration();
startTime = Toast.makeText(getApplicationContext(),"You
mediaPlayer.getCurrentPosition();
have Jumped backward 5
if (oneTimeOnly == 0) { seconds",Toast.LENGTH_SHORT).show();
seekbar.setMax((int) finalTime); }else{
oneTimeOnly = 1;
} Toast.makeText(getApplicationContext(),"Cannot
jump backward 5
tx2.setText(String.format("%d min, %d seconds",Toast.LENGTH_SHORT).show();
sec", }
}
TimeUnit.MILLISECONDS.toMinutes((long) });
finalTime), }

TimeUnit.MILLISECONDS.toSeconds((long) private Runnable UpdateSongTime = new


finalTime) - Runnable() {
public void run() {
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLI startTime =
SECONDS.toMinutes((long) mediaPlayer.getCurrentPosition();
finalTime))) tx1.setText(String.format("%d min, %d
); sec",

TimeUnit.MILLISECONDS.toMinutes((long)
startTime),

TimeUnit.MILLISECONDS.toSeconds((long)
startTime) -

TimeUnit.MINUTES.toSeconds(TimeUnit.MILLI
SECONDS.
toMinutes((long)
startTime)))
);
seekbar.setProgress((int)startTime);
myHandler.postDelayed(this, 100);
}
};
}

 Main3Activity.java

package com.example.finalapp;
import // When video Screen change
android.support.v7.app.AppCompatActivity size.
;

import android.os.Bundle; mediaPlayer.setOnVideoSizeChangedLi


stener(new
import MediaPlayer.OnVideoSizeChangedListe
android.support.v7.app.AppCompatActivity ner() {
;
@Override
import android.os.Bundle;
public void
import onVideoSizeChanged(MediaPlayer mp,
android.support.v7.app.AppCompatActivity int width, int height) {
;

import android.os.Bundle;
// Re-Set the videoView
import android.app.Activity; that acts as the anchor for the
MediaController
import android.app.ProgressDialog;

import android.content.res.Configuration;
mediaController.setAnchorView(videoV
import android.media.MediaPlayer; iew);

import }
android.media.MediaPlayer.OnPreparedList
});
ener;
}
import android.net.Uri;
});
import android.os.Bundle;

import android.util.Log;
}
import android.widget.MediaController;

import android.widget.VideoView;
// Find ID corresponding to the name of
public class Main3Activity extends
the resource (in the directory raw).
AppCompatActivity {
public int
private VideoView videoView;
getRawResIdByName(String resName) {
private int position = 0;
String pkgName =
private MediaController mediaController; this.getPackageName();
@Override // Return 0 if not found.

protected void onCreate(Bundle int resID =


savedInstanceState) { this.getResources().getIdentifier(resNam
e, "raw", pkgName);
super.onCreate(savedInstanceState);
Log.i("AndroidVideoView", "Res
setContentView(R.layout.activity_main3); Name: " + resName + "==> Res ID = " +
resID);
videoView = (VideoView)
findViewById(R.id.videoView); return resID;
// Set the media controller buttons }
if (mediaController == null) {

mediaController = new
MediaController(Main3Activity.this
); // When you change direction of phone,
this method will be called.
// Set the videoView that acts as the
anchor for the MediaController. // It store the state of video (Current
position)
mediaController.setAnchorView(vid
eoView); @Override

// Set MediaController for VideoView public void


onSaveInstanceState(Bundle
videoView.setMediaController(mediaContr savedInstanceState) {
oller);

} super.onSaveInstanceState(savedInstanc
eState);
try {

// ID of video file.
// Store current position.
int id =
this.getRawResIdByName("myvide
o"); savedInstanceState.putInt("CurrentPositi
on", videoView.getCurrentPosition());
videoView.setVideoURI(Uri.parse("android
.resource://" + getPackageName() + "/" + videoView.pause();
id));
}
} catch (Exception e) {

Log.e("Error", e.getMessage());
e.printStackTrace();

} // After rotating the phone. This


method is called.
videoView.requestFocus();
@Override
// When the video file ready for playback.
public void
videoView.setOnPreparedListener(new onRestoreInstanceState(Bundle
OnPreparedListener() { savedInstanceState) {
public void onPrepared(MediaPlayer
mediaPlayer) { super.onRestoreInstanceState(savedInsta
nceState);
videoView.seekTo(position);

if (position == 0) {
// Get saved position.
videoView.start();
position =
}
savedInstanceState.getInt("CurrentPositi
on");

videoView.seekTo(position);

 Code for string.xml

Code for colors.xml


 So now the Coding part is also completed.

 Now run the application to see the output.


Result:
Thus Media Player Android Application is developed and executed successfully.

Conclusion
In this lab we make application on which a mp3 and mp4 files are being played.

You might also like