【发布时间】:2017-06-06 11:51:44
【问题描述】:
在我的应用程序中,您需要获取设备上所有应用程序上次启动的日期和时间。我可以通过标准方式获取这些信息吗?
【问题讨论】:
-
您可以获取上次启动的应用名称但不能获取上次日期时间,您可以参考stackoverflow.com/questions/3290936/…
在我的应用程序中,您需要获取设备上所有应用程序上次启动的日期和时间。我可以通过标准方式获取这些信息吗?
【问题讨论】:
您可以通过创建一个应用程序类并从应用程序的清单文件中设置它来做到这一点。一步一步:
创建一个类扩展Application:
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
// save date to sharedpref
PreferenceManager.getDefaultSharedPreferences(this).
edit().putLong("LAST_LAUNCH_DATE_MS", new Date().getTime()).apply();
}
}
从清单文件中将其设置到您的应用中:
<application
android:name="com.my.project.MyApplication"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
.....
.....
</application>
您现在可以从SharedPreferences 获取以毫秒为单位的上次启动时间。
【讨论】:
只需节省每次启动的时间
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
long lastLaunchMillis = sharedPref.getLong("lastLaunch", 0);
if (lastLaunchMillis != 0) {
Calendar lastLaunch = Calendar.getInstance();
lastLaunch.setTimeInMillis(lastLaunchMillis);
//last launch found, handle
}
sharedPref.edit().putLong("lastLaunch", Calendar.getInstance().getTimeInMillis()).apply();
编辑:有关其他应用的启动统计信息,请查看UsageStatsManager。你可以在here找到一个使用示例。
【讨论】:
lollipop 设备。棒棒糖之前的设备呢?