我想在发出通知声音之前执行一些操作。经过一些谷歌搜索后,我发现OnAudioFocusChangeListener是要走的路。我创建了我的服务实现AudioManager.OnAudioFocusChangeListener但是永远不会调用onAudioFocusChange()方法。
public void onAudioFocusChange(int focusChange) {
Log.d(LOG_TAG, "Called!");
if(focusChange == AudioManager.AUDIOFOCUS_GAIN){
// Do STuff
}
}
有人可以帮助我,任何建议都表示赞赏!!
答案 0 :(得分:1)
AudioManager.OnAudioFocusChangeListener
必须在AudioManager
注册才能被正确调用。
//get the audiomanager
audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
//create the listener
audioFocusListener=new AudioManager.OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(int focusChange) {
// do your job here
if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
} else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
}
}
};
//register the listener
audioManager.requestAudioFocus(audioFocusListener,
AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
//later unregister it when you do not need it anymore
AppContext.audioManager.abandonAudioFocus(audioFocusListener);
您可以尝试使用例如Youtube应用程序,将触发此监听器。
修改强>
NotificationListenerService
的AndroidManifest.xml
<service
android:name=".NotificationListenerService"
android:label="@string/app_name"
android:enabled="true"
android:exported="true"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
NotificationListenerService.java:
public class NotificationListenerService extends android.service.notification.NotificationListenerService {
private static final String TAG = "NotificationListenerService";
public NotificationListenerService(){}
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
// do your job
}
}
要启用听众,您可以访问:
Settings > Sound & Notification > Notification Access > App > Enable
或从您的应用中调用此内容:
Intent i=new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
startActivity(i);