Gradle से जुड़ी सलाह और रेसिपी

Gradle के लिए Gradle और Android प्लग इन, कंपाइल करने का आसान तरीका उपलब्ध कराते हैं, अपने Android ऐप्लिकेशन या लाइब्रेरी को बनाएं और उसे पैकेज करें. यह पेज कुछ जानकारी इकट्ठा करता है में, आपको कुछ सुझाव और कॉन्फ़िगरेशन मिलते हैं. इनसे आपको हर बिल्ड का ज़्यादा से ज़्यादा फ़ायदा पाने में मदद मिलती है. अगर आपको बिल्ड को तेज़ बनाने के तरीकों के बारे में जानना है, तो ज़्यादा जानकारी के लिए पढ़ें वीडियो बनाने की स्पीड ऑप्टिमाइज़ करें.

अगर आपने Gradle को पहली बार इस्तेमाल किया है, तो Configure Your Build में मौजूद बुनियादी जानकारी को पढ़ें. इसके अलावा, Android प्लग इन का DSL संदर्भ दस्तावेज़ में, इस पेज में इस्तेमाल की गई प्रॉपर्टी के बारे में ज़्यादा जानें.

प्रोजेक्ट और सोर्स मैनेज करना

यहां कुछ कॉन्फ़िगरेशन दिए गए हैं. इनकी मदद से, आपके प्रोजेक्ट के मॉड्यूल और स्रोत. प्रोजेक्ट और मॉड्यूल बनाने और उन्हें मैनेज करने के बारे में ज़्यादा जानने के लिए, पढ़ें प्रोजेक्ट की खास जानकारी.

सोर्स सेट के डिफ़ॉल्ट कॉन्फ़िगरेशन बदलना

मॉड्यूल-लेवल build.gradle में sourceSets ब्लॉक का इस्तेमाल किया जा सकता है फ़ाइल यह बदलने के लिए है कि Gradle, फ़ाइल के हर कॉम्पोनेंट के लिए फ़ाइलों को कहां इकट्ठा करता है सोर्स सेट.

ग्रूवी

android {
  ...
  sourceSets {
    // Encapsulates configurations for the main source set.
    main {
      // Changes the directory for Java sources. The default directory is
      // 'src/main/java'.
      java.srcDirs = ['other/java']

      // When you list multiple directories, Gradle uses all of them to collect
      // sources. You should avoid specifying a directory which is a parent to one
      // or more other directories you specify.
      res.srcDirs = ['other/res1', 'other/res2']

      // For each source set, you can specify only one Android manifest.
      // The following points Gradle to a different manifest for this source set.
      manifest.srcFile 'other/AndroidManifest.xml'
      ...
    }

    // Create additional blocks to configure other source sets.
    androidTest {

      // If all the files for a source set are located under a single root
      // directory, you can specify that directory using the setRoot property.
      // When gathering sources for the source set, Gradle looks only in locations
      // relative to the root directory you specify. For example, after applying
      // the configuration below for the androidTest source set, Gradle looks for
      // Java sources only in the src/tests/java/ directory.
      setRoot 'src/tests'
      ...
    }
  }
}
...

Kotlin

android {
  ...
  sourceSets {
    // Encapsulates configurations for the main source set.
    getByName("main") {
      // Changes the directory for Java sources. The default directory is
      // 'src/main/java'.
      java.setSrcDirs("other/java")

      // When you list multiple directories, Gradle uses all of them to collect
      // sources. You should avoid specifying a directory which is a parent to one
      // or more other directories you specify.
      res.setSrcDirs("other/res1", "other/res2")

      // For each source set, you can specify only one Android manifest.
      // The following points Gradle to a different manifest for this source set.
      manifest.srcFile("other/AndroidManifest.xml")
      ...
    }

    // Create additional blocks to configure other source sets.
    androidTest {

      // If all the files for a source set are located under a single root
      // directory, you can specify that directory using the setRoot property.
      // When gathering sources for the source set, Gradle looks only in locations
      // relative to the root directory you specify. For example, after applying
      // the configuration below for the androidTest source set, Gradle looks for
      // Java sources only in the src/tests/java/ directory.
      setRoot("src/tests")
      ...
    }
  }
}
...

लाइब्रेरी और डिपेंडेंसी मैनेज करना

Gradle, डिपेंडेंसी मैनेज करने का एक मज़बूत तरीका उपलब्ध कराता है. इससे कोई फ़र्क़ नहीं पड़ता कि वे रिमोट लाइब्रेरी या लोकल लाइब्रेरी मॉड्यूल.

डिपेंडेंसी कॉन्फ़िगरेशन की मदद से खास बिल्ड को टारगेट करें

अगर आपको सिर्फ़ किसी खास बिल्ड वैरिएंट के सोर्स सेट या टेस्टिंग सोर्स सेट के लिए डिपेंडेंसी चाहिए, तो कैपिटल लेटर का इस्तेमाल करें निर्भरता कॉन्फ़िगरेशन नाम और प्रीफ़िक्स के तौर पर बिल्ड वैरिएंट के नाम का इस्तेमाल करें या टेस्टिंग सोर्स सेट.

ग्रूवी

android {...}

// Creates Gradle dependency configurations to use in the dependencies block.
configurations {
  // For variants that combine a product flavor and build type, you need to
  // intitialize a placeholder for its dependency configuration.
  freeDebugRuntimeOnly{}
  ...
}

dependencies {
    // Adds an implementation dependency only to the "free" product flavor.
    freeImplementation 'com.google.firebase:firebase-ads:21.5.1'
    // Adds a runtimeOnly dependency only to the "freeDebug" build variant.
    freeDebugRuntimeOnly fileTree(dir: 'libs', include: ['*.jar'])
    // Adds a remote binary dependency only for local tests.
    testImplementation 'junit:junit:4.12'
    // Adds a remote binary dependency only for the instrumented test APK.
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.5.1'
}

Kotlin

android {...}

dependencies {
    // Use ""() notation for custom flavors and build types
    // Adds an implementation dependency only to the "free" product flavor.
    "freeImplementation"("com.google.firebase:firebase-ads:21.5.1")
    // Adds a runtimeOnly dependency only to the "freeDebug" build variant.
    "freeDebugRuntimeOnly"(fileTree("dir" to "libs", "include" to "*.jar"))
    // Adds a remote binary dependency only for local tests.
    testImplementation("junit:junit:4.12")
    // Adds a remote binary dependency only for the instrumented test APK.
    androidTestImplementation("com.android.support.test.espresso:espresso-core:3.5.1")
}

अपने ऐप्लिकेशन के अलग-अलग वर्शन बनाना

Gradle और Android प्लगिन की मदद से, अपने ऐप्लिकेशन के अलग-अलग वर्शन बनाए जा सकते हैं किसी एक मॉड्यूल से ऐप्लिकेशन डाउनलोड करने की सुविधा मिलती है. इसके लिए, बिल्ड के वैरिएंट कॉन्फ़िगर करके.

डाइनैमिक वर्शन कोड कॉन्फ़िगर करना

डिफ़ॉल्ट रूप से, जब Gradle आपके प्रोजेक्ट के लिए APK जनरेट करता है, तो हर APK में वर्शन की वही जानकारी है जो मॉड्यूल लेवल की build.gradle फ़ाइल में दी गई है. क्योंकि Google Play Store एक ही ऐप्लिकेशन के लिए कई APK की अनुमति नहीं देता है कि सभी की वर्शन जानकारी समान है, तो आपको यह पक्का करना होगा कि प्रत्येक APK में यह आपके लिए बनाया गया है एक खास versionCode Play Store पर अपलोड करें.

ऐसा करने के लिए, अपनी पसंद के मुताबिक बिल्ड लॉजिक का इस्तेमाल किया जा सकता है. इस वजह से, कोई दूसरा वर्शन कोड असाइन किया जा सकता है करते हैं. उदाहरण के लिए, हर फ़ाइल के लिए अलग-अलग APKs बनाते समय एबीआई, अपने-आप बनने वाले APK का वर्शन कुछ ऐसा दिखता है:

ग्रूवी

android {
  ...
  defaultConfig {
    ...
    versionCode 4
  }
  splits {
    ...
  }
}

// Map for the version code that gives each ABI a value.
ext.abiCodes = ['armeabi-v7a':1, mips:2, x86:3]

// For per-density APKs, create a similar map like this:
// ext.densityCodes = ['hdpi': 1, 'xhdpi': 2, 'xxhdpi': 3, 'xxxhdpi': 4]

import com.android.build.OutputFile

// For each APK output variant, override versionCode with a combination of
// ext.abiCodes * 1000 + variant.versionCode. In this example, variant.versionCode
// is equal to defaultConfig.versionCode. If you configure product flavors that
// define their own versionCode, variant.versionCode uses that value instead.
android.applicationVariants.all { variant ->

  // Assigns a different version code for each output APK
  // other than the universal APK.
  variant.outputs.each { output ->

    // Stores the value of ext.abiCodes that is associated with the ABI for this variant.
    def baseAbiVersionCode =
            // Determines the ABI for this variant and returns the mapped value.
            project.ext.abiCodes.get(output.getFilter(OutputFile.ABI))

    // Because abiCodes.get() returns null for ABIs that are not mapped by ext.abiCodes,
    // the following code does not override the version code for universal APKs.
    // However, because we want universal APKs to have the lowest version code,
    // this outcome is desirable.
    if (baseAbiVersionCode != null) {

      // Assigns the new version code to versionCodeOverride, which changes the version code
      // for only the output APK, not for the variant itself. Skipping this step simply
      // causes Gradle to use the value of variant.versionCode for the APK.
      output.versionCodeOverride =
              baseAbiVersionCode * 1000 + variant.versionCode
    }
  }
}

Kotlin

android {
  ...
  defaultConfig {
    ...
    versionCode = 4
  }
  splits {
    ...
  }
}

// Map for the version code that gives each ABI a value.
val abiCodes = mapOf("armeabi-v7a" to 1, "mips" to 2, "x86" to 3)

// For per-density APKs, create a similar map like this:
// val densityCodes = mapOf("hdpi" to 1, "xhdpi" to 2, "xxhdpi" to 3, "xxxhdpi" to 4)

import com.android.build.api.variant.FilterConfiguration.FilterType.*

// For each APK output variant, override versionCode with a combination of
// abiCodes * 1000 + variant.versionCode. In this example, variant.versionCode
// is equal to defaultConfig.versionCode. If you configure product flavors that
// define their own versionCode, variant.versionCode uses that value instead.
androidComponents {
    onVariants { variant ->

        // Assigns a different version code for each output APK
        // other than the universal APK.
        variant.outputs.forEach { output ->
            val name = output.filters.find { it.filterType == ABI }?.identifier

            // Stores the value of abiCodes that is associated with the ABI for this variant.
            val baseAbiCode = abiCodes[name]
            // Because abiCodes.get() returns null for ABIs that are not mapped by ext.abiCodes,
            // the following code does not override the version code for universal APKs.
            // However, because we want universal APKs to have the lowest version code,
            // this outcome is desirable.
            if (baseAbiCode != null) {
                // Assigns the new version code to output.versionCode, which changes the version code
                // for only the output APK, not for the variant itself.
                output.versionCode.set(baseAbiCode * 1000 + (output.versionCode.get() ?: 0))
            }
        }
    }
}

अलग-अलग फ़्लेवर का एक साथ इस्तेमाल करें

कुछ मामलों में, हो सकता है कि आपको कॉन्फ़िगरेशन एक साथ जोड़ना पड़े अलग-अलग फ़्लेवर के लिए. ऐसा करने के लिए, Gradle के लिए Android प्लग इन की मदद से आप प्रॉडक्ट के फ़्लेवर के ग्रुप बना सकते हैं. इन ग्रुप को फ़्लेवर डाइमेंशन.

नीचे दिया गया कोड सैंपल का इस्तेमाल करता है "मोड" बनाने के लिए flavorDimensions प्रॉपर्टी ग्रुप करने के लिए फ़्लेवर डाइमेंशन "पूरा" और "डेमो" प्रॉडक्ट के फ़्लेवर, और "api" ग्रुप करने के लिए फ़्लेवर डाइमेंशन एपीआई लेवल के आधार पर प्रॉडक्ट के फ़्लेवर का कॉन्फ़िगरेशन. इसके बाद, Gradle एक साथ चलता है "मोड" से लोकप्रिय प्रॉडक्ट "api" वाले डाइमेंशन के साथ डाइमेंशन.

ग्रूवी

android {
  ...
  buildTypes {
    debug {...}
    release {...}
  }

  // Specifies the flavor dimensions you want to use. The order in which you
  // list each dimension determines its priority, from highest to lowest,
  // when Gradle merges variant sources and configurations. You must assign
  // each product flavor you configure to one of the flavor dimensions.
  flavorDimensions "api", "mode"

  productFlavors {
    demo {
      // Assigns this product flavor to the "mode" flavor dimension.
      dimension "mode"
      ...
    }

    full {
      dimension "mode"
      ...
    }

    // Configurations in the "api" product flavors override those in "mode"
    // flavors and the defaultConfig block. Gradle determines the priority
    // between flavor dimensions based on the order in which they appear next
    // to the flavorDimensions property above--the first dimension has a higher
    // priority than the second, and so on.
    minApi24 {
      dimension "api"
      minSdkVersion '24'
      // To ensure the target device receives the version of the app with
      // the highest compatible API level, assign version codes in increasing
      // value with API level. To learn more about assigning version codes to
      // support app updates and uploading to Google Play, read Multiple APK Support
      versionCode 30000 + android.defaultConfig.versionCode
      versionNameSuffix "-minApi24"
      ...
    }

    minApi23 {
      dimension "api"
      minSdkVersion '23'
      versionCode 20000  + android.defaultConfig.versionCode
      versionNameSuffix "-minApi23"
      ...
    }

    minApi21 {
      dimension "api"
      minSdkVersion '21'
      versionCode 10000  + android.defaultConfig.versionCode
      versionNameSuffix "-minApi21"
      ...
    }
  }
}
...

Kotlin

android {
  ...
  buildTypes {
    getByName("debug") {...}
    getByName("release") {...}
  }

  // Specifies the flavor dimensions you want to use. The order in which you
  // list each dimension determines its priority, from highest to lowest,
  // when Gradle merges variant sources and configurations. You must assign
  // each product flavor you configure to one of the flavor dimensions.
  flavorDimensions += listOf("api", "mode")

  productFlavors {
    create("demo") {
      // Assigns this product flavor to the "mode" flavor dimension.
      dimension = "mode"
      ...
    }

    create("full") {
      dimension = "mode"
      ...
    }

    // Configurations in the "api" product flavors override those in "mode"
    // flavors and the defaultConfig block. Gradle determines the priority
    // between flavor dimensions based on the order in which they appear next
    // to the flavorDimensions property above--the first dimension has a higher
    // priority than the second, and so on.
    create("minApi24") {
      dimension = "api"
      minSdkVersion(24)
      // To ensure the target device receives the version of the app with
      // the highest compatible API level, assign version codes in increasing
      // value with API level. To learn more about assigning version codes to
      // support app updates and uploading to Google Play, read Multiple APK Support
      versionCode = 30000 + android.defaultConfig.versionCode
      versionNameSuffix = "-minApi24"
      ...
    }

    create("minApi23") {
      dimension = "api"
      minSdkVersion(23)
      versionCode = 20000  + android.defaultConfig.versionCode
      versionNameSuffix = "-minApi23"
      ...
    }

    create("minApi21") {
      dimension = "api"
      minSdkVersion(21)
      versionCode = 10000  + android.defaultConfig.versionCode
      versionNameSuffix = "-minApi21"
      ...
    }
  }
}
...

वैरिएंट फ़िल्टर करें

आप फ़िल्टर ऐसे वैरिएंट बनाएं जिन्हें आपको मॉड्यूल की build.gradle फ़ाइल में variantFilter ब्लॉक करें. कॉन्टेंट बनाने नीचे दिया गया सैंपल कोड, Gradle को ऐसा कोई भी वैरिएंट नहीं बनाने के लिए कहता है जो एक-दूसरे के साथ मिलकर काम करता हो "minApi21" और "डेमो" प्रॉडक्ट फ़्लेवर:

ग्रूवी

android {
  ...
  buildTypes {...}

  flavorDimensions "api", "mode"
  productFlavors {
    demo {...}
    full {...}
    minApi24 {...}
    minApi23 {...}
    minApi21 {...}
  }

  variantFilter { variant ->
      def names = variant.flavors*.name
      // To check for a certain build type, use variant.buildType.name == "<buildType>"
      if (names.contains("minApi21") && names.contains("demo")) {
          // Gradle ignores any variants that satisfy the conditions above.
          setIgnore(true)
      }
  }
}
...

Kotlin

android {
  ...
  buildTypes {...}

  flavorDimensions "api", "mode"
  productFlavors {
    create("demo") {...}
    create("full") {...}
    create("minApi24") {...}
    create("minApi23") {...}
    create("minApi21") {...}
  }
}

androidComponents {
    beforeVariants { variantBuilder ->
        // To check for a certain build type, use variantBuilder.buildType == "<buildType>"
        if (variantBuilder.productFlavors.containsAll(listOf("api" to "minApi21", "mode" to "demo"))) {
            // Gradle ignores any variants that satisfy the conditions above.
            variantBuilder.enabled = false
        }
    }
}
...

अपने ऐप्लिकेशन की जांच करें

लोकल और इंटिग्रेटेड यूनिट टेस्ट चलाने के बारे में ज़्यादा जानने के लिए, अपने ऐप्लिकेशन की जांच करना लेख पढ़ें.

लिंट के विकल्पों को कॉन्फ़िगर करें

आप आपके मॉड्यूल-लेवल की build.gradle फ़ाइल में lintOptions ब्लॉक. यहां की यात्रा पर हूं अपने Android प्रोजेक्ट के लिए लिंट का इस्तेमाल करने के बारे में ज़्यादा जानें. लिंट की मदद से अपने कोड को बेहतर बनाएं लेख पढ़ें.

ग्रूवी

android {
    ...
    lintOptions {
        // Turns off checks for the issue IDs you specify.
        disable 'TypographyFractions','TypographyQuotes'
        // Turns on checks for the issue IDs you specify. These checks are in
        // addition to the default lint checks.
        enable 'RtlHardcoded','RtlCompat', 'RtlEnabled'
        // To enable checks for only a subset of issue IDs and ignore all others,
        // list the issue IDs with the 'check' property instead. This property overrides
        // any issue IDs you enable or disable using the properties above.
        checkOnly 'NewApi', 'InlinedApi'
        // If set to true, turns off analysis progress reporting by lint.
        quiet true
        // if set to true (default), stops the build if errors are found.
        abortOnError false
        // if true, only report errors.
        ignoreWarnings true
    }
}
...

Kotlin

android {
    ...
    lintOptions {
        // Turns off checks for the issue IDs you specify.
        disable("TypographyFractions")
        disable("TypographyQuotes")
        // Turns on checks for the issue IDs you specify. These checks are in
        // addition to the default lint checks.
        enable("RtlHardcoded")
        enable("RtlCompat")
        enable("RtlEnabled")
        // To enable checks for only a subset of issue IDs and ignore all others,
        // list the issue IDs with the 'check' property instead. This property overrides
        // any issue IDs you enable or disable using the properties above.
        checkOnly("NewApi", "InlinedApi")
        // If set to true, turns off analysis progress reporting by lint.
        quiet = true
        // if set to true (default), stops the build if errors are found.
        abortOnError = false
        // if true, only report errors.
        ignoreWarnings = true
    }
}
...

इंस्ट्रुमेंटेशन मेनिफ़ेस्ट सेटिंग कॉन्फ़िगर करें

जब Gradle आपका टेस्ट APK बनाता है, तब वह अपने-आप AndroidManifest.xml फ़ाइल जनरेट करता है और इसे <instrumentation> के साथ कॉन्फ़िगर करता है नोड के लिए अलग-अलग हैं. आप इस नोड के लिए कुछ सेटिंग को टेस्ट सोर्स सेट में कोई दूसरी मेनिफ़ेस्ट फ़ाइल या मॉड्यूल-लेवल की build.gradle फ़ाइल को कॉन्फ़िगर करना, जैसा कि दिए गए कोड का सैंपल देखें.

ग्रूवी

android {
  ...
  // Each product flavor you configure can override properties in the
  // defaultConfig block. To learn more, go to Configure Product Flavors.
  defaultConfig {
    ...
    // Specifies the application ID for the test APK.
    testApplicationId "com.test.foo"
    // Specifies the fully-qualified class name of the test instrumentation runner.
    testInstrumentationRunner "android.test.InstrumentationTestRunner"
    // If set to 'true', enables the instrumentation class to start and stop profiling.
    // If set to false (default), profiling occurs the entire time the instrumentation
    // class is running.
    testHandleProfiling true
    // If set to 'true', indicates that the Android system should run the instrumentation
    // class as a functional test. The default value is 'false'
    testFunctionalTest true
  }
}
...

Kotlin

android {
  ...
  // Each product flavor you configure can override properties in the
  // defaultConfig block. To learn more, go to Configure Product Flavors.
  defaultConfig {
    ...
    // Specifies the application ID for the test APK.
    testApplicationId = "com.test.foo"
    // Specifies the fully-qualified class name of the test instrumentation runner.
    testInstrumentationRunner = "android.test.InstrumentationTestRunner"
    // If set to 'true', enables the instrumentation class to start and stop profiling.
    // If set to false (default), profiling occurs the entire time the instrumentation
    // class is running.
    testHandleProfiling = true
    // If set to 'true', indicates that the Android system should run the instrumentation
    // class as a functional test. The default value is 'false'
    testFunctionalTest = true
  }
}
...

टेस्ट बिल्ड टाइप बदलना

डिफ़ॉल्ट रूप से, सभी टेस्ट डीबग बिल्ड टाइप पर चलते हैं. इसे बदला जा सकता है में testBuildType प्रॉपर्टी का उपयोग करके किसी अन्य बिल्ड प्रकार मॉड्यूल-लेवल की build.gradle फ़ाइल होनी चाहिए. उदाहरण के लिए, अगर आपको अपनी "स्टेजिंग" पर जांच करें बिल्ड टाइप, फ़ाइल में दिखाए गए तरीके से बदलाव करें स्निपेट शामिल करें.

ग्रूवी

android {
    ...
    testBuildType "staging"
}

Kotlin

android {
    ...
    testBuildType "staging"
}

Gradle टेस्ट के विकल्प कॉन्फ़िगर करें

Gradle आपके सभी टेस्ट को चलाने के तरीके को बदलने वाले विकल्पों को तय करने के लिए, मॉड्यूल-लेवल में testOptions ब्लॉक build.gradle.

ग्रूवी

android {
  ...
  // Encapsulates options for running tests.
  testOptions {
    // Changes the directory where Gradle saves test reports. By default, Gradle saves test reports
    // in the path_to_your_project/module_name/build/outputs/reports/ directory.
    // '$rootDir' sets the path relative to the root directory of the current project.
    reportDir "$rootDir/test-reports"
    // Changes the directory where Gradle saves test results. By default, Gradle saves test results
    // in the path_to_your_project/module_name/build/outputs/test-results/ directory.
    // '$rootDir' sets the path relative to the root directory of the current project.
    resultsDir "$rootDir/test-results"
  }
}

Kotlin

android {
  ...
  // Encapsulates options for running tests.
  testOptions {
    // Changes the directory where Gradle saves test reports. By default, Gradle saves test reports
    // in the path_to_your_project/module_name/build/outputs/reports/ directory.
    // '$rootDir' sets the path relative to the root directory of the current project.
    reportDir "$rootDir/test-reports"
    // Changes the directory where Gradle saves test results. By default, Gradle saves test results
    // in the path_to_your_project/module_name/build/outputs/test-results/ directory.
    // '$rootDir' sets the path relative to the root directory of the current project.
    resultsDir "$rootDir/test-results"
  }
}

सिर्फ़ स्थानीय इकाई जांच के विकल्प तय करने के लिए, testOptions.unitTests ब्लॉक.

ग्रूवी

android {
  ...
  testOptions {
    ...
    // Encapsulates options for local unit tests.
    unitTests {
      // By default, local unit tests throw an exception any time the code you are testing tries to access
      // Android platform APIs (unless you mock Android dependencies yourself or with a testing
      // framework like Mockito). However, you can enable the following property so that the test
      // returns either null or zero when accessing platform APIs, rather than throwing an exception.
      returnDefaultValues true

      // Encapsulates options for controlling how Gradle executes local unit tests. For a list
      // of all the options you can specify, read Gradle's reference documentation.
      all {
        // Sets JVM argument(s) for the test JVM(s).
        jvmArgs '-XX:MaxPermSize=256m'

        // You can also check the task name to apply options to only the tests you specify.
        if (it.name == 'testDebugUnitTest') {
          systemProperty 'debug', 'true'
        }
      }
    }
  }
}

Kotlin

android {
  ...
  testOptions {
    ...
    // Encapsulates options for local unit tests.
    unitTests {
      // By default, local unit tests throw an exception any time the code you are testing tries to access
      // Android platform APIs (unless you mock Android dependencies yourself or with a testing
      // framework like Mockito). However, you can enable the following property so that the test
      // returns either null or zero when accessing platform APIs, rather than throwing an exception.
      returnDefaultValues true

      // Encapsulates options for controlling how Gradle executes local unit tests. For a list
      // of all the options you can specify, read Gradle's reference documentation.
      all {
        // Sets JVM argument(s) for the test JVM(s).
        jvmArgs '-XX:MaxPermSize=256m'

        // You can also check the task name to apply options to only the tests you specify.
        if (it.name == 'testDebugUnitTest') {
          systemProperty 'debug', 'true'
        }
      }
    }
  }
}

अपने बिल्ड को ऑप्टिमाइज़ करें

इस सेक्शन में कुछ कॉन्फ़िगरेशन दिए गए हैं. इनकी मदद से, तेज़ी से काम पूरा किया जा सकता है और इंक्रीमेंटल बिल्ड इस बारे में ज़्यादा जानने के लिए, पढ़ें वीडियो बनाने की स्पीड ऑप्टिमाइज़ करें.

अपने कोड को छोटा करें

Android Studio, R8 का इस्तेमाल करता है, जो आपके कोड को छोटा करने के लिए, ProGuard नियमों वाली फ़ाइलों का इस्तेमाल करता है. नए के लिए प्रोजेक्ट के लिए उपलब्ध है, तो Android Studioproguard-android.txt Android SDK की tools/proguard/folder. कोड का साइज़ और कम करने के लिए, proguard-android-optimize.txt फ़ाइल जिसमें उसी जगह पर मौजूद कोई फ़ाइल है.

ग्रूवी

android {
  buildTypes {
    release {
      minifyEnabled true
      proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'),
                                           'proguard-rules.pro'
    }
  }
  ...
}
...

Kotlin

android {
  buildTypes {
    release {
      minifyEnabled true
      proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'),
                                           'proguard-rules.pro'
    }
  }
  ...
}
...

हर बिल्ड वैरिएंट के लिए खास नियम जोड़ने के लिए, कॉन्फ़िगर करें अतिरिक्त हर फ़्लेवर के लिए proguardFiles प्रॉपर्टी. उदाहरण के लिए, इसके बाद, flavor2-rules.pro को "फ़्लेवर2" में जोड़ा जाता है. अब "फ़्लेवर2" का रिलीज़ वर्शन सभी तीनों नियम फ़ाइलों का इस्तेमाल करता है, क्योंकि तो रिलीज़ ब्लॉक भी लागू हो जाते हैं.

ग्रूवी

android {
  ...
  buildTypes {
    release {
      minifyEnabled true
      proguardFiles getDefaultProguardFile('proguard-android.txt'),
             'proguard-rules.pro'
    }
  }
  productFlavors {
    flavor1 {
      ...
    }
    flavor2 {
      proguardFile 'flavor2-rules.pro'
    }
  }
}
...

Kotlin

android {
  ...
  buildTypes {
    release {
      minifyEnabled true
      proguardFiles getDefaultProguardFile('proguard-android.txt'),
             'proguard-rules.pro'
    }
  }
  productFlavors {
    flavor1 {
      ...
    }
    flavor2 {
      proguardFile 'flavor2-rules.pro'
    }
  }
}
...

ऐप्लिकेशन को पब्लिश करना

अपने ऐप्लिकेशन को Google Play पर पब्लिश करने के बारे में ज़्यादा जानने के लिए, अपना ऐप्लिकेशन पब्लिश करें लेख पढ़ें.

अपने ऐप्लिकेशन पर हस्ताक्षर करना

हालांकि, Android Studio रिलीज़ के लिए साइनिंग की सुविधा को कॉन्फ़िगर करने का आसान तरीका है बिल्ड होता है, तो आप अपने मॉड्यूल के build.gradle में signingConfigs ब्लॉक को मैन्युअल तरीके से कॉन्फ़िगर कर सकते हैं फ़ाइल:

ग्रूवी

android {
  ...
  defaultConfig { ... }

  // Encapsulates signing configurations.
  signingConfigs {
    // Creates a signing configuration called "release".
    release {
      // Specifies the path to your keystore file.
      storeFile file("my-release-key.jks")
      // Specifies the password for your keystore.
      storePassword "password"
      // Specifies the identifying name for your key.
      keyAlias "my-alias"
      // Specifies the password for your key.
      keyPassword "password"
    }
  }
  buildTypes {
    release {
      // Adds the "release" signing configuration to the release build type.
      signingConfig signingConfigs.release
      ...
    }
  }
}
...

Kotlin

android {
  ...
  defaultConfig { ... }

  // Encapsulates signing configurations.
  signingConfigs {
    // Creates a signing configuration called "release".
    release {
      // Specifies the path to your keystore file.
      storeFile file("my-release-key.jks")
      // Specifies the password for your keystore.
      storePassword "password"
      // Specifies the identifying name for your key.
      keyAlias "my-alias"
      // Specifies the password for your key.
      keyPassword "password"
    }
  }
  buildTypes {
    release {
      // Adds the "release" signing configuration to the release build type.
      signingConfig signingConfigs.release
      ...
    }
  }
}
...

अपने प्रोजेक्ट से निजी साइनिंग जानकारी हटाना

डिफ़ॉल्ट रूप से, साइनिंग कॉन्फ़िगरेशन को सादे टेक्स्ट में, मॉड्यूल के build.gradle फ़ाइल. अगर आप किसी टीम या ओपन-सोर्स प्रोजेक्ट के लिए, आपके पास इस संवेदनशील जानकारी को बिल्ड से बाहर ले जाने फ़ाइलों को भेजने के लिए नीचे दिया गया तरीका अपनाएं.

  1. अपनी रूट डायरेक्ट्री में keystore.properties नाम की फ़ाइल बनाएं प्रोजेक्ट करें और इसमें नीचे दी गई जानकारी शामिल करें:
    storePassword=myStorePassword
    keyPassword=myKeyPassword
    keyAlias=myKeyAlias
    storeFile=myStoreFileLocation
    
  2. अपनी build.gradle फ़ाइल में, keystore.properties को लोड करें फ़ाइल का फ़ॉर्मैट देखें (यह Android ब्लॉक से पहले होना चाहिए):

    ग्रूवी

    // Creates a variable called keystorePropertiesFile, and initializes it to the
    // keystore.properties file.
    def keystorePropertiesFile = rootProject.file("keystore.properties")
    
    // Initializes a new Properties() object called keystoreProperties.
    def keystoreProperties = new Properties()
    
    // Loads the keystore.properties file into the keystoreProperties object.
    keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
    
    android {
      ...
    }
    ...
    

    Kotlin

    // Creates a variable called keystorePropertiesFile, and initializes it to the
    // keystore.properties file.
    def keystorePropertiesFile = rootProject.file("keystore.properties")
    
    // Initializes a new Properties() object called keystoreProperties.
    def keystoreProperties = new Properties()
    
    // Loads the keystore.properties file into the keystoreProperties object.
    keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
    
    android {
      ...
    }
    ...
    
  3. keystoreProperties में सेव की गई, हस्ताक्षर की जानकारी डालें ऑब्जेक्ट:

    ग्रूवी

    android {
      signingConfigs {
        config {
          keyAlias keystoreProperties['keyAlias']
          keyPassword keystoreProperties['keyPassword']
          storeFile file(keystoreProperties['storeFile'])
          storePassword keystoreProperties['storePassword']
        }
      }
      ...
    }
    ...
    

    Kotlin

    android {
      signingConfigs {
        config {
          keyAlias keystoreProperties['keyAlias']
          keyPassword keystoreProperties['keyPassword']
          storeFile file(keystoreProperties['storeFile'])
          storePassword keystoreProperties['storePassword']
        }
      }
      ...
    }
    ...
    
  4. सूचना बार में अभी सिंक करें पर क्लिक करें.

ऐप्लिकेशन साइनिंग के बारे में ज़्यादा जानने के लिए, अपने ऐप्लिकेशन पर हस्ताक्षर करना लेख पढ़ें.

ऐप्लिकेशन डेवलपमेंट को आसान बनाएं

नीचे दी गई सलाह अपनाकर, Android ऐप्लिकेशन को डेवलप करना आसान हो जाता है.

अपने ऐप्लिकेशन के कोड के साथ कस्टम फ़ील्ड और संसाधन की वैल्यू शेयर करना

बिल्ड के दौरान, Gradle BuildConfig क्लास जनरेट करता है, ताकि आपके ऐप्लिकेशन कोड, मौजूदा बिल्ड के बारे में जानकारी की जांच कर सकता है. इन्हें भी जोड़ा जा सकता है आपके Gradle बिल्ड से BuildConfig क्लास में कस्टम फ़ील्ड buildConfigField() तरीके और ऐक्सेस का इस्तेमाल करने वाली कॉन्फ़िगरेशन फ़ाइल आपके ऐप्लिकेशन के रनटाइम कोड में वे वैल्यू शामिल होती हैं. इसी तरह, आप ऐप संसाधन जोड़ सकते हैं resValue() के साथ मान.

ग्रूवी

android {
  ...
  buildTypes {
    release {
      // These values are defined only for the release build, which
      // is typically used for full builds and continuous builds.
      buildConfigField("String", "BUILD_TIME", "\"${minutesSinceEpoch}\"")
      resValue("string", "build_time", "${minutesSinceEpoch}")
      ...
    }
    debug {
      // Use static values for incremental builds to ensure that
      // resource files and BuildConfig aren't rebuilt with each run.
      // If these rebuild dynamically, they can interfere with
      // Apply Changes as well as Gradle UP-TO-DATE checks.
      buildConfigField("String", "BUILD_TIME", "\"0\"")
      resValue("string", "build_time", "0")
    }
  }
}
...

Kotlin

android {
  ...
  buildTypes {
    release {
      // These values are defined only for the release build, which
      // is typically used for full builds and continuous builds.
      buildConfigField("String", "BUILD_TIME", "\"${minutesSinceEpoch}\"")
      resValue("string", "build_time", "${minutesSinceEpoch}")
      ...
    }
    debug {
      // Use static values for incremental builds to ensure that
      // resource files and BuildConfig aren't rebuilt with each run.
      // If these rebuild dynamically, they can interfere with
      // Apply Changes as well as Gradle UP-TO-DATE checks.
      buildConfigField("String", "BUILD_TIME", "\"0\"")
      resValue("string", "build_time", "0")
    }
  }
}
...

अपने ऐप्लिकेशन कोड में, प्रॉपर्टी को इस तरह ऐक्सेस किया जा सकता है:

Kotlin

...
Log.i(TAG, BuildConfig.BUILD_TIME)
Log.i(TAG, getString(R.string.build_time))

Java

...
Log.i(TAG, BuildConfig.BUILD_TIME);
Log.i(TAG, getString(R.string.build_time));

मेनिफ़ेस्ट के साथ प्रॉपर्टी शेयर करें

कुछ मामलों में, आपको दोनों में एक ही प्रॉपर्टी का एलान करना पड़ सकता है और आपका कोड (उदाहरण के लिए, जब किसी संस्था को यह तय करना हो कि FileProvider). एक ही प्रॉपर्टी को कई जगहों पर अपडेट करने के बजाय, बदलें, अपने मॉड्यूल के build.gradle में सिर्फ़ एक प्रॉपर्टी तय करें फ़ाइल को मेनिफ़ेस्ट और आपके कोड दोनों में उपलब्ध करवाना होगा, जैसा कि नीचे दिया गया नमूना. ज़्यादा जानने के लिए, बिल्ड वैरिएबल इंजेक्ट करें को मेनिफ़ेस्ट.

ग्रूवी

android {
  // For settings specific to a product flavor, configure these properties
  // for each flavor in the productFlavors block.
  defaultConfig {
    // Creates a property for the FileProvider authority.
    def filesAuthorityValue = applicationId + ".files"
    // Creates a placeholder property to use in the manifest.
    manifestPlaceholders =
      [filesAuthority: filesAuthorityValue]
      // Adds a new field for the authority to the BuildConfig class.
      buildConfigField("String",
                       "FILES_AUTHORITY",
                       "\"${filesAuthorityValue}\"")
  }
  ...
}
...

Kotlin

android {
  // For settings specific to a product flavor, configure these properties
  // for each flavor in the productFlavors block.
  defaultConfig {
    // Creates a property for the FileProvider authority.
    val filesAuthorityValue = applicationId + ".files"
    // Creates a placeholder property to use in the manifest.
    manifestPlaceholders["filesAuthority"] = filesAuthorityValue
      // Adds a new field for the authority to the BuildConfig class.
      buildConfigField("String",
                       "FILES_AUTHORITY",
                       "\"${filesAuthorityValue}\"")
  }
  ...
}
...

अपने मेनिफ़ेस्ट में, प्लेसहोल्डर को इस तरह ऐक्सेस करें:

<manifest>
  ...
  <application>
    ...
    <provider
      android:name="android.support.v4.content.FileProvider"
      android:authorities="${filesAuthority}"
      android:exported="false"
      android:grantUriPermissions="true">
      ...
    </provider>
  </application>
</manifest>

अपने ऐप्लिकेशन के कोड लुक में FILES_AUTHORITY फ़ील्ड को ऐक्सेस करने से कुछ ऐसा:

Kotlin

...
val contentUri: Uri = FileProvider.getUriForFile(context, BuildConfig.FILES_AUTHORITY, myFile)

Java

...
Uri contentUri = FileProvider.getUriForFile(getContext(),
  BuildConfig.FILES_AUTHORITY,
  myFile);