如何知道应用程序的上次启动时间

时间:2016-08-01 14:50:15

标签: android

嗨在做了很多搜索之后,我找不到问题的答案,这似乎有些简单。

我在设备上安装了多个应用。有没有办法找到所有应用程序的最后发布日期?

2 个答案:

答案 0 :(得分:2)

您可以在应用打开时将时间和日期放在SharedPref中。 然后,下次打开应用程序时,应用程序会读取SharedPref并显示它。

这样的事情:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Calendar c = Calendar.getInstance();

    SharedPreferences sp = this.getPreferences(Context.MODE_PRIVATE);

    String lastLaunch = sp.getString("launch", "First launch!");

    SharedPreferences.Editor editor = sp.edit();
    editor.putString("launch", c.getTime().toString());
    editor.commit();
}

String lastLaunch是它最后一次启动!如果它是第一次字符串是:"首次启动!"

我希望我能帮助你一点点。)

答案 1 :(得分:0)

根据您在上述评论中的要求,我提供了一种方法,可以使用SharedPreferences在一堆应用之间分享启动时间。

首先,我们需要允许我们的应用共享本地存储,以便他们可以访问偏好数据。为此,我们在应用清单中使用sharedUserId属性。这可以是您自己的唯一字符串,并且共享空间的每个应用必须具有以下内容:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="example.com.myapp"
    android:sharedUserId="string.user.id.here">

    ...

</manifest>

其次,我们使用Application类来确定应用程序何时到达前台以及何时到达前台,以Context.CONTEXT_IGNORE_SECURITY模式写下时间戳以在我们的应用之间共享:

public class MyApp extends Application implements ActivityLifecycleCallbacks {

    private boolean appInBg;
    private int TIMEOUT = 5000;
    private Handler mHandler = new Handler();

    @Override
    public void onActivityResumed() {
        if (appInBg) {
            writeToPref();
        } else {
            mHandler.cancelCallbacksAndMessages(null);
        }
    }

    @Override
    public void onActivityPaused() {
        mHanlder.postDelayed(new Runnable() {

            @Override
            public void run() {
                appInBg = true;
            }

        }, TIMEOUT);
    }

    ...


    private void writeToPref() {
         SharedPreferences prefs = myContext.getSharedPreferences("run_prefs", Context.CONTEXT_IGNORE_SECURITY);
         prefs.edit().putInt("last_run", System.currentTimeMillis()).apply();
    }
}

在这里,我们允许5秒的缓冲时间在屏幕之间切换。在大多数情况下,这应该足够了。

最后,我们可以按如下方式阅读书面SharedPreference值:

Context context = createPackageContext("example.com.myapp", 0);
SharedPreferences pref = context.getSharedPreferences("run_prefs", Context.CONTEXT_IGNORE_SECURITY);
int lastLaunch = pref.getString("last_run", System.currentTimeMillis());
// Similarly, for other apps.

希望这能解决您的问题。

相关问题