客户需求是在手动按power键灭屏的时候增加一下震动;
通过搜索发现单击power键通过一系列的筛选后(例如组合键,截屏键等事件的拦截),会走到PowerManagerService的goToSleep方法里面:
framework/base/services/core/java/com/android/server/power/PowerManagerService.java
diff --git a/base/services/core/java/com/android/server/power/PowerManagerService.java b/base/services/core/java/com/android/server/power/PowerManagerService.java
old mode 100644
new mode 100755
index a33ed36..6f8fc58
--- a/base/services/core/java/com/android/server/power/PowerManagerService.java
+++ b/base/services/core/java/com/android/server/power/PowerManagerService.java
@@ -45,6 +45,7 @@ import android.hardware.display.AmbientDisplayConfiguration;
import android.hardware.display.DisplayManagerInternal;
import android.hardware.display.DisplayManagerInternal.DisplayPowerRequest;
import android.hardware.power.V1_0.PowerHint;
+import android.media.AudioAttributes;
import android.net.Uri;
import android.os.BatteryManager;
import android.os.BatteryManagerInternal;
@@ -67,9 +68,11 @@ import android.os.ResultReceiver;
import android.os.ShellCallback;
import android.os.SystemClock;
import android.os.SystemProperties;
+import android.os.SystemVibrator;
import android.os.Trace;
import android.os.UserHandle;
import android.os.UserManager;
+import android.os.Vibrator;
import android.os.WorkSource;
import android.os.WorkSource.WorkChain;
import android.provider.Settings;
@@ -139,6 +142,11 @@ public final class PowerManagerService extends SystemService
private static final int MSG_CHECK_FOR_LONG_WAKELOCKS = 4;
// Message: Sent when an attentive timeout occurs to update the power state.
private static final int MSG_ATTENTIVE_TIMEOUT = 5;
+ private static final int SHUTDOWN_VIBRATE_MS = 500;
+ private static final AudioAttributes VIBRATION_ATTRIBUTES = new AudioAttributes.Builder()
+ .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
+ .setUsage(AudioAttributes.USAGE_ASSISTANCE_SONIFICATION)
+ .build();
// Dirty bit: mWakeLocks changed
private static final int DIRTY_WAKE_LOCKS = 1 << 0;
@@ -4926,6 +4934,20 @@ public final class PowerManagerService extends SystemService
final int uid = Binder.getCallingUid();
final long ident = Binder.clearCallingIdentity();
try {
+ // vibrate before shutting down
+ Vibrator vibrator = new SystemVibrator(context);
+ try {
+ vibrator.vibrate(SHUTDOWN_VIBRATE_MS, VIBRATION_ATTRIBUTES);
+ } catch (Exception e) {
+ // Failure to vibrate shouldn't interrupt shutdown. Just log it.
+ Log.w(TAG, "Failed to vibrate during shutdown.", e);
+ }
+
+ // vibrator is asynchronous so we need to wait to avoid shutting down too soon.
+ try {
+ Thread.sleep(SHUTDOWN_VIBRATE_MS);
+ } catch (InterruptedException unused) {
+ }
goToSleepInternal(eventTime, reason, flags, uid);
} finally {
Binder.restoreCallingIdentity(ident);
增加了上面的代码后发现,手动按power键时会先震动再灭屏,应该是上面的Thread.sleep导致的,这里再根据需要修改一下就好了。