├── .gitignore ├── .travis.yml ├── CONTRIBUTING.md ├── LICENSE ├── LICENSE-examples ├── PATENTS ├── README.md ├── build.gradle ├── demoapp ├── .gitignore ├── README.md ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── assets │ ├── LazyLoadedModule │ │ └── lazylibrary.dex │ └── LazyLoadedService │ │ └── lazyservice.apk │ ├── java │ └── com │ │ └── instagram │ │ └── lazyload │ │ └── demoapp │ │ ├── LibraryProxy.java │ │ ├── MainActivity.java │ │ ├── ManifestReader.java │ │ └── ServiceProxy.java │ └── res │ ├── layout │ └── activity_main.xml │ ├── mipmap-hdpi │ └── ic_launcher.png │ ├── mipmap-mdpi │ └── ic_launcher.png │ ├── mipmap-xhdpi │ └── ic_launcher.png │ ├── mipmap-xxhdpi │ └── ic_launcher.png │ ├── mipmap-xxxhdpi │ └── ic_launcher.png │ └── values │ ├── colors.xml │ ├── strings.xml │ └── styles.xml ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── ig-lazy-module-loader ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── main │ ├── AndroidManifest.xml │ └── java │ │ └── com │ │ └── instagram │ │ └── lazyload │ │ └── base │ │ ├── ActivityLike.java │ │ ├── CustomClassLoader.java │ │ ├── DefaultModuleStore.java │ │ ├── DefautlLoaderAlgorithm.java │ │ ├── DexAdder.java │ │ ├── FileIOUtils.java │ │ ├── FragmentLike.java │ │ ├── LazyLoadListener.java │ │ ├── LazyLoadingException.java │ │ ├── LazyModuleLoader.java │ │ ├── LazyModuleLoaderHelper.java │ │ ├── LoaderAlgorithm.java │ │ ├── ModuleManifest.java │ │ ├── ModuleManifestReader.java │ │ ├── ModulePathsAndDependencies.java │ │ ├── ModuleStore.java │ │ ├── NativeModuleLoader.java │ │ ├── ServiceLike.java │ │ └── SupportFragmentLike.java │ └── test │ └── java │ └── com │ └── instagram │ └── lazyload │ └── base │ └── LazyModuleLoaderTest.java ├── lazyloadedlibrary ├── .gitignore ├── build.gradle └── src │ └── main │ └── java │ └── com │ └── instagram │ └── lazyload │ └── lazyloadedlibrary │ └── LazyLoadedClass.java ├── lazyloadedservice ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ └── java │ └── com │ └── instagram │ └── lazyload │ └── lazyloadedservice │ └── LazyLoadedService.java └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | local.properties 4 | .idea 5 | .DS_Store 6 | build 7 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: android 2 | 3 | android: 4 | components: 5 | - build-tools-26.0.1 6 | - android-26 7 | licenses: 8 | - 'android-sdk-license-.+' 9 | 10 | before_script: 11 | - ./gradlew assemble 12 | 13 | script: 14 | - ./gradlew check 15 | 16 | jdk: 17 | - oraclejdk8 18 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to ig-lazy-module-loader 2 | We want to make contributing to this project as easy and transparent as 3 | possible. 4 | 5 | ## Pull Requests 6 | We actively welcome your pull requests. 7 | 8 | 1. Fork the repo and create your branch from `master`. 9 | 2. If you've added code that should be tested, add tests. 10 | 3. If you've changed APIs, update the documentation. 11 | 4. Ensure the test suite passes. 12 | 5. Make sure your code lints. 13 | 6. If you haven't already, complete the Contributor License Agreement ("CLA"). 14 | 15 | ## Contributor License Agreement ("CLA") 16 | In order to accept your pull request, we need you to submit a CLA. You only need 17 | to do this once to work on any of Facebook's open source projects. 18 | 19 | Complete your CLA here: 20 | 21 | ## Issues 22 | We use GitHub issues to track public bugs. Please ensure your description is 23 | clear and has sufficient instructions to be able to reproduce the issue. 24 | 25 | Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe 26 | disclosure of security bugs. In those cases, please go through the process 27 | outlined on that page and do not file a public issue. 28 | 29 | ## Coding Style 30 | * 2 spaces for indentation rather than tabs 31 | * 80 character line length 32 | 33 | ## License 34 | By contributing to ig-lazy-module-loader, you agree that your contributions will be licensed 35 | under its BSD license. -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | BSD License 2 | 3 | For ig-lazy-module-loader software 4 | 5 | Copyright (c) 2017-present, Facebook, Inc. All rights reserved. 6 | 7 | Redistribution and use in source and binary forms, with or without modification, 8 | are permitted provided that the following conditions are met: 9 | 10 | * Redistributions of source code must retain the above copyright notice, this 11 | list of conditions and the following disclaimer. 12 | 13 | * Redistributions in binary form must reproduce the above copyright notice, 14 | this list of conditions and the following disclaimer in the documentation 15 | and/or other materials provided with the distribution. 16 | 17 | * Neither the name Facebook nor the names of its contributors may be used to 18 | endorse or promote products derived from this software without specific 19 | prior written permission. 20 | 21 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 22 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 23 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 24 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 25 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 26 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 27 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 28 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 29 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 30 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------------------- /LICENSE-examples: -------------------------------------------------------------------------------- 1 | Copyright (c) 2017-present, Facebook, Inc. All rights reserved. 2 | 3 | The examples provided by Facebook are for non-commercial testing and evaluation 4 | purposes only. Facebook reserves all rights not expressly granted. 5 | 6 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 7 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 8 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 9 | FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 10 | ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 11 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 12 | -------------------------------------------------------------------------------- /PATENTS: -------------------------------------------------------------------------------- 1 | Additional Grant of Patent Rights Version 2 2 | 3 | "Software" means the ig-lazy-module-loader software contributed by Facebook, Inc. 4 | 5 | Facebook, Inc. ("Facebook") hereby grants to each recipient of the Software 6 | ("you") a perpetual, worldwide, royalty-free, non-exclusive, irrevocable 7 | (subject to the termination provision below) license under any Necessary 8 | Claims, to make, have made, use, sell, offer to sell, import, and otherwise 9 | transfer the Software. For avoidance of doubt, no license is granted under 10 | Facebook’s rights in any patent claims that are infringed by (i) modifications 11 | to the Software made by you or any third party or (ii) the Software in 12 | combination with any software or other technology. 13 | 14 | The license granted hereunder will terminate, automatically and without notice, 15 | if you (or any of your subsidiaries, corporate affiliates or agents) initiate 16 | directly or indirectly, or take a direct financial interest in, any Patent 17 | Assertion: (i) against Facebook or any of its subsidiaries or corporate 18 | affiliates, (ii) against any party if such Patent Assertion arises in whole or 19 | in part from any software, technology, product or service of Facebook or any of 20 | its subsidiaries or corporate affiliates, or (iii) against any party relating 21 | to the Software. Notwithstanding the foregoing, if Facebook or any of its 22 | subsidiaries or corporate affiliates files a lawsuit alleging patent 23 | infringement against you in the first instance, and you respond by filing a 24 | patent infringement counterclaim in that lawsuit against that party that is 25 | unrelated to the Software, the license granted hereunder will not terminate 26 | under section (i) of this paragraph due to such counterclaim. 27 | 28 | A "Necessary Claim" is a claim of a patent owned by Facebook that is 29 | necessarily infringed by the Software standing alone. 30 | 31 | A "Patent Assertion" is any lawsuit or other action alleging direct, indirect, 32 | or contributory infringement or inducement to infringe any patent, including a 33 | cross-claim or counterclaim. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Ig-Lazy-Module-Loader 2 | 3 | [![Build Status][build-status-svg]][build-status-link] 4 | [![Maven Central][maven-svg]][maven-link] 5 | [![License][license-svg]][license-link] 6 | 7 | 8 | This library helps with loading modules (features) in Android apps on demand, whenever needed. Before this library can be used a module needs to be compiled to a separate jar/dex or apk file. 9 | 10 | Right now, the library supports java libraries and android libraries which don't rely on android resources. Support for lazy loading resources may be added later. 11 | 12 | In the demo app there's two examples of lazy loading: 13 | - java library - compiled first to jar and then to dex file 14 | - android library - compiled to apk file (in this example I use Android service) 15 | 16 | ## Benefits 17 | Lazy loading of a feature vs having it in the main main executable file brings these benefits: 18 | - feature is loaded in memory only when really needed. It offloads code from the main executable file which remains smaller which guarantees better cold start time. On Dalvik it offloads methods off the main dex file decreasing performance penalty of multi dex 19 | - feature code is clustered together in memory as it lives in one file and it provides most optimal execution in terms of memory access 20 | - less disk space is used if some features remain unused because code is not uncompressed 21 | - it may improve developer velocity where many developers concurrently work on the same codebase by providing very rigid isolation between features 22 | - module hotswapping may be implemented allowing for faster development without restarting the app 23 | 24 | ## Tactics around lazy loading 25 | Not every module or a feature is a good candidate to be lazily loaded as lazy loading may incur small latency on the first load. 26 | 27 | Features used during cold start would ideally live in the main execubtale file (classes.dex) as this would ensure the most efficient app start. Anything that is outside cold start or, in general, is a less core to the app could be lazily loaded. 28 | 29 | There are some tactics around when to trigger lazy loading. Generally speaking a module should be loaded when it is expected to be used in the near future. To make sure the loading latency does not worsen user experience these tactics can be applied: 30 | - loading a module in the background when user is one click away from the module - it may mean that module remains unused if user doesn't decide to click into that feature or navigates back. But if there's high probability of clicking into that module then it's a well working solution 31 | - loading a module once user navigates into the module. If loading latency is small (below 50ms) for majority of cases (e.g. p99) then code can block on loading and once it's done navigate into the feature. Otherwise a simple spinner or a progress bar can be displayed so that app does not appear as frozen. 32 | - some modules are by nature asynchronous and this eases lazy loading as it will be the part of the asynchronous loading. An example of such module from Instagram domain is video player which runs in a secondary process. Instagram initially shows a screenshot of the video while video loads in the background (often times is fetched from the network). Lazy loading would happen in that secondary process and be completely transparent to users. 33 | 34 | Also, the first time module is loaded after app install or app upgrade the loading latency will be higher because of dexopt or dex2oat being run (which is compiling and optimizing code for faster execution). This case, although it happens rarely compared to every cold start (e.g. once a week - after app upgade) it usually forces to apply more conservative approach (e.g. loading one click away) especially for modules of significate size (at least couple of hundred kilobytes). 35 | 36 | ## Getting started 37 | The easiest way is to look at the demoapp. It's an Android app that shows a screen with two buttons to lazy load a java library and android library: 38 | 39 | Each feature has a Proxy object which lives in the main app. Proxy handles lazy loading of the actual module and delegates calls to it: 40 | ```java 41 | class ServiceProxy extends Service { 42 | 43 | private ServiceLike mLazyLoadedService; 44 | 45 | void onCreate() { 46 | try { 47 | mLazyLoadedService = LazyModuleLoaderHelper 48 | .createLoaderWithoutNativeLibrariesSupport(this, new ManifestReader(), mLazyLoadListener) 49 | .loadServiceModule(ManifestReader.LazyLoadedService, CLASS_NAME); 50 | } catch (LazyLoadingException e) { 51 | Log.e(TAG, "Failed to lazy loaded a service", e); 52 | } 53 | // delegate calls once lazy loading finished 54 | mLazyLoadedService.onCreate(); 55 | } 56 | 57 | public IBinder onBind(Intent intent) { 58 | // keep delegating calls 59 | return mLazyLoadedService.onBind(intent); 60 | } 61 | // ... 62 | } 63 | ``` 64 | *** 65 | In the main app an implementation for ModuleManifestReader interface must be added which provides basic metadata about lazy loaded module 66 | ```java 67 | class ManifestReader implements ModuleManifestReader { 68 | 69 | public final static String LazyLoadedService = "LazyLoadedService"; 70 | 71 | // Those file need to be placed in the assets/ folder 72 | private final static String ServiceFileName = "lazyservice.apk"; 73 | 74 | // Hash of the module may be useful when versioning of modules needs to be added 75 | private final static String ModuleHash = "null"; 76 | 77 | @Override 78 | public ModuleManifest readModuleManifest(String moduleName) throws IOException { 79 | if (moduleName.equals(LazyLoadedService)) { 80 | return new ModuleManifest.Builder(moduleName).setModuleHash(ModuleHash).setDexFileName 81 | (ServiceFileName).build(); 82 | } else { 83 | // ... 84 | } 85 | } 86 | } 87 | ``` 88 | *** 89 | Each compiled lazy loaded module must be placed in the assets folder. It could either be a dex file (for a java library) or apk (for android library). Right now there's no support for aar files. In the demoapp _lazylibrary.dex_ is compiled file of _lazyloadedlibrary_ and _lazyservice.apk_ is compiled file of _lazyloadedservice_ - both included in this repo: 90 | ``` 91 | $ ls LazyLoader/demoapp/src/main/assets/* 92 | src/main/assets//LazyLoadedModule/lazylibrary.dex 93 | src/main/assets//LazyLoadedService/lazyservice.apk 94 | ``` 95 | For java library you need to compile the library to a jar file and and then to dex file using dx tool. You also need to add a **provided** dependency in the gradle build file: 96 | ``` 97 | dx --dex --output=lazyloadedlibrary.dex lazyloadedlibrary.jar 98 | ``` 99 | ```groovy 100 | dependencies { 101 | provided project(':lazyloadedlibrary') 102 | } 103 | ``` 104 | 105 | ## Compile a AAR 106 | 107 | ``` 108 | ./gradlew clean assembleRelease 109 | ``` 110 | Outputs can be found in ig-lazy-module-loader/build/outputs/ 111 | 112 | ## Run the Tests 113 | ``` 114 | ./gradlew clean test 115 | ``` 116 | 117 | ## Gradle 118 | 119 | Add this to your build.gradle file: 120 | ``` groovy 121 | allprojects { 122 | repositories { 123 | maven { url 'https://jitpack.io' } 124 | } 125 | } 126 | 127 | dependencies { 128 | compile 'com.github.instagram:ig-lazy-module-loader:master-SNAPSHOT' 129 | } 130 | ``` 131 | 132 | ## Other Instagram Android Projects 133 | - [ig-json-parser][ig-json-parser-link] 134 | - [ig-disk-cache][ig-disk-cache-link] 135 | 136 | ## Instagram Engineering Blog 137 | - [Engineering Blog][eng-blog] 138 | 139 | ## License 140 | 141 | ``` 142 | Copyright (c) 2017-present, Facebook, Inc. 143 | All rights reserved. 144 | 145 | This source code is licensed under the BSD-style license found in the 146 | LICENSE file in the root directory of this source tree. An additional grant 147 | of patent rights can be found in the PATENTS file in the same directory. 148 | ``` 149 | 150 | [eng-blog]: http://engineering.instagram.com/ 151 | 152 | [build-status-svg]: https://travis-ci.org/Instagram/ig-disk-cache.svg 153 | [build-status-link]: https://travis-ci.org/Instagram/ig-disk-cache 154 | [maven-svg]: https://maven-badges.herokuapp.com/maven-central/com.instagram.igdiskcache/ig-disk-cache/badge.svg?style=flat 155 | [maven-link]: https://maven-badges.herokuapp.com/maven-central/com.instagram.igdiskcache/ig-disk-cache 156 | 157 | [ig-json-parser-link]: https://github.com/Instagram/ig-json-parser 158 | [ig-disk-cache-link]: https://github.com/Instagram/ig-disk-cache 159 | 160 | [license-svg]: https://img.shields.io/badge/license-BSD-lightgrey.svg 161 | [license-link]: https://github.com/Instagram/ig-disk-cache/blob/master/LICENSE -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | repositories { 5 | jcenter() 6 | } 7 | dependencies { 8 | classpath 'com.android.tools.build:gradle:2.3.0' 9 | classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5' 10 | } 11 | } 12 | 13 | allprojects { 14 | repositories { 15 | jcenter() 16 | } 17 | } 18 | 19 | task clean(type: Delete) { 20 | delete rootProject.buildDir 21 | } 22 | -------------------------------------------------------------------------------- /demoapp/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /demoapp/README.md: -------------------------------------------------------------------------------- 1 | # Demo app 2 | 3 | This is a simple Android app which allows to load upon a button click either a java library or android library which contains a Service. 4 | 5 | ### Run the demo 6 | ``` sh 7 | # Build the demo app from the 8 | gradle clean installdebug 9 | # Run the demo on device 10 | adb shell am start -n "adb shell am start -n "com.instagram.lazyload.demoapp/.MainActivity"" 11 | ``` 12 | -------------------------------------------------------------------------------- /demoapp/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 26 5 | buildToolsVersion "26.0.1" 6 | defaultConfig { 7 | applicationId "com.instagram.lazyload.demoapp" 8 | minSdkVersion 15 9 | targetSdkVersion 26 10 | versionCode 1 11 | versionName "1.0" 12 | } 13 | buildTypes { 14 | release { 15 | minifyEnabled false 16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 17 | } 18 | } 19 | lintOptions { 20 | abortOnError false 21 | } 22 | } 23 | 24 | dependencies { 25 | compile project(':ig-lazy-module-loader') 26 | provided project(':lazyloadedlibrary') 27 | compile fileTree(dir: 'libs', include: ['*.jar']) 28 | compile 'com.android.support:appcompat-v7:26.+' 29 | compile 'com.android.support.constraint:constraint-layout:1.0.2' 30 | } 31 | -------------------------------------------------------------------------------- /demoapp/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /opt/android_sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | 19 | # Uncomment this to preserve the line number information for 20 | # debugging stack traces. 21 | #-keepattributes SourceFile,LineNumberTable 22 | 23 | # If you keep the line number information, uncomment this to 24 | # hide the original source file name. 25 | #-renamesourcefileattribute SourceFile 26 | -------------------------------------------------------------------------------- /demoapp/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /demoapp/src/main/assets/LazyLoadedModule/lazylibrary.dex: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookarchive/ig-lazy-module-loader/40f7d5d96569343018b0dd2885c308b22610cb8b/demoapp/src/main/assets/LazyLoadedModule/lazylibrary.dex -------------------------------------------------------------------------------- /demoapp/src/main/assets/LazyLoadedService/lazyservice.apk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookarchive/ig-lazy-module-loader/40f7d5d96569343018b0dd2885c308b22610cb8b/demoapp/src/main/assets/LazyLoadedService/lazyservice.apk -------------------------------------------------------------------------------- /demoapp/src/main/java/com/instagram/lazyload/demoapp/LibraryProxy.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017-present, Facebook, Inc. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under the license found in the 6 | * LICENSE-examples file in the root directory of this source tree. 7 | */ 8 | 9 | package com.instagram.lazyload.demoapp; 10 | 11 | import android.content.Context; 12 | import android.util.Log; 13 | 14 | import com.instagram.lazyload.base.LazyLoadListener; 15 | import com.instagram.lazyload.base.LazyModuleLoaderHelper; 16 | import com.instagram.lazyload.lazyloadedlibrary.LazyLoadedClass; 17 | 18 | public class LibraryProxy { 19 | 20 | private final static String TAG = "LibraryProxy"; 21 | 22 | private final static LazyLoadListener mLazyLoadListener = new LazyLoadListener() { 23 | @Override 24 | public void moduleLazilyLoaded(String module, long loadTimeMs) { 25 | Log.i(TAG, "Library successfully loaded in " + loadTimeMs + "ms"); 26 | } 27 | 28 | @Override 29 | public void moduleLazilyInstalled(String module, long loadTimeMs) { 30 | Log.i(TAG, "Library successfully installed in " + loadTimeMs + "ms"); 31 | } 32 | }; 33 | 34 | private static LibraryProxy sInstance; 35 | private LazyLoadedClass mLazyLoadedClass; 36 | 37 | private LibraryProxy() { 38 | mLazyLoadedClass = new LazyLoadedClass(); 39 | } 40 | 41 | public static LibraryProxy getsInstance(Context context) { 42 | if (sInstance != null) { 43 | return sInstance; 44 | } 45 | 46 | installLibrary(context); 47 | sInstance = new LibraryProxy(); 48 | return sInstance; 49 | } 50 | 51 | private static void installLibrary(Context context) { 52 | try { 53 | LazyModuleLoaderHelper.createLoaderWithoutNativeLibrariesSupport( 54 | context, 55 | new ManifestReader(), 56 | mLazyLoadListener).installModule(ManifestReader.LazyLoadedModule); 57 | } catch (Exception e) { 58 | Log.e(TAG, "Failed to install a module", e); 59 | } 60 | } 61 | 62 | public void runComplicatedAlgorithms() { 63 | mLazyLoadedClass.runComplexAlgorithms(); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /demoapp/src/main/java/com/instagram/lazyload/demoapp/MainActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017-present, Facebook, Inc. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under the license found in the 6 | * LICENSE-examples file in the root directory of this source tree. 7 | */ 8 | 9 | package com.instagram.lazyload.demoapp; 10 | 11 | import android.content.Intent; 12 | import android.os.Bundle; 13 | import android.support.v7.app.AppCompatActivity; 14 | import android.view.View; 15 | 16 | public class MainActivity extends AppCompatActivity { 17 | 18 | @Override 19 | protected void onCreate(Bundle savedInstanceState) { 20 | super.onCreate(savedInstanceState); 21 | setContentView(com.instagram.lazyload.demoapp.R.layout.activity_main); 22 | } 23 | 24 | @Override 25 | protected void onStart() { 26 | super.onStart(); 27 | 28 | findViewById(R.id.button_service).setOnClickListener(new View 29 | .OnClickListener() { 30 | @Override 31 | public void onClick(View view) { 32 | startService(new Intent(MainActivity.this, ServiceProxy.class)); 33 | } 34 | }); 35 | 36 | findViewById(R.id.button_library).setOnClickListener(new View 37 | .OnClickListener() { 38 | @Override 39 | public void onClick(View view) { 40 | LibraryProxy.getsInstance(MainActivity.this).runComplicatedAlgorithms(); 41 | } 42 | }); 43 | } 44 | 45 | @Override 46 | protected void onStop() { 47 | super.onStop(); 48 | stopService(new Intent(MainActivity.this, ServiceProxy.class)); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /demoapp/src/main/java/com/instagram/lazyload/demoapp/ManifestReader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017-present, Facebook, Inc. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under the license found in the 6 | * LICENSE-examples file in the root directory of this source tree. 7 | */ 8 | 9 | package com.instagram.lazyload.demoapp; 10 | 11 | import com.instagram.lazyload.base.ModuleManifest; 12 | import com.instagram.lazyload.base.ModuleManifestReader; 13 | 14 | import java.io.IOException; 15 | 16 | /** 17 | * Class that creates manifests for lazy loaded modules. Manifests contains metadata about modules. 18 | */ 19 | class ManifestReader implements ModuleManifestReader { 20 | 21 | public final static String LazyLoadedService = "LazyLoadedService"; 22 | public final static String LazyLoadedModule = "LazyLoadedModule"; 23 | 24 | // Those files need to be placed in the assets/ folder of demo app 25 | private final static String ServiceFileName = "lazyservice.apk"; 26 | private final static String LibraryFileName = "lazylibrary.dex"; 27 | 28 | // Hash of the module may be useful when versioning of modules needs to be added 29 | private final static String ModuleHash = "null"; 30 | 31 | @Override 32 | public ModuleManifest readModuleManifest(String moduleName) throws IOException { 33 | if (moduleName.equals(LazyLoadedService)) { 34 | return new ModuleManifest.Builder(moduleName).setModuleHash(ModuleHash).setDexFileName 35 | (ServiceFileName).build(); 36 | } else if (moduleName.equals(LazyLoadedModule)) { 37 | return new ModuleManifest.Builder(moduleName).setModuleHash(ModuleHash).setDexFileName 38 | (LibraryFileName).build(); 39 | } else { 40 | return null; 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /demoapp/src/main/java/com/instagram/lazyload/demoapp/ServiceProxy.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017-present, Facebook, Inc. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under the license found in the 6 | * LICENSE-examples file in the root directory of this source tree. 7 | */ 8 | 9 | package com.instagram.lazyload.demoapp; 10 | 11 | import android.app.Service; 12 | import android.content.Intent; 13 | import android.os.IBinder; 14 | import android.util.Log; 15 | 16 | import com.instagram.lazyload.base.LazyLoadListener; 17 | import com.instagram.lazyload.base.LazyLoadingException; 18 | import com.instagram.lazyload.base.LazyModuleLoaderHelper; 19 | import com.instagram.lazyload.base.ServiceLike; 20 | 21 | /** 22 | * The only responsibility of this service is to load a implementation of the real service (from 23 | * a file from assets folder) and delegate all the calls to that service. 24 | *

25 | * This service is located in the main classes.dex file and can be created any time (no need to 26 | * load a service form secondary dex file before creating this service). 27 | */ 28 | public class ServiceProxy extends Service { 29 | 30 | private final static String TAG = "ServiceProxy"; 31 | 32 | private static final String CLASS_NAME = 33 | "com.instagram.lazyload.lazyloadedservice.LazyLoadedService"; 34 | 35 | private static final LazyLoadListener mLazyLoadListener = new LazyLoadListener() { 36 | @Override 37 | public void moduleLazilyLoaded(String module, long loadTimeMs) { 38 | Log.i(TAG, "Service successfully loaded in " + loadTimeMs + "ms"); 39 | } 40 | 41 | @Override 42 | public void moduleLazilyInstalled(String module, long loadTimeMs) { 43 | Log.i(TAG, "Service successfully installed in " + loadTimeMs + "ms"); 44 | } 45 | }; 46 | 47 | private ServiceLike mLazyLoadedService; 48 | 49 | @Override 50 | public void onCreate() { 51 | try { 52 | mLazyLoadedService = LazyModuleLoaderHelper.createLoaderWithoutNativeLibrariesSupport( 53 | this, 54 | new ManifestReader(), 55 | mLazyLoadListener).loadServiceModule( 56 | ManifestReader.LazyLoadedService, 57 | CLASS_NAME); 58 | } catch (LazyLoadingException e) { 59 | Log.e(TAG, "Failed to lazy loaded a service", e); 60 | } 61 | mLazyLoadedService.onCreate(); 62 | } 63 | 64 | @Override 65 | public IBinder onBind(Intent intent) { 66 | return mLazyLoadedService.onBind(intent); 67 | } 68 | 69 | @Override 70 | public boolean onUnbind(Intent intent) { 71 | return mLazyLoadedService.onUnbind(intent); 72 | } 73 | 74 | @Override 75 | public void onDestroy() { 76 | mLazyLoadedService.onDestroy(); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /demoapp/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 20 | 21 |