Handling Interruption

This is a sample program to show how to handle any type of interruption. The program will play an audio and when any type of interruption will occur the sound will pause and resume at end of the interruption.

Underlying Algorithm:

Basic description of algorithm in step by step form:

1.) Create a Project HandleInterruption.
2.) Put an audio file in raw folder and keep it inside the res folder.

3.) We will handle interruption in the onPause() and onResume() methods :

 

public void onPause()
{
super.onPause();
mPlayer.pause();
}
public void onResume()
{
super.onResume();
mPlayer.start();
}

 

 

4.) Run the application.

Steps to Create:

1.) Open Eclipse. Use the New Project Wizard and select Android Project Give the respective project name i.e. HandleInterruption. Enter following information:
Project name: HandleInterruption
Build Target: Android 2.1
Application name: HandleInterruption
Package name: com.sample.HandleInterruption
Create Activity: HandleInterruption

On Clicking Finish HandleInterruption code structure is generated with the necessary Android Packages being imported along with HandleInterruption.java. HandleInterruption class will look like following:

 

package com.sample.HandleInterruption;

import android.app.Activity;
import android.os.Bundle;
import android.media.MediaPlayer;

public class HandleInterruption extends Activity {
MediaPlayer mPlayer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

mPlayer = MediaPlayer.create(this, R.raw.preview);
mPlayer.start();
}
public void onPause() {
super.onPause();
mPlayer.pause();
}
public void onResume() {
super.onResume();
mPlayer.start();
}
}

 

 

Output –The final output:

Leave a Comment: