美文网首页
android 铃声震动

android 铃声震动

作者: sunny635533 | 来源:发表于2019-02-16 15:42 被阅读1次

    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();

            }

    }

    相关文章

      网友评论

          本文标题:android 铃声震动

          本文链接:https://www.haomeiwen.com/subject/tetieqtx.html