前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >android 震动和提示音的实现代码

android 震动和提示音的实现代码

作者头像
砸漏
发布2020-10-16 10:49:54
1.1K0
发布2020-10-16 10:49:54
举报
文章被收录于专栏:恩蓝脚本

android的消息提示(震动和提示音),实现代码如下所示:

代码语言:javascript
复制
public class VibratorUtil {
  protected AudioManager audioManager;
  protected Vibrator vibrator;
  private Ringtone ringtone;
  private static final int MIN_TIME_OUT = 4000; //时间间隔
  long lastNotificationTime;
  public VibratorUtil() {
    audioManager = (AudioManager) MyApp.getContext().getSystemService(Context.AUDIO_SERVICE); //此方法是由Context调用的
    vibrator = (Vibrator) MyApp.getContext().getSystemService(Context.VIBRATOR_SERVICE); //同上
  }
  /**
   * 开启手机震动和播放系统提示铃声
   */
  public void vibrateAndPlayTone() {
    if (System.currentTimeMillis() - lastNotificationTime < MIN_TIME_OUT) {
      return;
    }
    try {
      lastNotificationTime = System.currentTimeMillis();
      if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT) {
        return;
      }
      long[] pattern = new long[]{0, 180, 80, 120};
      vibrator.vibrate(pattern, -1); //震动
      if (ringtone == null) {
        Uri notificationUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        ringtone = RingtoneManager.getRingtone(MyApp.getContext(), notificationUri);
        if (ringtone == null) {
          return;
        }
      }
      if (!ringtone.isPlaying()) {
        ringtone.play();
        //判断手机品牌
        String vendor = Build.MANUFACTURER;
        if (vendor != null && vendor.toLowerCase().contains("samsung")) {
          Thread ctlThread = new Thread() {
            public void run() {
              try {
                Thread.sleep(3000);
                if (ringtone.isPlaying()) {
                  ringtone.stop();
                }
              } catch (Exception e) {
              }
            }
          };
          ctlThread.run();
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

总结

以上所述是小编给大家介绍的android 震动和提示音的实现代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对ZaLou.Cn网站的支持! 如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-09-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档