Ringer mode change listener Broadcast receiver?

做~自己de王妃 提交于 2019-11-26 16:05:01

问题


AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);

switch (am.getRingerMode()) {
    case AudioManager.RINGER_MODE_SILENT:
        Log.i("MyApp","Silent mode");
    break;

    case AudioManager.RINGER_MODE_VIBRATE:
        Log.i("MyApp","Vibrate mode");
    break;

    case AudioManager.RINGER_MODE_NORMAL:
        Log.i("MyApp","Normal mode");
    break;
}

From the code above I can get the ringer mode. What I would liek to do is listen the ringer mode changes and call a function.

What I have been told is that I can register the AudioManager. RINGER_MODE_CHANGED_ACTION and listen the change intent in broadcastreceiver onReceive method. It sounds clear. But I am new to android and really dont know how to write it. Is there any one can just write a piece of code and show how exactly it works instead of saying use this or that :) Thank you


回答1:


Use the following code inside the onCreate() method of your Activity or Service that you want to process the broadcast:

      BroadcastReceiver receiver=new BroadcastReceiver(){
          @Override
          public void onReceive(Context context, Intent intent) {
               //code...
          }
      };
      IntentFilter filter=new IntentFilter(
                      AudioManager.RINGER_MODE_CHANGED_ACTION);
      registerReceiver(receiver,filter);



回答2:


Another solution is to add a receiver with an action in Manifest:

<receiver android:name=".receivers.RingerModeStateChangeReceiver" >
    <intent-filter>
        <action android:name="android.media.RINGER_MODE_CHANGED" />
    </intent-filter>
</receiver>

and your class RingerModeStateChangeReceiver should extend BroadcastReceiver.




回答3:


Here's an update version in Kotlin. Place this under your onCreate() lifecycle.

this.activity?.registerReceiver(object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            if (intent.action == AudioManager.RINGER_MODE_CHANGED_ACTION) {
                // Set Player Volume
            }
        }
    }, IntentFilter(AudioManager.RINGER_MODE_CHANGED_ACTION))


来源:https://stackoverflow.com/questions/7483961/ringer-mode-change-listener-broadcast-receiver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!