Stop Device ringing through Alarm Ringtone - java

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!

Related

Pause other media apps

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;
}
}
};

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)

Android Nougat Media Player how put music Animation in Lock Screen?

I am using the original Music player in android Nougat, while the music is playing in the Lock Screen Appear an animation in the Buttom like this screenshot.
But when i using my own App Media Player in the same Android Nougat and Same device in the Lock Screen dont appear that animation.
The question is: How can i Add that animation in my Media Player App? it´s not a gif image because The animation moves to the rhythm of the music.
**This is my Notification Method ** if i am missing something or if i have to add something else.
ublic void Custom_Notificacion(){
Notification notification = new Notification(R.drawable.logobubble, null, System.currentTimeMillis());
notificationView = new RemoteViews(getPackageName(), R.layout.layout_notificacion_personalizada);
notificationView.setImageViewBitmap(R.id.id_FotoAlbumNotif,FotoNotif);
notificationView.setTextViewText(R.id.id_NombreMp3Notif,NommbreArtista);
notificationView.setTextViewText(R.id.id_NombreCancionNotif,NombreCancion);
notification.contentView = notificationView;
notification.flags |= Notification.FLAG_NO_CLEAR;
startForeground(constantes.NOTIFICATION_ID.FOREGROUND_SERVICE,notification);
}
I've read an article about this,an feasible solution is custom a lock screen page and display the Animation view within it,to achieve this you need a Service listening to the LOCK_SCREEN Broadcast,and start your LockScreenActivity ;replace the system lock screen at the same time.
here is some code segment might be helpful:
Register Broadcast Receiver
IntentFilter mScreenOffFilter = new IntentFilter();
mScreenOffFilter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(mScreenOffReceiver, mScreenOffFilter);
  // on receive method
private BroadcastReceiver mScreenOffReceiver = new BroadcastReceiver() {
#SuppressWarnings("deprecation")
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(NOTIFY_SCREEN_OFF)) {
Intent mLockIntent = new Intent(context, LockScreenActivity.class);
mLockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivity(mLockIntent);
}
}
Disable the Lock screen
KeyguardManager mKeyguardManager = (KeyguardManager)getSystemService(Context.KEYGUARD_SERVICE);
KeyguardManager.KeyguardLock mKeyguardLock = mKeyguardManager.newKeyguardLock("CustomLockScreen");
mKeyguardLock.disableKeyguard();
Hope this could be a little help

how to pause and play music player

I want to write a program which can pause and play every media players in android. How can i set priority of this program higher than the others? also i wrote the following code
public static final String SERVICECMD = "com.android.music.musicservicecommand";
public static final String CMDNAME = "command";
public static final String CMDPAUSE = "pause";
public static final String CMDPLAY = "play";
public static final String CMDTOGGLEPAUSE = "togglepause";
AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
if (mAudioManager.isMusicActive()) {
Intent i = new Intent(SERVICECMD);
i.putExtra(CMDNAME, CMDPAUSE);
MainActivity.this.sendBroadcast(i);
Toast.makeText(this, "media player is pause!", Toast.LENGTH_LONG).show();
}
if (!mAudioManager.isMusicActive()) {
Intent i = new Intent(SERVICECMD);
i.putExtra(CMDNAME, CMDPLAY);
MainActivity.this.sendBroadcast(i);
Toast.makeText(this, "media player is play!", Toast.LENGTH_LONG).show();
}
and it can pause every players but i dont know how to play them again. I can play some players but not all of them i dont know why ???
Have an onClick for a play and pause button
You'll have to find a way to retrieve all of the MediaPlayer Objects.
Pausing:
mMediaPlayer.pause(); // Pause the MediaPlayer
Playing:
mMediaPlayer.prepare(); // Prepares the MediaPlayer to play a song
** Please have an onPrepare method as well
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start(); // play!
}
Also, here's a reference for you:
https://github.com/naman14/Timber
This open source music app should have most of the relevant resources you need to creating a music player controller or etc. You'll be able to understand how it works.
Also, the code you've presented won't allow me to help you with identifying any issues unless you have not implemented the MediaPlayer Object.
Here's why: Difference between Audiomanager and MediaPlayer
-- EDIT --
Here's how you can stop other MediaPlayer instances via the MediaPlayerRegistry.
Android: How to stop other active media players?

Can a Broadcast Receiver receive a Mobile Data CONNECTIVITY_CHANGE notification while WiFi is enabled?

For the many threads, blogs, examples and tutorials on the topic of Broadcast Receivers and mobile data connectivity i have not seen this question asked or answered.
I believe, based on experimenting with one of my Apps, that the answer to this question is a distinct NO, that while WiFi is enabled, a Broadcast Receiver listening for Mobile Data CONNECTIVITY_CHANGE does not receive a broadcast notification when that event occurs. If i am wrong and have missed something please let me know.
My App is a home screen Widget with two classes, ActiveMobileData is the AppWidgetProvider and ConnectivityChangeReceiver is the BroadcastReceiver. The AppWidgetProvider class is my first App which i put together earlier this year mainly from code widely available in a book, on StackOverflow and on various blogs etc. There is no App just the home screen widget. It simply toggles a home screen icon between red and green to indicate the current mobile data state. It has worked perfectly for several months with about 100 users.
I decided to add the BroadcastReceiver to pick up clicks from Settings. This code is also straight forward - it determines the current state of mobile data, and uses a global boolean variable set by AppWidgetProvider to determine if the home screen icon is red or green. Then it simply ensures that the icon color matches the mobile data state.
It all works except when WiFi is enabled it does not get a notification. If there is a way around this limitation i would appreciate hearing about it.
Following is the code for the widget and then for the receiver. I left out some details to keep it somewhat brief. iconEnabled is the shared global boolean variable ...
public class ActiveMobileData extends AppWidgetProvider {
static boolean iconEnabled;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() != null)
super.onReceive(context, intent);
else {
context.startService(new Intent(context, ToggleService.class));
}
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[]appWidgetIds) {
context.startService(new Intent(context, ToggleService.class));
}
public static class ToggleService extends IntentService {
public ToggleService() {
super("ActiveMobileData$ToggleService");
}
#Override
protected void onHandleIntent(Intent intent) {
ComponentName cn = new ComponentName(this, ActiveMobileData.class);
AppWidgetManager mgr = AppWidgetManager.getInstance(this);
mgr.updateAppWidget(cn, buildUpdate(this));
}
private RemoteViews buildUpdate(Context context) {
RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.widget);
if (!isMobileDataEnabled(getApplicationContext())) {
updateViews.setImageViewResource(R.id.mobileDataState, R.mipmap.ic_launcher_g);
enableMobileData(getApplicationContext(), true);
iconEnabled = true;
} else {
updateViews.setImageViewResource(R.id.mobileDataState, R.mipmap.ic_launcher_r);
enableMobileData(getApplicationContext(), false);
iconEnabled = false;
}
Intent i = new Intent(this, ActiveMobileData.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
updateViews.setOnClickPendingIntent(R.id.mobileDataState, pi);
return updateViews;
}
public boolean isMobileDataEnabled(Context context) {
// ... the code here is the one that uses Java reflection
}
private void enableMobileData(Context context, boolean enabled) {
// ... the code here is the one that uses Java reflection
}
} // public static class ToggleService
} // public class ActiveMobileData
Following is the code for the BroadcastReceiver ...
public class ConnectivityChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive (Context context, Intent intent) {
handleIntent(context);
}
protected void handleIntent(Context context) {
ComponentName cn = new ComponentName(context, ActiveMobileData.class);
AppWidgetManager mgr = AppWidgetManager.getInstance(context);
mgr.updateAppWidget(cn, buildUpdate(context));
}
private RemoteViews buildUpdate(Context context) {
RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.widget);
if (!ActiveMobileData.iconEnabled && isMobileDataEnabled(context)) {
ActiveMobileData.iconEnabled = true;
updateViews.setImageViewResource(R.id.mobileDataState, R.mipmap.ic_launcher_g);
Intent i = new Intent(context, ActiveMobileData.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
updateViews.setOnClickPendingIntent(R.id.mobileDataState, pi);
} else
if (ActiveMobileData.iconEnabled && !isMobileDataEnabled(context)) {
ActiveMobileData.iconEnabled = false;
updateViews.setImageViewResource(R.id.mobileDataState, R.mipmap.ic_launcher_r);
Intent i = new Intent(context, ActiveMobileData.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
updateViews.setOnClickPendingIntent(R.id.mobileDataState, pi);
}
return updateViews;
}
private boolean isMobileDataEnabled(Context context) {
// ... Identical code to that in the AppWidgetProvider
}
} // class ConnectivityChangeReceiver
I don't know offhand, but I can point you to the 2 best places to look.
Best bet would be to look in detail into the JavaDoc for ConnectivityManager.html#CONNECTIVITY_ACTION and then the source code for the ConnectivityManager that is online on GrepCode
In particular comments within the source code often have very informative information that doesn't exist elsewhere.
Update:
After reading the javadoc for CONNECTIVITY_ACTION again, I believe that you are correct because it say A change in network connectivity has occurred. A default connection has either been established or lost. NOTE: Default Conn. NOT 'A Conn.' So it only gets launched when the 'default' changes. So if you lose 3g/4g/etc while on WIFI then I don't think this gets launched.
However there 'is' something you 'can' do... (but only when your widget is running) (I'm actually not 100% sure a 'widget' CAN do this... b/c I generally work with teaching services/AIDL/ContentProviders/etc (aka. 'backend' stuff within the platform) But you can put a 'refresh' button on your widget that can query to GET ALL NETWORKS and then parse through all that data and display which networks 'are' active, etc.
Also there is the option. You could make pending intents for your broadcast receiver(s) (I'd recommend just 1 BR and have different payloads so you can sort them for what is being notified) then register each of those pending intents as a call back with the ConnectivityManager to notify it whenever a 'network' that 'matches' the NetworkRequest exists. This will notify you at least when they 'come alive'...
(this next idea would likely require you to make a service with a separate thread to prevent ANR)
now when they 'die'... you 'could' setup a TCP connection and see when it dies... (not 'good' but might be only 'viable' option) (and if you are are 'generous' with trying to not wake up the phone, the battery impact could be minimal)

Categories

Resources