我正在尝试创建一个应用程序,当通过音量键更改电话铃声音量时做出响应。我创建了一个注册 a 的服务BroadcastReceiver
,但onReceive
没有被调用。
我在这个论坛中看到了使用audioManager.registerMediaButtonEventReceiver
和使用context.registerReceiver
. 我的班级可以根据useAudioManager
. 无论哪种方式,该类都已注册,但从onReceive
未被调用。
public class VolumeKeyReceiver extends BroadcastReceiver
{
private static final boolean useAudioManager = true;
@Override
public void onReceive( Context context, Intent intent )
{
Log.d( "Monitor", "Volume key" );
}
public void register( Context context )
{
if ( useAudioManager )
{
AudioManager audioManager = (AudioManager)(context.getSystemService(Context.AUDIO_SERVICE));
ComponentName componentName = new ComponentName( context, this.getClass() );
audioManager.registerMediaButtonEventReceiver( componentName );
Log.d( "Monitor", "registered via AudioManager" );
}
else
{
IntentFilter filter = new IntentFilter( Intent.ACTION_MEDIA_BUTTON );
filter.setPriority( IntentFilter.SYSTEM_HIGH_PRIORITY );
context.registerReceiver( this, filter );
Log.d( "Monitor", "registered via Context" );
}
}
}
public class MonitorService extends Service
{
private VolumeKeyReceiver volumeKeyReceiver = null;
@Override
public void onCreate()
{
super.onCreate();
volumeKeyReceiver = new VolumeKeyReceiver();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
volumeKeyReceiver.register( this );
return START_STICKY;
}
}
<receiver android:name=".VolumeKeyReceiver">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
onDestroy()
为了简洁起见,我省略unregister()
了。
知道为什么我没有收到通知吗?我缺少任何权限吗?我正在 Galaxy S3 上测试它。