zoukankan      html  css  js  c++  java
  • Android Notification 的声音和震动

    我们在Android系统发送一条Notification的时候,经常需要通过震动或声音来提醒用户。如何为Notification设置声音和震动了。大致思路有: 
    - AndroidNotification系统默认的声音和震动 
    - 为AndroidNotification设置自定义的声音和震动 
    - 自己使用Vibrator和SoundPool来产生声音和震动

    使用震动需要注意添加权限:

    <uses-permission android:name="android.permission.VIBRATE"/>

    使用系统默认的声音和震动

    1.设置Notification

    //使用默认的声音
    notif.defaults |= Notification.DEFAULT_SOUND;
    
    //使用默认的震动
    notif.defaults |= Notification.DEFAULT_VIBRATE;
    
    //使用默认的声音、振动、闪光
    notif.defaults = Notification.DEFAULT_ALL;
    

    2.设置NotificationCompat.Builder

    NotificationCompat.Builder setDefaults(int defaults)

    //使用默认的声音、振动、闪光
    new Notification.Builder(context).setDefaults(Notification.DEFAULT_ALL);
    
    //使用默认的震动和声音
    new Notification.Builder(context).setDefaults(Notification.DEFAULT_SOUND|Notification.DEFAULT_VIBRATE)

    为Notification设置自定义的声音和震动

    Vibrate

    AndroidNotification震动实际上是调用Vibrator的vibrate (long[] pattern, int repeat)这个方法,传入的参数是一个long[].

    long[]参数的介绍

    数组第一个参数表示延迟震动时间 
    第二个参数表示震动持续时间 
    第三个参数表示震动后的休眠时间 
    第四个参数又表示震动持续时间 
    第五个参数也表示正到休眠时间 
    以此类推

    // Start without a delay
    // Vibrate for 100 milliseconds
    // Sleep for 1000 milliseconds
    long[] pattern = {0, 100, 1000};
    
    // Start without a delay
    // Each element then alternates between vibrate, sleep, vibrate, sleep...
    long[] pattern1 = {0, 100, 1000, 300, 200, 100, 500, 200, 100};

    为Notification设置自定义的振动模式

    //为Notification设置
    notification.vibrate = pattern;
    
    
    //为Builder设置
    NotificationCompat.Builder.setVibrate (pattern)

    Sound

    Notification的声音参数,要求类型为Uri.关于Uri的规范,可参考 http://www.ietf.org/rfc/rfc2396.txt.

    1.获取uri

    //从raw
    Uri sound=Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notificationsound );
     or
    Uri sound=Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/raw/notificationsound");
     or
    Uri sound=Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/"+R.raw.notificationsound);
    
    //从铃声管理器
    Uri sound= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    
    //从文件
    Uri sound=Uri.fromFile(new File("/sdcard/sound.mp3"))
    Uri sound=Uri.parse(new File("/sdcard/sound.mp3").toString()));
    
    //从ContentResolver

    2.设置uri

    notification.sound =Uri sound;
    NotificationCompat.Builder.setSound(Uri sound)

    自己调用震动和声音播放

    使用震动

    http://stackoverflow.com/questions/13950338/how-to-make-an-android-device-vibrate

     播放声音

  • 相关阅读:
    浅谈线段树
    浅谈KMP
    20200729线上模拟题解
    20200727线上模拟题解
    声明
    tarjan--割点,缩点
    20201029模拟
    高精模板
    二分图--二分图的几种模型
    树的直径与树的重心
  • 原文地址:https://www.cnblogs.com/xgjblog/p/7921880.html
Copyright © 2011-2022 走看看