programing

Android 기기를 진동시키는 방법다른 주파수로요?

kingscode 2022. 7. 10. 19:14
반응형

Android 기기를 진동시키는 방법다른 주파수로요?

안드로이드 어플을 만들었어요.이제 어떤 동작이 일어났을 때 기기를 진동시키고 싶습니다.이거 어떻게 해?

시험:

import android.os.Vibrator;
...
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    v.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
    //deprecated in API 26 
    v.vibrate(500);
}

주의:

AndroidManifest.xml 파일에 권한을 포함하는 것을 잊지 마십시오.

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

진동 허가 부여

진동 코드 구현을 시작하기 전에 응용 프로그램에 진동 권한을 부여해야 합니다.

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

AndroidManifest.xml 파일에 이 행을 포함해야 합니다.

진동 라이브러리 가져오기

대부분의 IDE가 이 기능을 제공하지만 그렇지 않은 경우 Import 스테이트먼트는 다음과 같습니다.

 import android.os.Vibrator;

진동이 발생하는 액티비티에서는, 이것을 확인해 주세요.

일정 시간 동안 진동하는 방법

대부분의 경우 미리 정해진 짧은 시간 동안 장치를 진동시켜야 합니다.를 실현하려면 , 「 」를 합니다.vibrate(long milliseconds)를 제시하겠습니다.하다

// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

// Vibrate for 400 milliseconds
v.vibrate(400);

그거야, 간단해!

무한 진동 방법

디바이스가 무한히 진동을 계속하고 싶은 경우가 있습니다.경우, 「」를 합니다.vibrate(long[] pattern, int repeat)★★★★

// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

// Start without a delay
// Vibrate for 100 milliseconds
// Sleep for 1000 milliseconds
long[] pattern = {0, 100, 1000};

// The '0' here means to repeat indefinitely
// '0' is actually the index at which the pattern keeps repeating from (the start)
// To repeat the pattern from any other point, you could increase the index, e.g. '1'
v.vibrate(pattern, 0);

되면 하세요.cancel()★★★★

v.cancel();

진동 패턴 사용법

보다 맞춤형 진동을 원하는 경우 고유한 진동 패턴을 만들어 볼 수 있습니다.

// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

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

// The '-1' here means to vibrate once, as '-1' is out of bounds in the pattern array
v.vibrate(pattern, -1);

보다 복잡한 진동

보다 포괄적인 햅틱 피드백을 제공하는 여러 SDK가 있습니다.내가 특수효과에 사용하는 것 중 하나는 Android용 Immession의 Haptic Development Platform이다.

트러블 슈팅

장치가 진동하지 않으면 먼저 진동할 수 있는지 확인하십시오.

// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

// Output yes if can vibrate, no otherwise
if (v.hasVibrator()) {
    Log.v("Can Vibrate", "YES");
} else {
    Log.v("Can Vibrate", "NO");
}

둘째, 앱에 진동 허가를 내주세요!첫 번째 포인트로 돌아갑니다.

업데이트 2017 진동(interval) 방식은 Android-O(API 8.0)에서 더 이상 사용되지 않습니다.

모든 Android 버전을 지원하려면 이 방법을 사용합니다.

// Vibrate for 150 milliseconds
private void shakeItBaby() {
    if (Build.VERSION.SDK_INT >= 26) {
        ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(150, VibrationEffect.DEFAULT_AMPLITUDE));
    } else {
        ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(150);
    }
}

코틀린:

// Vibrate for 150 milliseconds
private fun shakeItBaby(context: Context) {
    if (Build.VERSION.SDK_INT >= 26) {
        (context.getSystemService(VIBRATOR_SERVICE) as Vibrator).vibrate(VibrationEffect.createOneShot(150, VibrationEffect.DEFAULT_AMPLITUDE))
    } else {
        (context.getSystemService(VIBRATOR_SERVICE) as Vibrator).vibrate(150)
    }
}

위의 답변은 완벽합니다.단, 버튼 클릭으로 앱을 정확히 두 번 진동시키고 싶었기 때문에, 이 작은 정보가 여기에 없기 때문에, 장래의 독자에게 투고할 수 있습니다. :)

우리는 위와 같이 따라야 하며 아래와 같이 진동 패턴의 변화만 있을 것입니다.

long[] pattern = {0, 100, 1000, 300};
v.vibrate(pattern, -1); //-1 is important

이것은 정확히 두 번 진동할 것이다.이미 알고 있듯이

  1. 0은 지연에 대한 값입니다.
  2. 100은 처음으로 100ms 동안 진동이라고 말한다.
  3. 다음으로 1000ms의 지연이 발생합니다.
  4. 300ms 동안 다시 진동하는 을 올린다.

지연과 진동을 번갈아 언급할 수 있지만(예: 3회 진동에 대해 0, 100, 1000, 300 등) @Dave의 말은 책임감 있게 사용합니다.:)

또한 반복 매개변수가 -1로 설정되어 있다는 점도 유의하십시오. 이는 패턴에 언급된 대로 진동이 발생함을 의미합니다.:)

허가 없이 진동하다

사용자 작업에 대한 피드백을 제공하기 위해 장치를 한 번 진동시키려면 다음과 같이 하십시오.하시면 됩니다.performHapticFeedback() View. 은 「 」가 VIBRATE★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

프로젝트의 Utils.kt와 같은 일반적인 클래스에서는 다음 함수를 최상위 함수로 사용합니다.

/**
 * Vibrates the device. Used for providing feedback when the user performs an action.
 */
fun vibrate(view: View) {
    view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
}

그런 다음, 데이터 센터 내 어디에서나 사용할 수 있습니다.Fragment ★★★★★★★★★★★★★★★★★」Activity음음음같 뭇매하다

vibrate(requireView())

그렇게 간단해!

첫 번째 구현에서 이 작업을 수행하는 방법을 이해하는 데 어려움을 겪었습니다. 다음 사항을 확인하십시오.

1) 장치가 진동을 지원합니다(삼성 태블릿이 작동하지 않아 코드를 계속 확인했습니다. 원래 코드는 CM 터치패드에서 완벽하게 작동했습니다).

2) AndroidManifest.xml 파일의 어플리케이션레벨을 상회하여 코드 실행을 허가하고 있습니다.

3) 다른 Import와 함께 MainActivity.java로 Import Android.content를 모두 Import합니다.컨텍스트: Android.os를 Import합니다.진동자

4)(광범위하게 이 스레드에서 이미 논의되)-나는 기능에서 하다가가 코드에서 다른 지점에서-로 XML(Clickab에 정의된 이미지를(안드로이드:단추 -&gt에 긴 클릭;작업을 수행하)또는 단추를 경청하는 사람, 또는 클릭할 수 있는 개체가 필요하는 진동을 부르는 데 사용할에 따라 이 호출하여 진동합니다.르 이미지 - Android):

 public void vibrate(int duration)
 {
    Vibrator vibs = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    vibs.vibrate(duration);    
 }

Kotlin 업데이트로 안전성이 향상되었습니다.

Utils.kt와 같은 프로젝트의 공통 클래스에서 최상위 함수로 사용합니다.

// Vibrates the device for 100 milliseconds.
fun vibrateDevice(context: Context) {
    val vibrator = getSystemService(context, Vibrator::class.java)
    vibrator?.let {
        if (Build.VERSION.SDK_INT >= 26) {
            it.vibrate(VibrationEffect.createOneShot(100, VibrationEffect.DEFAULT_AMPLITUDE))
        } else {
            @Suppress("DEPRECATION")
            it.vibrate(100)
        }
    }
}

그리고 코드의 아무 곳이나 다음과 같이 호출합니다.

vibrateDevice(requireContext())

설명.

「」를 사용합니다.Vibrator::class.java하는 것보다 입니다.String상수를 지정합니다.

.vibrator로 하려면 , 「」를 사용합니다.let { }할 수 없는 '진동'이 발생하기 때문입니다vibrator될 것이다null.

에서 격퇴를 억제하는 것은 괜찮다.else이 경고는 최신 SDK에서 가져온 것이므로 절을 참조하십시오.

진동 사용에 대해서는 런타임에 허락을 받을 필요가 없습니다.하지만 우리는 그것을 신고할 필요가 있다.AndroidManifest.xml다음과 같습니다.

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

패턴/파동 진동:

import android.os.Vibrator;
...
// Pause for 500ms, vibrate for 500ms, then start again
private static final long[] VIBRATE_PATTERN = { 500, 500 };

mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    // API 26 and above
    mVibrator.vibrate(VibrationEffect.createWaveform(VIBRATE_PATTERN, 0));
} else {
    // Below API 26
    mVibrator.vibrate(VIBRATE_PATTERN, 0);
}

플러스

에서 필요한 허가AndroidManifest.xml:

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

안에 넣어야 한다<manifest>꼬리표와 바깥쪽<application>태그를 붙입니다.

다음 유틸리티 방법을 사용합니다.

public static final void vibratePhone(Context context, short vibrateMilliSeconds) {
    Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
    vibrator.vibrate(vibrateMilliSeconds);
}

AndroidManifest 파일에 다음 사용 권한 추가

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

위와 같이 다른 유형의 진동(패턴/무한)을 사용하려는 경우 오버로드된 메서드를 사용할 수 있습니다.

위의 답변은 매우 정확합니다만, 저는 그것을 하기 위한 간단한 단계를 제공하고 있습니다.

 private static final long[] THREE_CYCLES = new long[] { 100, 1000, 1000,  1000, 1000, 1000 };

  public void longVibrate(View v) 
  {
     vibrateMulti(THREE_CYCLES);
  }

  private void vibrateMulti(long[] cycles) {
      NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
      Notification notification = new Notification();

      notification.vibrate = cycles; 
      notificationManager.notify(0, notification);
  }

그리고 xml 파일에 다음과 같이 입력합니다.

<button android:layout_height="wrap_content" 
        android:layout_width ="wrap_content" 
        android:onclick      ="longVibrate" 
        android:text         ="VibrateThrice">
</button>

그게 가장 쉬운 방법이야.

사용방법:

import android.os.Vibrator;
     ...
     Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
     // Vibrate for 1000 milliseconds
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            v.vibrate(VibrationEffect.createOneShot(1000,VibrationEffect.DEFAULT_AMPLITUDE));
     }else{
     //deprecated in API 26 
            v.vibrate(1000);
     }

주의:

AndroidManifest.xml 파일에 권한을 포함하는 것을 잊지 마십시오.

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

장치 및 장치의 작동을 진동시킬 수 있습니다.

   Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
           v.vibrate(100);

사용 권한이 필요하지만 런타임 사용 권한은 필요하지 않습니다.

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

언급URL : https://stackoverflow.com/questions/13950338/how-to-make-an-android-device-vibrate-with-different-frequency

반응형