I am trying to stop a media player and get out of my activity class whenever the stop option of the process dialog is pressed,but by using the below code开发者_Python百科 i am able to getting out of my activity class but unable to stop the media player sound ,and it is running continuously till the thread stop..
Please help me on this matter Thanx in advance..
public class Test_Service extends Activity {
private MediaPlayer mp;
private Thread welcomeThread;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mp = MediaPlayer.create(Test_Service.this,R.raw.alarm1);
welcomeThread=new Thread() {
int wait = 0;
@Override
public void run() {
try {
super.run();
while (wait <30000) {
mp.start();
sleep(3000);
wait +=3000;
}
} catch (Exception e) {
System.out.println("EXc=" + e);
} finally {
}
}
};
new AlertDialog.Builder(Test_Service.this)
.setTitle("Alarm is running")
.setPositiveButton("Stop",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
mp.stop();
welcomeThread.stop();
Test_Service.this.finish();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
mp.stop();
Test_Service.this.finish();
}
})
.create().show();
welcomeThread.start();
}
}
First of all, you should use a Handler
with it's postDelayed()
method to delay the start.
Furthermore you can set the following OnDismissListener
on your AlertDialog and stop the player there to avoid code repetition.
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
mp.release();
handler.removeCallbacks(startingRunnable);
finish();
}
});
MediaPlayer.release()
will stop your MediaPlayer and release it. If you want to reuse this MediaPlayer you will have to create a new one after calling release()
.
精彩评论