我正在寻找一种方法,让我的程序在屏幕因超时关闭后使手机振动。我做了很多研究,但没有找到有效的方法。我研究了 PowerManager 类,更具体地说是 WakeLock 机制。从许多帖子的声音来看,我需要使用 WakeLock 类的 PARTIAL_WAKE_LOCK 变量。
PARTIAL_WAKE_LOCK - 确保 CPU 正在运行的唤醒锁。
但是,当屏幕关闭时,我无法让它振动手机。我知道我正确使用了 WakeLock,因为我可以让 SCREEN_DIM_WAKE_LOCK 正常工作。 PARTIAL_WAKE_LOCK 是我正在寻找的吗?
@Override
public void onCreate() {
super.onCreate();
// REGISTER RECEIVER THAT HANDLES SCREEN ON AND SCREEN OFF LOGIC
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
}
@Override
public void onStart(Intent intent, int startId) {
boolean screenOn = intent.getBooleanExtra("screen_state", false);
if (!screenOn) {
// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// This example will cause the phone to vibrate "SOS" in Morse Code
// In Morse Code, "s" = "dot-dot-dot", "o" = "dash-dash-dash"
// There are pauses to separate dots/dashes, letters, and words
// The following numbers represent millisecond lengths
int dot = 200; // Length of a Morse Code "dot" in milliseconds
int dash = 500; // Length of a Morse Code "dash" in milliseconds
int short_gap = 200; // Length of Gap Between dots/dashes
int medium_gap = 500; // Length of Gap Between Letters
int long_gap = 1000; // Length of Gap Between Words
long[] pattern = {
0, // Start immediately
dot, short_gap, dot, short_gap, dot, // s
medium_gap,
dash, short_gap, dash, short_gap, dash, // o
medium_gap,
dot, short_gap, dot, short_gap, dot, // s
long_gap
};
// Only perform this pattern one time (-1 means "do not repeat")
v.vibrate(pattern, -1);
} else {
// YOUR CODE
}
}
注意,您必须将使用权限行添加到块之外的 Manifest.xml 文件中。
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="...">
<uses-permission android:name="android.permission.VIBRATE"/>
注意:您还必须在真机上测试此代码,模拟器无法振动
对我来说,解决方案是直接使用无模式振动,这样我就不必使用 PowerManager 来唤醒锁定。
long vibrationDuration = 10000L; // 10 second or 10000 milliseconds
int vibrationAmplitude = 200; // between 1 and 255
Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
VibrationEffect vibe = VibrationEffect.createOneShot(vibrationDuration, vibrationAmplitude);
// for API level 33 or higher
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
vibrator.vibrate(vibe, VibrationAttributes.createForUsage(VibrationAttributes.USAGE_MEDIA));
else
vibrator.vibrate(vibe, new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).build());