了解之前是否推出了应用

时间:2014-01-13 19:29:48

标签: android

我遇到了以下问题: 应用程序需要知道是否至少在一次之前启动了另一个已安装的应用程序。 我想过用第一个应用程序在sd上创建一个文件。第二个应用程序知道第一个应用程序至少启动过一次。 有没有更好的方法呢?

1 个答案:

答案 0 :(得分:0)

使用sharedpreferences:

在需要至少启动一次的第一个应用程序上:(在创建方法上)

//This will store a string with a value "yessir" when the app is launched. You can tweak it a bit by adding something like if !launched string exist skip the creation to avoid creating the string at every launch.

SharedPreferences pref = getSharedPreferences("my_prefs", Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("launched", "yessir");
editor.commit();

在第二个应用上:

        try {
            Context myContext = createPackageContext("package_name_of_the_first_app", Context.CONTEXT_IGNORE_SECURITY);
            SharedPreferences pref = myContext.getSharedPreferences(
                    "my_prefs", Context.MODE_PRIVATE);
            String isItLaunched = pref.getString("launched", "");
            if (isItLaunched.equals("yessir") {
                // The first app got launched so do something
            } else {
                // the first app was not launched so do something else 
            }          
        } catch (NameNotFoundException e) {
        }