programing

앱의 (레이아웃) XML 변수에서 매니페스트 버전 번호를 어떻게 얻을 수 있습니까?

new-time 2020. 5. 21. 21:47
반응형

앱의 (레이아웃) XML 변수에서 매니페스트 버전 번호를 어떻게 얻을 수 있습니까?


코드의 주요 부분에서 프로젝트의 매니페스트 버전 번호를 참조하는 방법을 원합니다. 지금까지 내가 한 일은 String XML 파일의 버전 번호를 매니페스트 (@ string / Version)에 연결하는 것입니다. 내가하고 싶은 것은 다른 방법으로 문자열 XML 변수를 매니페스트의 버전에 연결하는 것입니다. 이유? 매니페스트 파일 한 위치에서 버전 번호 만 변경하고 싶습니다. 이것을 할 수있는 방법이 있습니까? 감사!


나는 이미

여기에

대답했다고 생각합니다 .

String versionName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;

또는

int versionCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;

버전을 직접 가져 오는 방법은 없지만 두 가지 해결 방법이 있습니다.

  1. 버전은 리소스 문자열에 저장되고 다음을 통해 매니페스트에 배치 될 수 있습니다.
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
         package="com.somepackage"
         android:versionName="@string/version" android:versionCode="20">
    
  2. 사용자 정의보기를 작성하여 XML에 배치 할 수 있습니다. 뷰는 이것을 사용하여 이름을 할당합니다 :
    context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
    

이러한 솔루션 중 하나를 사용하면 버전 이름을 XML로 배치 할 수 있습니다. 불행히도 이와 같은 멋진 간단한 해결책은 없습니다

android.R.string.version

.


 

versionName

활동 레이아웃과 같은 XML 자원에서 사용할 수 있습니다 . 먼저 노드

app/build.gradle

에서 다음 코드 조각 으로 문자열 리소스를 만듭니다

android

.

applicationVariants.all { variant ->
    variant.resValue "string", "versionName", variant.versionName
}

따라서 전체

build.gradle

파일 내용은 다음과 같습니다.

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion '24.0.0 rc3'
    defaultConfig {
        applicationId 'com.example.myapplication'
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 17
        versionName '0.2.3'
        jackOptions {
            enabled true
        }
    }
    applicationVariants.all { variant ->
        variant.resValue "string", "versionName", variant.versionName
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
} 

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.android.support:design:23.3.0'
    compile 'com.android.support:support-v4:23.3.0'
}

그런 다음

@string/versionName

XML에서 사용할 수 있습니다 . Android Studio는 빨간색으로 표시하지만 앱은 문제없이 컴파일됩니다. 예를 들어 다음과 같이 사용할 수 있습니다

app/src/main/res/xml/preferences.xml

.

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <PreferenceCategory
        android:title="About"
        android:key="pref_key_about">

        <Preference
            android:key="pref_about_build"
            android:title="Build version"
            android:summary="@string/versionName" />

    </PreferenceCategory>


</PreferenceScreen>

Preference 클래스를 확장 하여이 문제를 해결했습니다.

package com.example.android;

import android.content.Context;
import android.preference.Preference;
import android.util.AttributeSet;

public class VersionPreference extends Preference {
    public VersionPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
        String versionName;
        final PackageManager packageManager = context.getPackageManager();
        if (packageManager != null) {
            try {
                PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
                versionName = packageInfo.versionName;
            } catch (PackageManager.NameNotFoundException e) {
                versionName = null;
            }
            setSummary(versionName);
        }
    }
}

그런 다음 내 환경 설정 XML에서 :

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <com.example.android.VersionPreference android:title="Version" />
</PreferenceScreen>

I use BuildConfig.VERSION_NAME.toString();. What's the difference between that and getting it from the packageManager?

No XML based solutions have worked for me, sorry.


IF you are using Gradle you can use the build.gradle file to programmatically add value to the xml resources at compile time.

Example Code extracted from: https://medium.com/@manas/manage-your-android-app-s-versioncode-versionname-with-gradle-7f9c5dcf09bf

buildTypes {
    debug {
        versionNameSuffix ".debug"
        resValue "string", "app_version", "${defaultConfig.versionName}${versionNameSuffix}"
    }
    release {
        resValue "string", "app_version", "${defaultConfig.versionName}"
    }
}

now use @string/app_version as needed in XML

It will add .debug to the version name as describe in the linked article when in debug mode.


You can't use it from the XML.

You need to extend the widget you are using in the XML and add the logic to set the text using what's mentioned on Konstantin Burov's answer.


Easiest solution is to use BuildConfig.

I use BuildConfig.VERSION_NAME in my application.

You can also use BuildConfig.VERSION_CODE to get version code.


Late to the game, but you can do it without @string/xyz by using ?android:attr

    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="?android:attr/versionName"
     />
    <!-- or -->
    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="?android:attr/versionCode"
     />

참고URL : https://stackoverflow.com/questions/4471025/how-can-you-get-the-manifest-version-number-from-the-apps-layout-xml-variable

반응형