Akshay J Akshay J - 1 month ago 7
Android Question

Alert Dialog: play mp3 till it's displayed

I am using the following code to display a notification to the user:

AlertDialog.Builder alert = new AlertDialog.Builder(track.this);
alert.setTitle("Bus arriving !");
alert.setMessage("Bus has reached into your tracking area");
alert.setPositiveButton("OK",null);
alert.show();


and I have the following code to play a notification alert to the user:

void PlayAlertfNeeded()
{
try {
if (player.isPlaying()) {
player.stop();
player.release();
player = new MediaPlayer();
}

ToneGenerator toneGen1 = new ToneGenerator(AudioManager.STREAM_ALARM, 100);
toneGen1.startTone(ToneGenerator.TONE_CDMA_ABBR_ALERT,500);
toneGen1.startTone(ToneGenerator.TONE_CDMA_ABBR_ALERT,2000);


AssetFileDescriptor descriptor = getAssets().openFd("canttrackthebus.mp3");
player.reset();
player.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();

player.prepare();
player.setVolume(1f, 1f);
player.setLooping(false);
player.start();
} catch (Exception e) {
e.printStackTrace();
}
}


I need to display the alert dialog and keep the mp3 on loop till the user presses the OK button.

There is no onCreate available for Alert, so how can this be achieved?

Answer
 void createDialog(){
        AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
        alert.setTitle("Bus arriving !");
        alert.setMessage("Bus has reached into your tracking area");
        alert.setPositiveButton("OK",null);
        alert.show();

        PlayAlertfNeeded();
        alert.setOnDismissListener(this);
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        if (player != null) {
            player.stop();
            player.release();
        }
    }
Comments