Pause other media apps - java

When I start my MediaPlayer, other apps that are playing audio don't stop. Same when using MediaRecorder.
I managed to use AudioManager to have some functionality, but much of that class is either deprecated, or for high APIs.
For example, I can register a callback, but I can't unregister it cause the abandonAudioFocus() is deprecated.
Looking at sources, it tells me to use a MediaSession, but that's too complicated for my simple goal of playing a simple recorded audio, I don't want to use all the functionality of every single Android platform.

You can do that with AudioManager
AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
// Request audio focus for playback
int result = am.requestAudioFocus(focusChangeListener,
// Use the music stream.
AudioManager.STREAM_MUSIC,
// Request permanent focus.
AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
// other app had stopped playing song now , so u can do u stuff now .
}
Audio focus is assigned in turn to each application that requests it.
This means that if another application requests audio focus, your
application will lose it. You will be notifi ed of the loss of audio
focus through the onAudioFocusChange handler of the Audio Focus Change
Listener you registered when requesting the audio focus
private OnAudioFocusChangeListener focusChangeListener =
new OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
AudioManager am =(AudioManager)getSystemService(Context.AUDIO_SERVICE);
switch (focusChange) {
case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) :
// Lower the volume while ducking.
mediaPlayer.setVolume(0.2f, 0.2f);
break;
case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) :
pause();
break;
case (AudioManager.AUDIOFOCUS_LOSS) :
stop();
ComponentName component =new ComponentName(AudioPlayerActivity.this,MediaControlReceiver.class);
am.unregisterMediaButtonEventReceiver(component);
break;
case (AudioManager.AUDIOFOCUS_GAIN) :
// Return the volume to normal and resume if paused.
mediaPlayer.setVolume(1f, 1f);
mediaPlayer.start();
break;
default: break;
}
}
};

Related

Stop Device ringing through Alarm Ringtone

I am ringing my device in different activity and stopping it in different activity.
But the problem is device ringing is starting and stopping in same activity but not stopping in different activity..
The code is
Ringtone ringtone;
ringtone = RingtoneManager.getRingtone(mContext.getApplicationContext(),
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE));
AudioManager audioManager = (AudioManager) mContext.getApplicationContext().getSystemService(AUDIO_SERVICE);
int volume = audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);
audioManager.setStreamVolume(AudioManager.STREAM_ALARM, volume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
ringtone.setStreamType(AudioManager.STREAM_ALARM);
ringtone.stop(); //ringing is not stoping
Is there any other way to stop forcefully all ringing in my device..
If ringing is same in all of the Activities I suggest you to use Singleton class to access your RingtoneManager and AudioManager
public class Utilities {
// static variable of Ringtone
private static Ringtone mRingtone = null;
// static variable of AudioManager
private static AudioManager mAudioManager = null;
// static method to get instance of Ringtone
public static Rington getRingtone(Context mContext) {
if (mRingtone == null) {
mRingtone = RingtoneManager.getRingtone(mContext.getApplicationContext(),
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE));
}
return mRingtone;
}
// static method to get instance of AudioManager
public static AudioManager getAudioManager(Context mContext) {
if (mAudioManager == null) {
mAudioManager = mContext.getApplicationContext().getSystemService(AUDIO_SERVICE);
}
return mAudioManager;
}
}
Now in your Activity use something like this
Ringtone ringtone = Utilities.getRingtone(this)
AudioManager audioManager = Utilities.getAudioManager(this);
int volume = audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);
audioManager.setStreamVolume(AudioManager.STREAM_ALARM, volume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
ringtone.setStreamType(AudioManager.STREAM_ALARM);
ringtone.stop(); //this will stop ringing
I also did something similar to create a musicPlayer, as music should stop even if the user stops it from notification or somewhere else, I created a service and used Singleton instances to Play, Pause, Stop etc,.
Learn more about Singleton Classes here!
Edit 1
You code for removing Silent Mode looks fine to me, there must be something else wrong about Alarm not playing in Silent mode
This is an alternative solution for Sound in Silent Mode.
For removing silence/vibration mode I used the Alert Audio as MediaPlayer because music/media can be played even if the phone is on DND mode, I created an Emergency Alert App, which will make sound only when there is an emergency and some other Certain Action is performed.
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 20, 0);
Hope this will help!

MediaPlayer delay 0.4 seconds for Bluetooth headset

I'm developing an application with playing audio. In several cases I change the AudioStreamType to AudioManager.STREAM_RING(is mode when music is playing both: speakers and headset). When I use Bluetooth headset, I have a small annoying delay.
So i was reading that Bluetooth has a buffer and and this is logical
, but how I can solve this? Also i tried to change buffer size or delay for mediaPlayer.
So, i create a mediaPlayer like as:
#Override
public void onInit() {
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setLooping(true);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
songManager = new SongsManager(context);
}
#Override
public void onPrepare() {
// prepare media player
if (mediaPlayer != null) {
mediaPlayer.reset();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
absolutePathToPlayingSong = /*some place*/;
mediaPlayer.setDataSource(/*some place*/);
mediaPlayer.prepare();
mediaPlayer.setVolume(volumeLvl, volumeLvl);
}
AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
audio.setStreamVolume(AudioManager.STREAM_MUSIC, 20, 0);
}
then i just start player:
mediaPlayer.start();
So, i already tried:
to change a prepare() to prepareAsync() - probably it was tiny help, to may be i had a sound hallucinations. Unfortunately it broke a seekTo() in one place
added onPrepared() and start playing from listener - I not sure that it help
Give me please any advance^ how to fix delay for Bluetooth headset? I checked this device in YouTube application and it work great. So problem in my application. sorry my bad English!)
I have 2 target devices android 7.0(SDK 24) and android 4.2 (SDK 16)

How to stop Google's Media Player, if audio in app starts playing

I have to stop external media player if my app audio starts playing. In case of youtube, it stops automatically but google's media player, doesn't stops.
I have used following code.
AudioManager audioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
AudioManager.OnAudioFocusChangeListener audioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
#Override
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_LOSS:
if (TextToSpeechController.getMediaPlayerInstance().isPlaying()) { TextToSpeechController.getMediaPlayerInstance().stop();}
break;
}
};
audioManager.requestAudioFocus(audioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
But it is stopping my other audio's as well.
Any help would be appreciated.
Try this
AudioManager manager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
if(manager.isMusicActive())
{
// do something - or don't
}

Check for call interruption - Android Lollipop

I am using the following code in onPause to check the call interruption in my app
//called inside ONPAUSE i.e. whenever my app is interrupted
ActivityManager activityManager = (ActivityManager)getBaseContext().getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> runningTasks = activityManager.getRunningTasks(Integer.MAX_VALUE);
String packageLaunched = runningTasks.get(0).baseActivity.getPackageName();
// see package name of app which interrupted my app
if (!packageLaunched.contains("package.name.of.my.app")) {
// do whatever when any other app interrups, as its on top.
}
The problem is,
packageLaunched used to change when call interrupted my app on previous versions of android.
But on android Lollipop call isn't in any running task :/
How can i track an incoming call from my android app?
Register a BroadCastReciever for a Incoming call intent and do it in onRecieveIntent . Only a workaround though but will do the trick in all cases and all os versions.
This solution works on every version of android, including lollipop
Use this broadcast reciever
class TeleListener extends PhoneStateListener {
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
// CALL_STATE_IDLE;
Toast.makeText(getApplicationContext(), "CALL_STATE_IDLE",
Toast.LENGTH_LONG).show();
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
// CALL_STATE_OFFHOOK;
Toast.makeText(getApplicationContext(), "CALL_STATE_OFFHOOK",
Toast.LENGTH_LONG).show();
break;
case TelephonyManager.CALL_STATE_RINGING:
// CALL_STATE_RINGING
Toast.makeText(getApplicationContext(), incomingNumber,
Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "CALL_STATE_RINGING",
Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
}
and register it like this in onCreate
TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
TelephonyMgr.listen(new TeleListener(), PhoneStateListener.LISTEN_CALL_STATE);
And yes, please dont miss
Cheers! Your problems is solved ;)

Hardware volume buttons are not working when my app is running

I have been working on an app that plays some audio. I am currently playing the audio as a STREAM_MUSIC type of stream and this works just fine. I want to be able to control the volume with the hardware volume controls on the device. When I am in the app the hardware buttons don't do anything, the volume doesn't change and the toast doesn't pop up. I then press the home button so the app is running in the background the hardware volume buttons work. They only work when my app is running in the background.
I have tried to use the code this.setVolumeControlStream(AudioManager.STREAM_MUSIC); in my onCreate() method and this did not change the apps behavior and I am still facing the same problems.
I also have been testing this on a DROID 2, DROID RAZR, Samsung Galaxy s3, Samsung Galaxy s4, Lenovo tablet, and a rooted DROID 2 but they all behave the same.
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
setVolumeControlStream(audio.STREAM_MUSIC); //this line should set up the hardware
//buttons to control the volume
if (QtApplication.m_delegateObject != null && QtApplication.onCreate != null) {
QtApplication.invokeDelegateMethod(QtApplication.onCreate, savedInstanceState);
return;
}
requestWindowFeature(Window.FEATURE_NO_TITLE);
try {
m_activityInfo = getPackageManager().getActivityInfo(getComponentName(), PackageManager.GET_META_DATA);
} catch (NameNotFoundException e) {
e.printStackTrace();
finish();
return;
}
if (null == getLastNonConfigurationInstance()) {
// if splash screen is defined, then show it
if (m_activityInfo.metaData.containsKey("android.app.splash_screen") )
setContentView(m_activityInfo.metaData.getInt("android.app.splash_screen"));
startApp(true);
}
}
You may be tempted to try and listen for volume key presses and modify the volume of your audio stream that way. Resist the urge. Android provides the handy setVolumeControlStream() method to direct volume key presses to the audio stream you specify.
Take a look at this, I think it might be helpful:
Use Hardware Volume Keys to Control Your App’s Audio Volume
EDIT:
on your oncreate method you have to do:
this.setVolumeControlStream(AudioManager.STREAM_MUSIC); //if you use AudioManager.STREAM_MUSIC to load the sound
soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
#Override
public void onLoadComplete(SoundPool soundPool, int sampleId,
int status) {
loaded = true;
}
});
soundPool.load(this, R.raw.sound1, 1); // your sound

Categories

Resources