2

I want to create an anti theft alarm, so when the android device is stolen, it should make a loudly alert. I tried this code, but it does not work.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    v.vibrate(300);

    Uri alert = RingtoneManager
            .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    MediaPlayer mMediaPlayer = new MediaPlayer();

    try {
        mMediaPlayer.setDataSource(this, alert);
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
        mMediaPlayer.setLooping(false);
        //mMediaPlayer.prepare();
        mMediaPlayer.start();
    }
}
akhil_mittal
  • 23,309
  • 7
  • 96
  • 95
Michael Frans
  • 613
  • 3
  • 23
  • 49

1 Answers1

4

I have used this to override the phone volume settings:

int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);

audioManager.setStreamVolume(AudioManager.STREAM_ALARM, maxVolume,AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE); 
Rakib Ansary
  • 4,078
  • 2
  • 18
  • 29
Marmoy
  • 8,009
  • 7
  • 46
  • 74
  • If you mean the code in Michael's original question is not working, that is because the "mMediaPlayer.prepare();" must be uncommented (at least on 4.4.4, it is required -- I tried myself). Curious that no one else pointed this out. – Steve B Dec 07 '14 at 03:08
  • This works great - but I don't want to fiddle around with the user's choice to silence his phone... what I need is JUST ONE notification to make noise, because it is an alarm that needs to be delivered. If I use this solution, the mute is off after my alarm... :( – Zordid Jun 10 '15 at 07:54
  • Just store the existing state before the change and return the phone to that state after your notification – Marmoy Jun 10 '15 at 11:51