前言:大多数的视频播放软件,上下滑动都可以实现屏幕亮度和音量大小的调节。这一功能的实现主要涉及安卓的手势检测与系统服务两个技术点,在这篇文章中主要讲解如何利用系统服务实现音量大小的调节,手势检测会在后期的文章中涉及。
第一步,界面设计
由于本文只是大致讲解音量调节大小的实现,界面就不做美化了,直接使用安卓系统控件两个Button,分别用于音量的增加与减小,代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin" >
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:onClick="audioUp"
android:text="调大" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:onClick="audioDown"
android:text="调小 />
</LinearLayout>
第二步,定义方法
从上面的界面布局代码中可以看到两个Button的点击事件分别是audioUp与audioDown,因此需要在Java代码中定义这两个方法,代码如下:
public void audioUp(View view) {
boolean bool = AudioUtil.audioUp(this);
if(bool){
toastShort(“调节成功”);
}else{
toastShort("已经是最大音量");
}
}public void audioDown(View view) {
boolean bool = AudioUtil.audioDown(this);
if(bool){
toastShort(“调节成功”);
}else{
toastShort("已经是最小音量");
}
}
第三步,实现AudioUtil,并实现相应的逻辑
AudioUtil代码如下:
import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
public class AudioUtil {
public static boolean audioUp(Activity act) {
return audioDo(1, act);
}
public static boolean audioDown(Activity act) {
return audioDo(0, act);
}
private static boolean audioDo(int flag, Activity act) {
AudioManager mAudioManager = (AudioManager) act.getSystemService(Context.AUDIO_SERVICE);
int maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
if (flag == 0) {
if (currentVolume == 0) {
return false;
}
mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, AudioManager.FX_FOCUS_NAVIGATION_UP);
return true;
} else {
if (currentVolume == maxVolume) {
return false;
}
mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FX_FOCUS_NAVIGATION_UP);
return true;
}
}
}
第四步,测试完美收工