I am making an app that mutes and unmutes a device, but it is crashing when I open it. I have no idea why it is doing this and would really like some help. Here is the code:
package com.earthmonster.testmute4;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
AudioManager audioManager = (AudioManager)getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AudioManager am = (AudioManager)getSystemService(AUDIO_SERVICE);
int volume_level=am.getStreamVolume(AudioManager.STREAM_MUSIC);
if (volume_level > 0)
{
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
audioManager.setStreamVolume(AudioManager.STREAM_SYSTEM, 0, 0);
audioManager.setStreamVolume(AudioManager.STREAM_RING, 0, 0);
audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, 0, 0);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
}
else {
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 100, 0);
audioManager.setStreamVolume(AudioManager.STREAM_SYSTEM, 100, 0);
audioManager.setStreamVolume(AudioManager.STREAM_RING, 100, 0);
audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, 100, 0);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 100, 0);
}
finish();
}
}
Can someone please figure out the problem! I am an absolute beginner on this. No java experience. No android developing experience. And mostly compiled this code from various sources on the internet.
Thanks in advance.