2016-04-27 57 views

回答

0

你可以在你的服務中創建一個方法來獲取任何SystemProperty,並且該方法應該調用Looper.loop();使該循環將用於SystemProperty時間輪詢時間 此實現可能不是最優的這樣的方式,但它採用的是Android 4.4.2使用,你可以在這裏看到http://androidxref.com/4.4.2_r2/xref/frameworks/base/services/java/com/android/server/SystemServer.java 你可以在上面的鏈接見:

boolean disableStorage = SystemProperties.getBoolean("config.disable_storage", false); 
    boolean disableMedia = SystemProperties.getBoolean("config.disable_media", false); 
    boolean disableBluetooth = SystemProperties.getBoolean("config.disable_bluetooth", false); 
    boolean disableTelephony = SystemProperties.getBoolean("config.disable_telephony", false); 
    boolean disableLocation = SystemProperties.getBoolean("config.disable_location", false); 
    boolean disableSystemUI = SystemProperties.getBoolean("config.disable_systemui", false); 
    boolean disableNonCoreServices = SystemProperties.getBoolean("config.disable_noncore", false); 
    boolean disableNetwork = SystemProperties.getBoolean("config.disable_network", false); 

在Looper.loop()的幫助下,在initAndLoop()方法中檢查這些布爾變量;在這裏你可以通知你的其他組件,即使在一個單一的SystemProperty的任何變化。

另一種方法是創建靜態回調並獲得呼籲在任何SystemProperty的任何變化,看到主分支的代碼SystemService這裏:https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/os/SystemService.java

你可以看到在上面的鏈接下面的代碼是什麼做的:

private static Object sPropertyLock = new Object(); 

static { 
    SystemProperties.addChangeCallback(new Runnable() { 
     @Override 
     public void run() { 
      synchronized (sPropertyLock) { 
       sPropertyLock.notifyAll(); 
      } 
     } 
    }); 
} 

/** 
* Wait until given service has entered specific state. 
*/ 
public static void waitForState(String service, State state, long timeoutMillis) 
     throws TimeoutException { 
    final long endMillis = SystemClock.elapsedRealtime() + timeoutMillis; 
    while (true) { 
     synchronized (sPropertyLock) { 
      final State currentState = getState(service); 
      if (state.equals(currentState)) { 
       return; 
      } 

      if (SystemClock.elapsedRealtime() >= endMillis) { 
       throw new TimeoutException("Service " + service + " currently " + currentState 
         + "; waited " + timeoutMillis + "ms for " + state); 
      } 

      try { 
       sPropertyLock.wait(timeoutMillis); 
      } catch (InterruptedException e) { 
      } 
     } 
    } 
} 

/** 
* Wait until any of given services enters {@link State#STOPPED}. 
*/ 
public static void waitForAnyStopped(String... services) { 
    while (true) { 
     synchronized (sPropertyLock) { 
      for (String service : services) { 
       if (State.STOPPED.equals(getState(service))) { 
        return; 
       } 
      } 

      try { 
       sPropertyLock.wait(); 
      } catch (InterruptedException e) { 
      } 
     } 
    } 
} 

此信息來自Shridutt Kothari。檢查this谷歌發佈有關收聽單個SystemProperty更改

相關問題