繁体   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