So, I am making an app that makes use of volume keys and upon pressing them, the volume bar should not appear. I tried this, but for some reason, it didn't work. While the sound doesn't get updated (because of return true
in the onKeyUp()
event), the volume bar still appears. Have I made a mistake somewhere in the code? How can I fix this?
P.S: I also added <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
but, like I said, it still doesn't work
Java:
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.*;
public class MainActivity extends AppCompatActivity {
TextView tv;
RelativeLayout rl;
int n=1;
int nmax;
AudioManager am;
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_VOLUME_UP){
if(n<nmax) {
//am.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_SAME, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
am.adjustVolume(AudioManager.ADJUST_SAME,AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
n++;
tv.setText(""+n);
return true;
}
}else if(keyCode == KeyEvent.KEYCODE_VOLUME_DOWN){
if(n>1){
//am.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_SAME, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
am.adjustVolume(AudioManager.ADJUST_SAME,AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
n--;
tv.setText(""+n);
return true;
}
}
return super.onKeyUp(keyCode, event);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nmax = runnables.length;
am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
am.setMode(AudioManager.MODE_NORMAL);
tv = findViewById(R.id.textView);
tv.setText("1");
rl = findViewById(R.id.rl);
rl.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
runnables[n-1].run();
}
});
}
Runnable[] runnables = {null,null,null,null,null};
}
XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#6000FFFF"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textColor="#FF0000"
android:textSize="100sp" />
</RelativeLayout>