Android导航栏音量调节
程序员文章站
2022-05-12 09:18:44
...
导航栏音量加减其实质是模拟实体按键
android系统定义了音量up和down的keyevent,如下:
./core/java/android/view/KeyEvent.java
/** Key code constant: Volume Up key.
* Adjusts the speaker volume up. */
public static final int KEYCODE_VOLUME_UP = 24;
/** Key code constant: Volume Down key.
* Adjusts the speaker volume down. */
public static final int KEYCODE_VOLUME_DOWN = 25;
事件被触发的代码如下:
./services/core/java/com/android/server/policy/PhoneWindowManager.java
int flags = AudioManager.FLAG_SHOW_UI | AudioManager.FLAG_PLAY_SOUND
| AudioManager.FLAG_FROM_KEY;
String pkgName = mContext.getOpPackageName();
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
try {
getAudioService().adjustSuggestedStreamVolume(AudioManager.ADJUST_RAISE,
AudioManager.USE_DEFAULT_STREAM_TYPE, flags, pkgName, TAG);
} catch (Exception e) {
Log.e(TAG, "Error dispatching volume up in dispatchTvAudioEvent.", e);
}
break;
case KeyEvent.KEYCODE_VOLUME_DOWN:
try {
getAudioService().adjustSuggestedStreamVolume(AudioManager.ADJUST_LOWER,
AudioManager.USE_DEFAULT_STREAM_TYPE, flags, pkgName, TAG);
} catch (Exception e) {
Log.e(TAG, "Error dispatching volume down in dispatchTvAudioEvent.", e);
}
break;
最终通过AudioService去设置音量大小
因此在导航栏创建虚拟音量键时,需要在xml中加上keyCode值,如下
<com.android.systemui.statusbar.policy.KeyButtonView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:systemui="http://schemas.android.com/apk/res-auto"
android:id="@+id/volume_up"
android:layout_width="@dimen/navigation_key_width"
android:layout_height="match_parent"
android:layout_weight="0"
systemui:keyCode="24"
android:scaleType="center"
android:contentDescription="@string/accessibility_home"
android:paddingStart="@dimen/navigation_key_padding"
android:paddingEnd="@dimen/navigation_key_padding"
/>
<com.android.systemui.statusbar.policy.KeyButtonView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:systemui="http://schemas.android.com/apk/res-auto"
android:id="@+id/volume_down"
android:layout_width="@dimen/navigation_key_width"
android:layout_height="match_parent"
android:layout_weight="0"
systemui:keyCode="25"
android:scaleType="center"
android:contentDescription="@string/accessibility_home"
android:paddingStart="@dimen/navigation_key_padding"
android:paddingEnd="@dimen/navigation_key_padding"
/>
上一篇: Trie上的后缀数组
推荐阅读
-
Android实现底部导航栏功能(选项卡)
-
Android自定义ViewPagerIndicator实现炫酷导航栏指示器(ViewPager+Fragment)
-
Android中TabLayout+ViewPager 简单实现app底部Tab导航栏
-
Android使用RadioGroup实现底部导航栏
-
Android实现底部导航栏功能(选项卡)
-
Android自定义ViewPagerIndicator实现炫酷导航栏指示器(ViewPager+Fragment)
-
ANDROID BottomNavigationBar底部导航栏的实现示例
-
Android实现顶部导航栏可点击可滑动效果(仿微信仿豆瓣网)
-
Android实现简单底部导航栏 Android仿微信滑动切换效果
-
Android 状态栏虚拟导航键透明效果的实现方法