I am trying to do this simple App that allows the phone to ring but not to play a sound when receiving notifications under Android 4 (ICS). In order to do that I set the ring/notification stream to 0 (mute). When receiving a call I set the ring volume to max (p.e. 7) and then, on Idle, I turn it back to 0 (mute).
To do that I use this simple code.
public class ReceiverClass extends BroadcastReceiver
{
@Override public void onReceive(Context context, Intent intent)
{
if ("android.intent.action.PHONE_STATE".equals(intent.getAction()))
{ String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
AudioManager amanager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
if (TelephonyManager.EXTRA_STATE_IDLE.equals(state))
{ amanager.setStreamVolume(AudioManager.STREAM_RING, 0, 0);
}
else if (TelephonyManager.EXTRA_STATE_RINGING.equals(state))
{ amanager.setStreamVolume(AudioManager.STREAM_RING, 7, 0);
}
}
}
}
The problem is that it sometime works and it sometime doesn't. I cannot find a reason. I call myself ten times and the ring sounds maybe 6. The other 4 were muted. strange??
I understand that my application could take "too long" to call setStreamVolume to 7 so maybe that is way sometimes gets on time (and sounds) and sometimes it is too late (so it doesn't sound) because the call already started with 0 volume. So, is there a way to restart the ringing sound? Could anybody help me with this? Thanks.
I must say you should try giving your Broadcast Receiver high priority. which can be done like below
<intent-filter android:priority="1000">
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
refer the link >> Highest priority
It can/may solve your problem.
来源:https://stackoverflow.com/questions/11274105/android-setstreamvolume-for-stream-ring-doesnt-always-work-while-ringing