我想知道如何在我的代码中实现 KEYCODE_VOLUME_UP 和 DOWN。因此,每次按下音量增大或减小键时,都会同时反映在我的通知音量控制应用程序上。
我要实现的方法如下,当按下物理音量上下按钮时,我自己的应用程序音量会上下:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
return true;
default:
return false;
}
}
我要实现的代码是:
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
run();
}
public void run()
{
mgr=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
final LayoutInflater inflater =
(LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
final View ViewLayout = inflater.inflate(R.layout.activity_main,
(ViewGroup)findViewById(R.id.activity_main));
alarm=(SeekBar)ViewLayout.findViewById(R.id.alarm);
music=(SeekBar)ViewLayout.findViewById(R.id.music);
ring=(SeekBar)ViewLayout.findViewById(R.id.ring);
system=(SeekBar)ViewLayout.findViewById(R.id.system);
voice=(SeekBar)ViewLayout.findViewById(R.id.voice);
alarmVol=(TextView)ViewLayout.findViewById(R.id.alarmVol);
musicVol=(TextView)ViewLayout.findViewById(R.id.musicVol);
ringVol=(TextView)ViewLayout.findViewById(R.id.ringVol);
systemVol=(TextView)ViewLayout.findViewById(R.id.systemVol);
voiceVol=(TextView)ViewLayout.findViewById(R.id.voiceVol);
alertDialogBuilder = new AlertDialog.Builder(this);
//alertDialogBuilder.setIcon(R.mipmap.ic_launcher);
//alertDialogBuilder.setTitle("Volume Control");
alertDialogBuilder.setView(ViewLayout);
initBar(alarm, AudioManager.STREAM_ALARM, alarmVol);
initBar(music, AudioManager.STREAM_MUSIC, musicVol);
initBar(ring, AudioManager.STREAM_RING, ringVol);
initBar(system, AudioManager.STREAM_SYSTEM, systemVol);
initBar(voice, AudioManager.STREAM_VOICE_CALL, voiceVol);
alertDialogBuilder.create();
alertDialogBuilder.show();
}
private void initBar(SeekBar bar, final int stream, final TextView textView)
{
final float maxVolume=mgr.getStreamMaxVolume(stream);
float curVol = mgr.getStreamVolume((stream));
bar.setMax((int)maxVolume);
bar.setProgress((int)curVol);
bar.setKeyProgressIncrement(1);
textView.setText(String.valueOf((int)(curVol/maxVolume*100)));
bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar bar, int progress,
boolean fromUser) {
mgr.setStreamVolume(stream, progress,
AudioManager.FLAG_PLAY_SOUND);
textView.setText(String.valueOf((int)
((progress/maxVolume)*100)));
}
public void onStartTrackingTouch(SeekBar bar) {
}
public void onStopTrackingTouch(SeekBar bar) {
}
});
}
}