android 铃声震动

2019-02-16  本文已影响1人  SunnyLYummy

private void startVibrateAndSound(Context context) {

Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);

        if (vibrator !=null) {

vibrator.vibrate(2000);

        }

boolean shouldPlaySound =true;

        Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        AudioManager audioService = (AudioManager) context

.getSystemService(Context.AUDIO_SERVICE);

        if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {

shouldPlaySound =false;

        }

//        boolean voice_switch = context.getSharedPreferences("config", Context.MODE_PRIVATE)

//                .getBoolean("voice_switch", true);

        boolean voice_switch =true;

        MediaPlayer mMediaPlayer =new MediaPlayer();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

AudioAttributes audioAttributes =new AudioAttributes.Builder()

.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)

.setLegacyStreamType(AudioManager.STREAM_NOTIFICATION)

.setUsage(AudioAttributes.USAGE_NOTIFICATION_EVENT).build();

            mMediaPlayer.setAudioAttributes(audioAttributes);

        }else {

mMediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);

        }

if (mMediaPlayer ==null)

mMediaPlayer =new MediaPlayer();

        try {

mMediaPlayer

.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

@Override

                        public void onCompletion(MediaPlayer player) {

player.seekTo(0);

                        }

});

            mMediaPlayer.setDataSource(context, uri);

            mMediaPlayer.prepare();

            if (shouldPlaySound && voice_switch && mMediaPlayer !=null)

mMediaPlayer.start();

        }catch (Exception e) {

// TODO Auto-generated catch block

            e.printStackTrace();

        }

}

上一篇 下一篇

猜你喜欢

热点阅读