I want the background music to repeat as long as the user stays in a particular screen. Is there a function in the MediaPlayer class that allows you to do the above task?
button1.setOnClickListener(new View.OnClickListener() {
#Overridepublic void onClick(View v) {
Intent intent = new Intent(context,kids_quiz.class);
startActivity(intent);
player=MediaPlayer.create(Games.this,R.raw.macdonald);
player.start();
}
});
Just start it when you are in that Activity, setLooping to true, and when the user leaves the screen destroy the mediaPlayer in Activity.onDestroy(and maybe onPause depending on what you want to accomplish) method.
Remember it is important to destroy a mediaPlayer when you're done with it as it consumes a lot of resources.
Related
There'd be a button on the home screen which would play a certain song and change the background image of the button. If the user clicks on the button again (when the music is playing) then the music should stop and the background image of the button should set itself back to the general position. But it looks like the program can't detect if my Mediaplayer is playing. What am I missing here?
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
AppWidgetManager appWidgetManager= AppWidgetManager.getInstance(context);
RemoteViews rv= new RemoteViews(context.getPackageName(),
R.layout.playbtn_widget);
if (intent.getAction().equals("btnPlay")) {
if (!mediaPlayer.isPlaying()) {
mediaPlayer= MediaPlayer.create(context,R.raw.itsmylife);
mediaPlayer.start();
rv.setImageViewResource(R.id.imbtnwidget,
R.drawable.btnk32);
} else {
mediaPlayer.stop();
}
mediaPlayer.setOnCompletionListener(mediaPlayer -> {
rv.setImageViewResource(R.id.imbtnwidget,
R.drawable.btnk3);
appWidgetManager.updateAppWidget(new ComponentName(context,
BtnAppWidgetProvider.class), rv);
});
appWidgetManager.updateAppWidget(new ComponentName(context,
BtnAppWidgetProvider.class), rv);
}
}
It should set the background image back and stop the music when I tap on the button, but it just starts the mediaplayer again and the background image remains the same. I have no idea how I could fix this. It seems like it creates a new mediaplayer every single time
Issue
It creates a new Media Player because the class is recreated or re-executed. This clears all the variables and re-defines them. This makes the issue in your case.
Solution
Just create a class name anything like MediaPlayerHelper.java
Create a variable of MediaPlayer which is public and static. Like this:
public static MediaPlayer mp;
Now, when the button is pressed, you can check if it is playing or not. Something like this:
if(MediaPlayerHelper.mp != null && MediaPlayerHelper.mp.isPlaying()){
// the media player is currently playing. Stop it.
}else{
// the media is not playing. Start it
}
Hello I am making boxing countdown timer and I have the ring that plays at the end and start of each round. I would like to make "end" button but when I am using Intent like bellow I go to previously activity but mp3 files still working in background. How to end all tasks and go to previously activity without any mp3 and tasks in background?
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder dialog=new AlertDialog.Builder(Main3Activity.this);
dialog.setMessage("Czy napewno chcesz wyjść z trenignu?");
dialog.setPositiveButton("Tak", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent=new Intent(Main3Activity.this, Main5Activity.class);
startActivity(intent);
}
});
dialog.setNegativeButton("Nie", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog dialogg=dialog.create();
dialogg.show();
}
});`
removeEventListener()
use HTML DOM removeEventListener() Method
btn1.removeEventListener("click", function(){});
see: https://www.w3schools.com/JSREF/met_element_removeeventlistener.asp
Your question looks incomplete or incorrect to me.
If you want to go to previous activity from the activity stack, then you should not use intent to start the previous activity, rather finish the current Activity.
If you want to stop playing the bell ring once the user is not interacting with the Main3Activity or when Main3Activity is not visible to the user. Then best practice is to write a code in the onStop() method of the Main3activity to check for the object which is responsible for playing the sound and safely call stop or destroy the object.
simply finish the activity which can destroy the instance of activity and everything that is running on that particular activity. simply write this line after startActivity
finish();
I'm trying to animate my imagebuttons by making them wobble when clicked.
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.buttonStart:
buttonStart.startAnimation(wobble);
Intent i;
i = new Intent(this, CityRendActivity.class);
startActivity(i);
break;
}
}
When I click my Start button, it very slowly starts to wobble, but only appears to shake back and forth like 3 times, and a lot slower than I have defined in the xml file. When I remove the lines that contain the intent code, the wobble works perfectly and the button shakes 5 times quickly (though now of course it doesn't load up my other activity).
So why would the code after the wobble animation effect how it's run? Doesn't each line get resolved individually before proceeding? I don't understand how loading up a different activity would effect the animation that I've set up. Any thoughts? Thanks.
Try adding animation listener for your animation and onAnimationEnd() start your Activity Intent.
wobble.setAnimationListener(new AnimationListener(){
#Override
public void onAnimationStart(Animation animation){}
#Override
public void onAnimationRepeat(Animation animation){}
#Override
public void onAnimationEnd(Animation animation){
startActivity(new Intent(YourCurrentActivity.this, CityRendActivity.class)); // if the code is in Fragment, then replace YourCurrentActivity.this by getActivity()
}
});
Actually In this code. animation and starting a new activity will execute at a same time. that will disturb the animation in between. so delay the starting of activity with your animation time. so that animation will completed and then your Activity will start.hope this work for you.
new Handler().postDelayed(new Runnable(){
#Overide
void run(){
startActivity(new Intent(this, CityRendActivity.class));
}
},time_ofanimation);
Here in my MainActivity.java I have an object MediaPlayer, which plays a sound when you click playB button and pause by pressing pauseB. Everything is working fine. But if you re-open the app and click pauseB, the sound continues to play. How to fix it? How to catch the current playing MediaPlayer?
public class MainActivity extends ActionBarActivity {
Button playB;
Button pauseB;
Context c;
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button playB = (Button) findViewById(R.id.playB);
Button pauseB = (Button) findViewById(R.id.pauseB);
mp = mp.create(this, R.raw.fawaid_1);
playB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mp.start();
}
});
pauseB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mp.pause();
}
});
}
}
when you re-open the app, onCreate is called again, hence you have a new MediaPlayer object, and from that moment, play and pause buttons will control that new player object instead of a previous one. That's why your pause button will have no effect on the sound that started BEFORE you minimized the app. And if you press play button now, you will have two sounds playing at the same time
one way to overcome this, is to check if media player has already been initialized:
if(mp==null)
mp = MediaPlayer.create(this, R.raw.fawaid_1);
It is advisable to use Service with AIDL in developing music player.
Reasons.
You can retain the control again once you go back in your activity.
It is easy to perform an inter process communication.
Here is a simple music Player that runs on the Background, Music Player
The song I used in this music player is Owned by SnowFlakes
When a user presses the back button on an intent, the application should quit. How can I ensure the application quits when the back button is pressed?
In my Home Activity I override the "onBackPressed" to:
#Override
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
so if the user is in the home activity and press back, he goes to the home screen.
I took the code from Going to home screen Programmatically
Immediately after you start a new activity, using startActivity, make sure you call finish() so that the current activity is not stacked behind the new one.
EDIT
With regards to your comment:
What you're suggesting is not particularly how the android app flow usually works, and how the users expect it to work. What you can do if you really want to, is to make sure that every startActivity leading up to that activity, is a startActivityForResult and has an onActivityResult listener that checks for an exit code, and bubbles that back. You can read more about that here. Basically, use setResult before finishing an activity, to set an exit code of your choice, and if your parent activity receives that exit code, you set it in that activity, and finish that one, etc...
A better user experience:
/**
* Back button listener.
* Will close the application if the back button pressed twice.
*/
#Override
public void onBackPressed()
{
if(backButtonCount >= 1)
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else
{
Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show();
backButtonCount++;
}
}
The app will only exit if there are no activities in the back stack. SO add this line in your manifest android:noHistory="true" to all the activities that you dont want to be back stacked.And then to close the app call the finish() in the OnBackPressed
<activity android:name=".activities.DemoActivity"
android:screenOrientation="portrait"
**android:noHistory="true"**
/>
Why wouldn't the user just hit the home button? Then they can exit your app from any of your activities, not just a specific one.
If you are worried about your application continuing to do something in the background. Make sure to stop it in the relevant onPause and onStop commands (which will get triggered when the user presses Home).
If your issue is that you want the next time the user clicks on your app for it to start back at the beginning, I recommend putting some kind of menu item or UI button on the screen that takes the user back to the starting activity of your app. Like the twitter bird in the official twitter app, etc.
Use onBackPressedmethod
#Override
public void onBackPressed() {
finish();
super.onBackPressed();
}
This will solve your issue.
First of all, Android does not recommend you to do that within the back button, but rather using the lifecycle methods provided. The back button should not destroy the Activity.
Activities are being added to the stack, accessible from the Overview (square button since they introduced the Material design in 5.0) when the back button is pressed on the last remaining Activity from the UI stack. If the user wants to close down your app, they should swipe it off (close it) from the Overview menu.
Your app is responsible to stop any background tasks and jobs you don't want to run, on onPause(), onStop() and onDestroy() lifecycle methods. Please read more about the lifecycles and their proper implementation here: http://developer.android.com/training/basics/activity-lifecycle/stopping.html
But to answer your question, you can do hacks to implement the exact behaviour you want, but as I said, it is not recommended:
#Override
public void onBackPressed() {
// make sure you have this outcommented
// super.onBackPressed();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
To exit from an Android app, just simply use.
in your Main Activity, or you can use Android manifest file to set
android:noHistory="true"
finish your current_activity using method finish() onBack method of your current_activity
and then add below lines in onDestroy of the current_activity for Removing Force close
#Override
public void onDestroy()
{
android.os.Process.killProcess(android.os.Process.myPid());
super.onDestroy();
}
I modified #Vlad_Spays answer so that the back button acts normally unless it's the last item in the stack, then it prompts the user before exiting the app.
#Override
public void onBackPressed(){
if (isTaskRoot()){
if (backButtonCount >= 1){
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}else{
Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show();
backButtonCount++;
}
}else{
super.onBackPressed();
}
}
you can simply use this
startActivity(new Intent(this, Splash.class));
moveTaskToBack(true);
The startActivity(new Intent(this, Splash.class)); is the first class that will be lauched when the application starts
moveTaskToBack(true); will minimize your application
Add this code in the activity from where you want to exit from the app on pressing back button:
#Override
public void onBackPressed() {
super.onBackPressed();
exitFromApp();
}
private void exitFromApp() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
}