android - 用铃声振动手机直到铃声停止

标签 android

在我的应用程序中,我正在播放来自服务的铃声。

protected boolean playRingtone() {      
    Uri ringtoneUri = _savedValues.loadRingtoneUri();
    _audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    _maxVolume = _audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    _oldVolume = _audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    _audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, _maxVolume,AudioManager.FLAG_SHOW_UI);




    _mp = new MediaPlayer();
     try {
         _mp.setDataSource(this, ringtoneUri);
    } catch (Exception e) {
        return false;
    }

    _mp.setVolume(_maxVolume, _maxVolume);
    _mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
    _mp.setLooping(true);
     try {
         _mp.prepare();
    } catch (Exception e) {
        return false;
    }

    _mp.start();         
     return true;
}

以及服务何时停止

public void Stop() {
    //cancel ringtone playback if it's going on
    if (_ringAloud) {
        if (_audioManager != null) {
            _audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,_oldVolume, AudioManager.FLAG_SHOW_UI);
        }
        if (_mp != null) {
            if (_mp.isPlaying()) {
                _mp.stop();
            }
            _mp.release();
        }
    }

现在,我希望它也振动直到服务停止。 但是 Vibrator 类除了 vibrate(time) 和 vibrate(pattern,repeat) 之外没有提供任何方法。 那么,有没有办法让手机振动与铃声同步。

最佳答案

您可以使用此方法启动和停止振动。

public static void onClickStartVibrate(Context c)
    {

        //Set the pattern for vibration  
        long pattern[]={0,200,100,300,400};

        //Start the vibration
        vibrator = (Vibrator)c.getSystemService(Context.VIBRATOR_SERVICE);
        //start vibration with repeated count, use -1 if you don't want to repeat the vibration
        vibrator.vibrate(pattern, 0);   

    }

停止振动

public static void onClickStopVibrate()
    {
        try{
            vibrator.cancel();
        }
        catch(NullPointerException e)
        {}
    }

关于android - 用铃声振动手机直到铃声停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18824538/

相关文章:

android - 编辑文本作为微调器

android - 安装指标的 Google Play 含义

java - Libgdx 跟随鼠标 |投影?

android - 检测应用程序是否安装?

Android:使用 Moshi 适配器解析内部非结构化 Json

android - 如何在不在支持列表中的国家/地区开发具有应用内结算功能的应用?

android - 获取 listView 中的值微调器(android)

java - 尝试在空对象引用上调用虚拟方法 '...'

java - 从主类调用 FragmentActivity (appCompatActivity)

java - "org.xmlpull.v1.XmlPullParserException: expected: START_TAG"错误