admin
2021-07-20 27bd1f81221b8c8e8047118a64c2beb7bc214bbb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.lcjian.library.util.common;
 
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.preference.PreferenceManager;
 
public class PackageUtils2 {
 
    public static boolean isFirstStartup(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            int currentVersion = info.versionCode;
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
            int lastVersion = prefs.getInt("version_code", 0);
            if (currentVersion > lastVersion) { // 如果当前版本大于上次版本,该版本属于第一次启动
                // 将当前版本写入preference中,则下次启动的时候,据此判断,不再为首次启动
                prefs.edit().putInt("version_code", currentVersion).commit();
                return true;
            } else {
                return false;
            }
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return false;
    }
 
    /**
     * 获取versionCode
     *
     * @param context
     * @return 版本号
     */
    public static int getVersionCode(Context context) {
        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return pi.versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
            return 0;
        }
    }
 
    public static String getPackageName(Context context) {
        return context.getPackageName();
    }
}