簡體   English   中英

android 設備上是否有唯一的啟動會話 ID 或計數?

[英]Is there a unique boot session id or count on an android device?

我正在編寫的應用程序需要知道“啟動會話”是否已經更改,但它不需要在啟動時實際啟動,如果可能的話,我寧願不必使用RECEIVE_BOOT_COMPLETED權限.

所以我想知道是否有任何設備范圍的引導會話 ID 或計數可以查詢並存儲在我的數據庫中以供以后檢查。 我知道我可以在啟動后以毫秒為單位獲得時間,但我認為在這種情況下這不會有用。

提前感謝您的幫助。

是的,在 API >= 24 上。您可以使用BOOT_COUNT全局設置變量 要閱讀本文,請嘗試這樣的片段:

int boot_count = Settings.Global.getInt(getContext().getContentResolver(),
                                        Settings.Global.BOOT_COUNT);

在 API 24 之前,您被困住了RECEIVE_BOOT_COMPLETED

我使用此代碼在所有版本的 Android 上獲取唯一的啟動 ID。 對於 Nougat 及更高版本,我使用Settings.Global.BOOT_COUNT 對於早於 Nougat 的版本,我從“/proc/sys/kernel/random/boot_id”讀取了一個唯一的引導 ID。 在我的測試中,我在 Android 5 上的文件訪問沒有任何問題。 在 Android 5、8、9 和 11 上使用我們應用的發布版本在真實設備上進行了測試。

這不依賴於系統時鍾,系統時鍾可以跳躍或由用戶更改。

感謝@george-hilliard 對Settings.Global.BOOT_COUNT解決方案的回答

String bootId = "";

if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ) { // Starting in Android 7 / N(ougat) / API Level 24, we have access to `Settings.Global.BOOT_COUNT`, which increments with every boot.
  bootId = Settings.Global.getString( getApplicationContext().getContentResolver(), Settings.Global.BOOT_COUNT );
}
else { // Before Android 7 / N(ougat) / API Level 24, we need to get the boot id from the /proc/sys/kernel/random/boot_id file. Example boot_id: "691aa77e-aff4-47c2-829e-a34df426c7e7".
 File bootIdFile = new File( "/proc/sys/kernel/random/boot_id" );

  if ( bootIdFile.exists() ) {
    FileInputStream inputStream = null;

    try {
      inputStream           = new FileInputStream( bootIdFile );
      BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
      bootId                = reader.readLine().trim(); // Read first line of file to get the boot id and remove any leading and trailing spaces.
    }
    catch ( FileNotFoundException error ) {
      error.printStackTrace();
    }
    catch ( IOException error ) {
      error.printStackTrace();
    }
    finally {
      if ( inputStream != null ) try { inputStream.close(); } catch (IOException error ) { error.printStackTrace();; }
    }
  }
}

if ( bootId == "" ) {
  Log.e( "UniqueTag", "Could not retrieve boot ID. Build.VERSION.SDK_INT: " + Build.VERSION.SDK_INT );
}

為什么不在數據庫中存儲上次啟動的(絕對)日期和時間? 您可以使用自啟動以來的時間輕松計算它,並且考慮到啟動時間比一毫秒長得多,它應該是相當准確的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM