1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.messaging.util;
18 
19 import android.content.Context;
20 import android.content.pm.PackageInfo;
21 import android.content.pm.PackageManager.NameNotFoundException;
22 
23 import java.util.Locale;
24 
25 public final class VersionUtil {
26     private static final Object sLock = new Object();
27     private static VersionUtil sInstance;
28     private final String mSimpleVersionName;
29     private final int mVersionCode;
30 
getInstance(final Context context)31     public static VersionUtil getInstance(final Context context) {
32         synchronized (sLock) {
33             if (sInstance == null) {
34                 sInstance = new VersionUtil(context);
35             }
36         }
37         return sInstance;
38     }
39 
VersionUtil(final Context context)40     private VersionUtil(final Context context) {
41         int versionCode;
42         try {
43             PackageInfo pi = context.getPackageManager().getPackageInfo(
44                     context.getPackageName(), 0);
45             versionCode = pi.versionCode;
46         } catch (final NameNotFoundException exception) {
47             Assert.fail("couldn't get package info " + exception);
48             versionCode = -1;
49         }
50         mVersionCode = versionCode;
51         final int majorBuildNumber = versionCode / 1000;
52         // Use US locale to format version number so that other language characters don't
53         // show up in version string.
54         mSimpleVersionName = String.format(Locale.US, "%d.%d.%03d",
55                 majorBuildNumber / 10000,
56                 (majorBuildNumber / 1000) % 10,
57                 majorBuildNumber % 1000);
58     }
59 
getVersionCode()60     public int getVersionCode() {
61         return mVersionCode;
62     }
63 
getSimpleName()64     public String getSimpleName() {
65         return mSimpleVersionName;
66     }
67 }
68