Takeaway:

Recently, I bought a new mobile phone (android11.0 version). I had a lot of fun with my new mobile phone, but accidentally found that the APP I wrote could not vibrate after being retired to the background. After many researches, I found a solution.

/** * The phone vibrates **@param context
     * @paramIsRepeat whether to repeat the vibration */
    public static void playVibrate(Context context, boolean isRepeat) {

        /* * Set vibrate to an array of long vibrates in milliseconds * If you want to vibrate for 1 second, then stop for 0.5 seconds, then vibrate for 2 seconds, you can set the array to long[]{1000, 500, 2000}. * Don't forget to apply for vibration permission in the AndroidManifest configuration file */
        try {
            Vibrator mVibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
            long[] patern = new long[] {1000.500.2000};
            AudioAttributes audioAttributes = null;
            Note: If you find that version 5.0 or 6.0 does not vibrate even after the app is backlogged, you only need to change the build.version_codes.n version number below */
            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) {
        }
    }
Copy the code

The above is the wrapped method, the call is very simple, as follows:

playVibrate(getApplicationContext(), true);
Copy the code