search
HomeJavajavaTutorialHow to use Java high version API in Android

    Android plug-in opens support for new APIs

    On this day, Xiao Wang imported a library, and a large piece of it crashed immediately after it went online? Find the problem:

    How to use Java high version API in Android

    #What the hell? Unable to use Android 8.0? In this way, all mobile phones launched below 8.0 crashed. After checking, I found out that I need to enable the plug-in to enable support for Java Api

    android {
      defaultConfig {
        multiDexEnabled true
      }
    
      compileOptions {
        // Flag to enable support for the new language APIs
        coreLibraryDesugaringEnabled true
    
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
      }
    }
    
    dependencies {
      coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.5'
    }

    Be sure to turn on multiDexEnabled. The principle is that a separate dex package will be created during compilation to do some compatible processing.

    Commonly used classes that require compatible processing:

    1. LocalDate date processing

    		// 日期
    		LocalDate today = LocalDate.now();
    		// 几号
    		int dayofMonth = today.getDayOfMonth();
    		// 星期几
    		int dayofWeek = today.getDayOfWeek().getValue();
    		// 今年
    		int dayofYear = today.getDayOfYear();
    		
    		LocalDate endOfFeb = LocalDate.parse("2018-02-28"); 
    
                    // 取本月第1天:
    		LocalDate firstDayOfThisMonth = today.with(TemporalAdjusters.firstDayOfMonth()); 
    		// 取本月第2天:
    		LocalDate secondDayOfThisMonth = today.withDayOfMonth(2); 
    
    		// 取本月最后一天,再也不用计算是28,29,30还是31:
    		LocalDate lastDayOfThisMonth = today.with(TemporalAdjusters.lastDayOfMonth());
    
    		// 取下一天:
    		LocalDate firstDayOfNextMonth = lastDayOfThisMonth.plusDays(1); 
    
    		// 取2017年1月第一个周一:
    		LocalDate firstMondayOf2017 = LocalDate.parse("2017-01-01").with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY));

    2. Stream collection flow operations

      List<widget> widgets = new ArrayList<>();
            widgets.add(new widget(Color.RED, "Name", 1));
            int sum = widgets.stream()
                    .filter(w -> w.getColor() == Color.RED)
                    .mapToInt(w -> w.getWeight())
                    .sum();
    
        List<User> userList = Stream.
            of(arrayList).
            map(person -> new User(person.getName())).
            collect(Collectors.toList());
    
        //peek 和map类似-但是他更强大-它对每个元素执行操作并返回一个新的 Stream
        Stream.of("one", "two", "three", "four") 
        .filter(e -> e.length() > 3) 
        .peek(e -> System.out.println("Filtered value: " + e)) 
        .map(String::toUpperCase) 
        .peek(e -> System.out.println("Mapped value: " + e)) 
        .collect(Collectors.toList());
    
        //limit 返回 Stream 的前面 n 个元素;
        //skip 则是扔掉前 n 个元素
        List<String> personList2 = persons.stream()
        .map(Person::getName)
        .limit(10)
        .skip(3)
        .collect(Collectors.toList()); 
        System.out.println(personList2);

    And some operations of Kotlin There are some types of symbols. Now that projects are all Kotlin, generally there is no need for this stuff. If you are an old Java project, I hope that the filter map collection can use the stream API to easily convert data.

    AGP7 compilation problem

    When the previous project was compiled, since our compatibility code was written in the build.gradle of the submodule, the app module would be merged successfully after compilation, and there would be no problem running. . However, after the project was upgraded to AGP some time ago, the specified API cannot be run. You need to add a compatible code block in the build.gradle of the running module app to run it. This is recorded here.

        ...
        repositories {
            maven { url &#39;https://maven.aliyun.com/nexus/content/groups/public/&#39; }
            google()
            maven { url &#39;https://jitpack.io&#39; }
            mavenCentral()
            jcenter()
        }
    
        dependencies {
            classpath &#39;com.android.tools.build:gradle:7.0.3&#39;
    
            classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    
            classpath &#39;com.google.gms:google-services:4.3.8&#39;
        }
       ...

    app build.gradle needs to be added

    android {
      defaultConfig {
        multiDexEnabled true
      }
    
      compileOptions {
        // Flag to enable support for the new language APIs
        coreLibraryDesugaringEnabled true
    
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
      }
    }
    
    dependencies {
      coreLibraryDesugaring &#39;com.android.tools:desugar_jdk_libs:1.1.5&#39;
    }

    The above is the detailed content of How to use Java high version API in Android. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    JVM performance vs other languagesJVM performance vs other languagesMay 14, 2025 am 12:16 AM

    JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

    Java Platform Independence: Examples of useJava Platform Independence: Examples of useMay 14, 2025 am 12:14 AM

    JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

    JVM Architecture: A Deep Dive into the Java Virtual MachineJVM Architecture: A Deep Dive into the Java Virtual MachineMay 14, 2025 am 12:12 AM

    TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

    JVM: Is JVM related to the OS?JVM: Is JVM related to the OS?May 14, 2025 am 12:11 AM

    JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

    Java: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceJava: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceMay 14, 2025 am 12:05 AM

    Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

    Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

    JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

    What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

    Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

    Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

    The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Article

    Hot Tools

    SublimeText3 English version

    SublimeText3 English version

    Recommended: Win version, supports code prompts!

    PhpStorm Mac version

    PhpStorm Mac version

    The latest (2018.2.1) professional PHP integrated development tool

    SAP NetWeaver Server Adapter for Eclipse

    SAP NetWeaver Server Adapter for Eclipse

    Integrate Eclipse with SAP NetWeaver application server.

    Safe Exam Browser

    Safe Exam Browser

    Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

    WebStorm Mac version

    WebStorm Mac version

    Useful JavaScript development tools