简体   繁体   中英

How to add sound when back button is pressed in complete application

我的应用程序很大,有很多活动和片段,是否可以在应用程序中的任何地方随时按下后退按钮来添加声音?

Override onBackPressed() method of your activity class

@Override
public void onBackPressed()
{
    super.onBackPressed();

    String tonePath = "android.resource://in.plackal.juswrite2/raw/" + R.raw.tone1;
    RingtoneManager ringToneManager = RingtoneManager.getRingtone(getApplicationContext(), Uri.parse(tonePath));

    ringToneManager.play();

    finish();
}

You can make a custom class BaseActivity which extends Activity class.

In that, override onBackPressed like this:

public class BaseActivity extends Activity{

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        super.onBackPressed();
        //play sound

    }
}

Now, in all your activities, extend BaseActivity instead of Activity .

public class MyActivity1 extends BaseActivity{

}

and

public class MyActivity2 extends BaseActivity{

}

Hope this helps.

I think you just have to @Override the onBackPressed() , and then inside of this method put the sound.

@Override
public void onBackPressed() {
    Log.d("back", "onBackPressed Called");
    MediaPlayer mp = MediaPlayer.create(getApplicationContext(),R.raw.AudioFile);
    mp.start();
}

Hope it helps.

Derive all your activities from a base activity and play your sound in onBackPressed in the base activity.

OK I voted for one of the faster answers (FlamePrincess) that included code.

Use SoundPool class to play small sound files.

Override Back button for every Activity and play the sound inside that method.

@Override
public void onBackPressed() {
   // Write your sound play logic over here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM