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

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

    <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)
  • 相关阅读:
    20180315 代码错题(7)
    20180315 代码错题(6)
    20180315 代码错题(5)
    20180315 代码错题(4)
    01背包问题(动态规划)
    等差素数列 暴力搜索
    小L记单词
    三角形
    小L的试卷
    小L的项链切割 (回文串)
  • 原文地址:https://www.cnblogs.com/liumin-txgt/p/13064428.html
Copyright © 2011-2022 走看看