5858import java .io .FileDescriptor ;
5959import java .io .IOException ;
6060import java .io .PrintWriter ;
61+ import java .nio .ByteBuffer ;
62+ import java .nio .CharBuffer ;
63+ import java .nio .charset .CharsetDecoder ;
64+ import java .nio .charset .CodingErrorAction ;
65+ import java .nio .charset .StandardCharsets ;
6166import java .util .List ;
6267
6368/**
@@ -897,7 +902,10 @@ public void enforceCallingPermission() {
897902 }
898903
899904 final class WakeupReasonThread extends Thread {
900- final String [] mReason = new String [1 ];
905+ private static final int MAX_REASON_SIZE = 512 ;
906+ private CharsetDecoder mDecoder ;
907+ private ByteBuffer mUtf8Buffer ;
908+ private CharBuffer mUtf16Buffer ;
901909
902910 WakeupReasonThread () {
903911 super ("BatteryStats_wakeupReason" );
@@ -906,25 +914,53 @@ final class WakeupReasonThread extends Thread {
906914 public void run () {
907915 Process .setThreadPriority (Process .THREAD_PRIORITY_FOREGROUND );
908916
917+ mDecoder = StandardCharsets .UTF_8
918+ .newDecoder ()
919+ .onMalformedInput (CodingErrorAction .REPLACE )
920+ .onUnmappableCharacter (CodingErrorAction .REPLACE )
921+ .replaceWith ("?" );
922+
923+ mUtf8Buffer = ByteBuffer .allocateDirect (MAX_REASON_SIZE );
924+ mUtf16Buffer = CharBuffer .allocate (MAX_REASON_SIZE );
925+
909926 try {
910- int num ;
911- while ((num = nativeWaitWakeup ( mReason )) >= 0 ) {
927+ String reason ;
928+ while ((reason = waitWakeup ( )) != null ) {
912929 synchronized (mStats ) {
913- // num will be either 0 or 1.
914- if (num > 0 ) {
915- mStats .noteWakeupReasonLocked (mReason [0 ]);
916- } else {
917- mStats .noteWakeupReasonLocked ("unknown" );
918- }
930+ mStats .noteWakeupReasonLocked (reason );
919931 }
920932 }
921933 } catch (RuntimeException e ) {
922934 Slog .e (TAG , "Failure reading wakeup reasons" , e );
923935 }
924936 }
937+
938+ private String waitWakeup () {
939+ mUtf8Buffer .clear ();
940+ mUtf16Buffer .clear ();
941+ mDecoder .reset ();
942+
943+ int bytesWritten = nativeWaitWakeup (mUtf8Buffer );
944+ if (bytesWritten < 0 ) {
945+ return null ;
946+ } else if (bytesWritten == 0 ) {
947+ return "unknown" ;
948+ }
949+
950+ // Set the buffer's limit to the number of bytes written.
951+ mUtf8Buffer .limit (bytesWritten );
952+
953+ // Decode the buffer from UTF-8 to UTF-16.
954+ // Unmappable characters will be replaced.
955+ mDecoder .decode (mUtf8Buffer , mUtf16Buffer , true );
956+ mUtf16Buffer .flip ();
957+
958+ // Create a String from the UTF-16 buffer.
959+ return mUtf16Buffer .toString ();
960+ }
925961 }
926962
927- private static native int nativeWaitWakeup (String [] outReason );
963+ private static native int nativeWaitWakeup (ByteBuffer outBuffer );
928964
929965 private void dumpHelp (PrintWriter pw ) {
930966 pw .println ("Battery stats (batterystats) dump options:" );
0 commit comments