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 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().
Related
I'm making a quiz app in which there is a sound game.But i find that sound keeps playing even when app is closed. Two time I'm using mediaplayer.
1.while clicking on image button.
2.on changing question.
Question is changed every 15 sec and after killing app sound is getting played every 15 seconds.
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.start();
}
});
btnA.setOnClickListener(this);
btnB.setOnClickListener(this);
btnC.setOnClickListener(this);
btnD.setOnClickListener(this);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
}
#Override
protected void onResume()
{
super.onResume();
questionPlay = db.getMorseQuestionMode(mode);
totalQuestion = questionPlay.size();
mCountDown = new CountDownTimer(TIMEOUT, INTERVAL) {
#Override
public void onTick(long millisUntilFinished) {
progressBar.setProgress(progressValue);
progressValue++;
}
#Override
public void onFinish() {
mCountDown.cancel();
showQuestion(++index);
}
};
showQuestion(index);
}
private void showQuestion(int index) {
if (index < totalQuestion) {
thisQuestion++;
txtQuestion.setText(String.format("%d/%d", thisQuestion, totalQuestion));
progressBar.setProgress(0);
progressValue = 0;
int QusId = this.getResources().getIdentifier(questionPlay.get(index).getQus().toString(), "raw", getPackageName());
btnA.setText(questionPlay.get(index).getAnswerA());
btnB.setText(questionPlay.get(index).getAnswerB());
btnC.setText(questionPlay.get(index).getAnswerC());
btnD.setText(questionPlay.get(index).getAnswerD());
mCountDown.start();
mediaPlayer= MediaPlayer.create(this,QusId);
mediaPlayer.start();
} else {
Intent intent = new Intent(this, Done.class);
Bundle dataSend = new Bundle();
dataSend.putInt("SCORE", score);
dataSend.putInt("TOTAL", totalQuestion);
dataSend.putInt("CORRECT", correctAnswer);
intent.putExtras(dataSend);
startActivity(intent);
finish();
}
}
#Override
public void onClick(View v) {
mCountDown.cancel();
if (index < totalQuestion) {
Button clickedButton = (Button) v;
if (clickedButton.getText().equals(questionPlay.get(index).getCorrectAnswer())) {
score += 10; // increase score
correctAnswer++; //increase correct answer
showQuestion(++index);
} else {
vibrator.vibrate(50);
showQuestion(++index); // If choose right , just go to next question
}
txtScore.setText(String.format("%d", score));
}
}
//CLicking back Button
public void onBackPressed() {
showExitAlertBox();
}
public void showExitAlertBox() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setMessage("You want to quit the play?");
//Yes Quit then go to category page
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int button) {
Intent intent = new Intent(getApplicationContext(), CategorySecond.class);
startActivity(intent);
}
});
//no Quit stay on same page
alertDialog.setNegativeButton("NO", null);
alertDialog.show();
mediaPlayer.stop();
}
}
Error Showing us below
W/MediaPlayer-JNI: MediaPlayer finalized without being released
Cancel your timer and stop mediaplayer if playing in onStop
#Override
public void onStop() {
if (mediaPlayer.isPlaying())
mediaPlayer.stop();
if(mCountDown != null)
mCountDown.cancel();
super.onStop();
}
handle on destroy
#Override
public void onDestroy() {
if (mediaPlayer.isPlaying())
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
if(mCountDown != null)
mCountDown.cancel();
}
You have not released the mediaplayer properly.
Use
protected void onStop(){
mediaPlayer.release();
mediaPlayer = null;
}
call this method where ever required.
I wanna create android app which after 30 second will display to me AlertDialog
I did it but i wanna make AlertDialog will display any where in android for example in home of android.
like this http://www.papktop.com/wp-content/uploads/2012/01/Popup-Notifier-1.jpg
it is my code (main Activity )
public class MainActivity extends ActionBarActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//EventBus.getDefault().register(this);
mTextField = (TextView) findViewById(R.id.mTextField);
}
public void show(View view) {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setMessage("Nek Test");
// alertDialog.setIcon(getResources().getDrawable(R.mipmap.notification_image));
alertDialog.setTitle("Reminder");
alertDialog.setPositiveButton("Got it", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
alertDialog.show();
}
}.start();
}
}
For show a dialog outside the app, for example over the Home you need to put this permission in the manifest:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
Create a service like this:
public class AlertService extends Service {
private static Context context;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
context = this;
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setMessage("Nek Test");
alertDialog.setTitle("Reminder");
/**ADD THIS FOR DISPLAY THE ALERT ANYWHERE*/
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.setPositiveButton("Got it", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
alertDialog.show();
}
}.start();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}//End class
And finally start the service from activity:
startService(new Intent(this, AlertService.class));
and add this line into the "application" tag in the manifest:
<service android:name=".AlertService" />
There are many ways to do this :
1- Implement a service that will start in the main activity and in the service execute a timer, and whenever the timer finishes it will call a broadcast receiver and this receiver will trigger the showing of the alert dialogue.
2- You could use otto : http://square.github.io/otto/
In otto you have to register every activity to otto and unregister onDestroy off course. The timer has to be in an asynctask and on the post execute you post a certain result. Then you subscribe the onAsyncTaskResult in each activity and trigger the alert dialogue there.
3- You also use otto but this time do not subscrib to onAsyncTaskResult and instead of posting in the onPostExecute send a broadcast. Have a broadcast listener ready and on receive show the alert dialogue
This code works best for me without any errors
public class AlertService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
final AlertDialog alertDialog = new AlertDialog.Builder(AlertService.this).create();
alertDialog.setMessage("Nek Test");
alertDialog.setTitle("Reminder");
alertDialog.setButton("Got it", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
/**ADD THIS FOR DISPLAY THE ALERT ANYWHERE*/
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.show();
return flags;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
I am trying to open a AlertDialog. When this AlertDialog is opened, the threads need to wait for user input in order to continue its program. I read that I need to lock the object thats need to wait and notified. When I run this code on my phone. The alertdialog won't show, and it looks like the app is looping, because after a few seconds I get a message that the app isn't responding. Below you will find the code I wrote.. By the way. I am a virgin to android programming. So please be gentle :P
public class EditTagActivity extends Activity{
AlertDialog alertDialog;
Runnable h = new Runnable()
{
# Override
public void run()
{
alertDialog.show();
synchronized(g)
{
try
{
Log.d("Threads", "g.wait()");
g.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
};
Runnable g = new Runnable()
{
#Override
public void run()
{
Log.d("Threads", "createAlertDialog()");
createAlertDialog();
runOnUiThread(h);
}
};
public AlertDialog alert;
Runnable test = new dialogManager();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_tag);
Log.d("Threads", "setup()");
setup();
}
void setup()
{
Log.d("Threads", "g.run()");
g.run();
}
void createAlertDialog()
{
Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Alert");
alert.setMessage("Flaq");
alert.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
synchronized(g)
{
Log.d("Threads", "g.notifyAll");
g.notifyAll();
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
synchronized(g)
{
Log.d("Threads", "g.notifyAll");
g.notifyAll();
}
}
});
alertDialog = alert.create();
}
}
Instead of Java's Thread and Runnable approach, you should use Android's AsyncTask, It helps you resolve this more simply by overriding the onPreExecute and onPostExecute methods to handle things just before and after running the code in background.
This post has a good example for using the AsyncTask class.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Can’t create handler inside thread that has not called Looper.prepare()
I want to call the alertdialogbox in the thread as follows
public class connect implements Runnable
{
public void run() //run method
{
AlertDialog.Builder alert = new AlertDialog.Builder(cordovaExample.activity);
alert.setTitle("Confirm");
alert.setMessage("Are you sure?");
alert.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Do nothing but close the dialog
dialog.dismiss();
}
});
alert.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Do nothing
dialog.dismiss();
}
});
AlertDialog s = alert.create();
alert.show();
}
}
I am calling this thread from the following activity
public class cordovaExample extends DroidGap
{
Context mcontext;
public static cordovaExample activity;
private static MediaPlayer music=null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
activity=this;
super.init();
new Thread(new connect(this)).start();
}
}
but its giving error
Can't create handler inside thread that has not called Looper.prepare()
Any help will be appreciated
Write this line in App UI thread
alert.show();
Something like this
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
alert.show();
}
});
you cant do changes in ui while thread is running.If u want to do so,Use Handler or runOnUiThead or best option is to use AsyncTask.
I made an activity that has an audio as a background music. When i add a skip button to move to another activity the background music of my first activity was continuously playing. Here's my code, kindly check and post what should i add to my code. Thanks in advance!
public class pgone extends Activity {
protected boolean _active = true;
protected int _splashTime = 7000;
public void onAttachedToWindow() {
super.onAttachedToWindow();
Window window = getWindow();
window.setFormat(PixelFormat.RGBA_8888);
}
MediaPlayer audio;
MediaPlayer SLONE;
private long splashDelay = 6000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pgone);
TimerTask task = new TimerTask()
{
public void run() {
Intent mainIntent = new Intent().setClass(pgone.this, pgtwo.class);
startActivity(mainIntent);
finish();
}
};
final Timer timer = new Timer();
timer.schedule(task, splashDelay);
audio = MediaPlayer.create(this,R.raw.storyaud);
audio.start();
SLONE = MediaPlayer.create(this,R.raw.sl1);
SLONE.start();
final MediaPlayer mp = MediaPlayer.create(this, R.raw.buttonbeep);
final Vibrator mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
Button skipButton = (Button)findViewById(R.id.skip);
skipButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent skipIntent = new Intent(pgone.this,choose.class);
startActivity(skipIntent);
mp.start();
mVibrator.vibrate(500);
finish();
timer.cancel();
timer.purge();
}
});
}
protected void exitByBackKey() {
AlertDialog alertbox = new AlertDialog.Builder(this)
.setMessage("Do you want to exit the game?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
}
})
.show();
}
}
You should stop the audio before moving to the next Activity. Try replacing mp.start() by mp.stop() here,
Button skipButton = (Button)findViewById(R.id.skip);
skipButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent skipIntent = new Intent(pgone.this,choose.class);
startActivity(skipIntent);
mp.stop();
mVibrator.vibrate(500);
finish();
timer.cancel();
timer.purge();
}
});
Please Write mp.stop() mp.reset() instead of mp.start() on click event of skip button, and see below link for more information.
Media Player example of Playing Sounds
Simple Android Mp3 Media Player
The easiest and most efficient way -
#Override
protected void onPause() {
super.onPause();
yoursMusicPlayerObject.release();
}
Exploit Activity life cycle's onPause phase when you jump to next activity .Just release the I/O resources under use which is yours MediaPlayer object here .