Professional Documents
Culture Documents
Some times in your application, if you wanted to ask the user about
taking a decision between yes or no in response of any particular action
taken by the user, by remaining in the same activity and without
changing the screen, you can use Alert Dialog.
Now you have to set the positive (yes) or negative (no) button using the
object of the AlertDialogBuilder class. Its syntax is
alertDialogBuilder.setPositiveButton(CharSequence text,
DialogInterface.OnClickListener listener)
alertDialogBuilder.setNegativeButton(CharSequence text,
DialogInterface.OnClickListener listener)
Apart from this , you can use other functions provided by the builder
class to customize the alert dialog. These are listed below
setIcon(Drawable icon)
1
This method set the icon of the alert dialog box.
setMessage(CharSequence message)
3
This method sets the message to be displayed in the alert dialog
setOnCancelListener(DialogInterface.OnCancelListener
5 onCancelListener)
This method Sets the callback that will be called if the dialog is cancelled.
setTitle(CharSequence title)
6
This method set the title to be appear in the dialog
After creating and setting the dialog builder , you will create an alert dialog
by calling the create() method of the builder class. Its syntax is
alertDialog.show();
This will create the alert dialog and will show it on the screen.
Dialog fragment
Before enter into an example we should need to know dialog
fragment.Dialog fragment is a fragment which can show fragment in
dialog box
@Override
builder.setPositiveButton(R.string.fire, new
DialogInterface.OnClickListener() {
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
finish();
});
return builder.create();
List dialog
It has used to show list of items in a dialog box.For suppose, user need
to select a list of items or else need to click a item from multiple list of
items.At this situation we can use list dialog.
builder.setTitle(Pick a Color)
});
return builder.create();
.setMultiChoiceItems(R.array.toppings, null,
new DialogInterface.OnMultiChoiceClickListener() {
@Override
if (isChecked) {
mSelectedItems.add(which);
else if (mSelectedItems.contains(which)) {
mSelectedItems.remove(Integer.valueOf(which));
})
@Override
...
}
})
@Override
...
});
return builder.create();
Example
The following example demonstrates the use of AlertDialog in android.
Steps Description
1 You will use Android studio to create an Android application and name it
as My Application under a package
com.example.sairamkrishna.myapplication.
5 Run the application and choose a running android device and install the
application on it and verify the results.
Here is the modified code of src/MainActivity.java
package com.example.sairamkrishna.myapplication;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alertDialogBuilder.setPositiveButton("yes",
new DialogInterface.OnClickListener() {
@Override
button",Toast.LENGTH_LONG).show();
});
alertDialogBuilder.setNegativeButton("No",new
DialogInterface.OnClickListener() {
Override
finish();
});
alertDialog.show();
<RelativeLayout
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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Alert Dialog"
android:id="@+id/textView"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorialspoint"
android:id="@+id/textView2"
android:textColor="#ff3eff0f"
android:textSize="35dp"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2"
android:layout_alignLeft="@+id/textView"
android:layout_alignStart="@+id/textView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Alert dialog"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2"
android:layout_marginTop="42dp"
android:onClick="open"
android:layout_alignLeft="@+id/imageView"
android:layout_alignStart="@+id/imageView" />
</RelativeLayout>
Here is ofStrings.xml
<resources>
</resources>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.sairamkrishna.myapplication.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your
actual Android Mobile device with your computer. To run the app from
Android studio, open one of your project's activity files and click
Run icon from the toolbar. Before starting your application, ]Android
studio will display following window to select an option where you want
to run your Android application.
Select your an option and then click on it. For suppose, if you have
clicked on yes button, then result would as follows
if you click on no button it will call finish() and it will close your
application.
Now you will set the source , output and encoding format and output file.
Their syntax is given below.
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
After specifying the audio source and format and its output file, we can
then call the two basic methods prepare and start to start recording the
audio.
myAudioRecorder.prepare();
myAudioRecorder.start();
Apart from these methods , there are other methods listed in the
MediaRecorder class that allows you more control over audio and video
recording.
1 setAudioSource()
2 setVideoSource()
3 setOutputFormat()
4 setAudioEncoder()
This method specifies the audio encoder to be used
5 setOutputFile()
This method configures the path to the file into which the recorded audio
is to be stored
6 stop()
7 release()
Example
This example provides demonstration of MediaRecorder class to capture
audio and then MediaPlayer class to play that recorded audio.
Steps Description
1 You will use Android studio IDE to create an Android application and name
it as AudioCapture under a package
com.example.sairamkrishna.myapplication.
5 Run the application and choose a running android device and install the
application on it and verify the results.
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.IOException;
import java.util.Random;
import android.support.v4.app.ActivityCompat;
import android.content.pm.PackageManager;
import android.support.v4.content.ContextCompat;
buttonStopPlayingRecording ;
MediaRecorder mediaRecorder ;
Random random ;
MediaPlayer mediaPlayer ;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonStopPlayingRecording = (Button)findViewById(R.id.button4);
buttonStop.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(false);
buttonStopPlayingRecording.setEnabled(false);
buttonStart.setOnClickListener(new View.OnClickListener() {
@Override
if(checkPermission()) {
AudioSavePathInDevice =
Environment.getExternalStorageDirectory().getAbsolutePath() +
"/" +
CreateRandomAudioFileName(5) + "AudioRecording.3gp";
MediaRecorderReady();
try {
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
buttonStart.setEnabled(false);
buttonStop.setEnabled(true);
Toast.LENGTH_LONG).show();
} else {
requestPermission();
});
buttonStop.setOnClickListener(new View.OnClickListener() {
@Override
buttonStop.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(true);
buttonStart.setEnabled(true);
buttonStopPlayingRecording.setEnabled(false);
Toast.LENGTH_LONG).show();
});
buttonPlayLastRecordAudio.setOnClickListener(new View.OnClickListener() {
@Override
SecurityException, IllegalStateException {
buttonStop.setEnabled(false);
buttonStart.setEnabled(false);
buttonStopPlayingRecording.setEnabled(true);
try {
mediaPlayer.setDataSource(AudioSavePathInDevice);
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
mediaPlayer.start();
});
buttonStopPlayingRecording.setOnClickListener(new View.OnClickListener() {
@Override
buttonStop.setEnabled(false);
buttonStart.setEnabled(true);
buttonStopPlayingRecording.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(true);
if(mediaPlayer != null){
mediaPlayer.stop();
mediaPlayer.release();
MediaRecorderReady();
});
mediaRecorder=new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(AudioSavePathInDevice);
}
public String CreateRandomAudioFileName(int string){
int i = 0 ;
stringBuilder.append(RandomAudioFileName.
charAt(random.nextInt(RandomAudioFileName.length())));
i++ ;
return stringBuilder.toString();
ActivityCompat.requestPermissions(MainActivity.this, new
@Override
switch (requestCode) {
case RequestPermissionCode:
if (grantResults.length> 0) {
PackageManager.PERMISSION_GRANTED;
PackageManager.PERMISSION_GRANTED;
} else {
Toast.makeText(MainActivity.this,"Permission
Denied",Toast.LENGTH_LONG).show();
break;
WRITE_EXTERNAL_STORAGE);
RECORD_AUDIO);
result1 == PackageManager.PERMISSION_GRANTED;
<RelativeLayout 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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:src="@drawable/abc"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Record"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_alignParentLeft="true"
android:layout_marginTop="37dp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="STOP"
android:id="@+id/button2"
android:layout_alignTop="@+id/button"
android:layout_centerHorizontal="true"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Play"
android:id="@+id/button3"
android:layout_alignTop="@+id/button2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button4"
android:layout_below="@+id/button2"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
/>
</RelativeLayout>
<resources>
</resources>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.sairamkrishna.myapplication.MainActivity"
android:label="@string/app_name" >
<intent-filter>
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your
actual Android Mobile device with your computer. To run the app from
Android studio, open one of your project's activity files and click
Run icon from the toolbar. Before starting your application, Android
studio will display following images.
Now by default you will see stop and play button disable. Just press the
Record button and your application will start recording the audio. It will
display the following screen.
Now just press stop button and it will save the recorded audio to external
sd card. When you click on stop button , the following screen would
appear.
Now just press the play button and and recorded audio will just start
playing on the device. The following message appears when you click on
play button.