简体   繁体   English

如何检测应用程序是否已安装超过一天?

[英]How to detect if app has been installed for more than a day?

What is the simplest way to detect if my app has been installed for more than a day?检测我的应用程序是否已安装超过一天的最简单方法是什么? I'd like to use Kotlin.我想使用 Kotlin。

Pseudo-code:伪代码:

if(appInstalledForMoreThanADay)
{
    print("this app has been installed on this device for more than 1 day")
}

You can get the actual install time through context.getPackageManager() and grabbing the PackageInfo您可以通过context.getPackageManager()获取实际安装时间并获取PackageInfo

public long firstInstallTime

The time at which the app was first installed.首次安装应用程序的时间。 Units are as per System#currentTimeMillis()单位按照System#currentTimeMillis()

There's lastUpdateTime too if you're into that如果你喜欢,也有lastUpdateTime

As Henry mentioned, You can use shared preferences to save the date of installation, and then every time the app starts check if the current date is one day bigger than the saved date.正如亨利提到的,您可以使用共享首选项来保存安装日期,然后每次应用程序启动时检查当前日期是否比保存日期大一天。 It should look something like this:它应该是这样的:

class MainActivity : AppCompatActivity()
{
    companion object
    {
        const val INSTALLATION_DATE_KEY = "INSTALLATION_DATE_KEY"
        const val MILLIS_IN_ONE_DAY = 86_400_000L;
    }

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val sharedPref = getPreferences(Context.MODE_PRIVATE) ?: return

        val installationTime = sharedPref.getLong(INSTALLATION_DATE_KEY, -1L)

        if (installationTime == -1L) // app run for first time
        {
            with(sharedPref.edit()) {
                val time = System.currentTimeMillis()
                Log.d("MyTag", "First run. Time = $time")
                putLong(INSTALLATION_DATE_KEY, time)
                commit()
            }
        }
        else
        {
            if (System.currentTimeMillis() - MILLIS_IN_ONE_DAY >= installationTime)
            {
                Log.d("MyTag", "App installed more than one day ago")
            }
            else
            {
                Log.d("MyTag", "App installed less than one day ago")
            }
        }
    }
}

PS.附注。 It won't be "installation" time but "first-run time".它不会是“安装”时间,而是“首次运行时间”。 So when the user installs the app and runs it for the first time after 2 days it won't work.因此,当用户安装该应用程序并在 2 天后第一次运行它时,它将无法工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM