Android7.0以上使用手机系统震动功能

909 阅读1分钟

导读:

最近购买了一部新手机(是android11.0版本),新手机玩得不亦乐乎,但却意外发现自己写的APP退到后台之后无法震动,多番研究下才找到解决方法,现在贴代码出来,留个纪念。

/**
     * 手机震动
     *
     * @param context
     * @param isRepeat 是否重复震动
     */
    public static void playVibrate(Context context, boolean isRepeat) {

        /*
         * 设置震动,用一个long的数组来表示震动状态(以毫秒为单位)
         * 如果要设置先震动1秒,然后停止0.5秒,再震动2秒则可设置数组为:long[]{1000, 500, 2000}。
         * 别忘了在AndroidManifest配置文件中申请震动的权限
         */
        try {
            Vibrator mVibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
            long[] patern = new long[]{1000, 500, 2000};
            AudioAttributes audioAttributes = null;
            /**
             * 适配android7.0以上版本的震动
             * 说明:如果发现5.0或6.0版本在app退到后台之后也无法震动,那么只需要改下方的Build.VERSION_CODES.N版本号即可
             */
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                audioAttributes = new AudioAttributes.Builder()
                        .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                        .setUsage(AudioAttributes.USAGE_ALARM) //key
                        .build();
                mVibrator.vibrate(patern, isRepeat ? 1 : -1, audioAttributes);
            }else {
                mVibrator.vibrate(patern, isRepeat ? 1 : -1);
            }
        } catch (Exception ex) {
        }
    }

上面是封装好的方法,调用很简单,如下:

playVibrate(getApplicationContext(), true);