Android Hot Fix solution (Andfix)

Source: Internet
Author: User

Andfix Introduction Andfix is an online hot patch framework for Android apps. Using this framework, we are able to modify the bug in the app online without re-recurring version. Andfix is the abbreviation for "Android Hot-fix". The Andfix supports Android 2.3 to 6.0 versions and supports arm and X86 system architecture devices. Perfect support for Dalvik and art runtime. Andfix patch files are files that end in. Apatch. Andfix is Ali's Open source project. Https://github.com/alibaba/AndFix Small Example: Download the demo APK Http://120.55.185.35:8080/old.apkdemo, or scan the QR code below, Install the APK after running Andfixdemo, click on the "Prompt message" button, jump out of "not repaired Toast", click "Start Repair", the app will go to the remote server to download the patch update, probably will last a few seconds, wait a few seconds after the "prompt message" button, will pop up the repaired content

The actual operation does not need to click on the "Start Repair" button, in the demo in order to compare the effect, so add a button to control the actual operation of the detection needs to patch the program:
    1. Similar detection upgrade, in the Open app or a page to detect
    2. Server-side push (requires and server-side definition for more implementation details)

The advantages of Andfix are obvious.
    1. The patch pack is small (the above example, the patch pack is only a few k), the patching speed is fast
    2. After you've patched up, you don't have to call anymore.
Method of use: 1. Add dependency


2. Initialize the custom application and register the application in the Androidmanifest.xml


3. Patching in the activity, (the detection step is omitted here, the default is to download the patch and update directly, the actual development needs to check the version of the patch, update and delete the patch package, dynamic access to patch path, etc.)


4. The configuration has been completed here, the next with the formal key packaging, the generation of old.apk, put old.apk on the server, the project is on-line

5. After the project is on-line, there will be a variety of unexpected situations, (such as copy changes, urgent bugs, resulting in the app crash, such as trouble, the normal situation only for version upgrade), here to see the Andfix hot fix steps to modify the Showtoast method as an example


6. Now change the Showtoast method and package it, named fix.apk


7. Download the Apkpatch tool


8. Make Patch Pack, CD to directory, run apkpatch.bat-f fix.apk-t old.apk-o output1-k demo.jks-p 123456-a demo-e 123456

(Here-t for the old apk-f for the repaired Apk,-o for output directory-K for packaged key-p-E for password-A for alias)

9. The screen output added a modified toast method, while the directory under the new OUTPUT1 directory, click to see, where. Apatch for the real patch pack


10. Use the Dex2jar tool to turn the diff file into a jar file and view it with Jd.gui


In fact, this tool is more than two Dex files, analyze the modified place, and then generate a patch package

11. Name the. Apatch App.apatch upload to the server and wait for the client to patch


SOURCE Analysis: 1 First look at the initialization in application
@Override    publicvoidonCreate() {        super.onCreate();        // 初始化patch管理类        new PatchManager(this);        // 初始化patch版本        mPatchManager.init("2.0");        // 加载已经添加到PatchManager中的patch        mPatchManager.loadPatch();    }

2 constructs the Patchmanager object, looks at the code
publicPatchManager(Context context) {        mContext = context;        new//初始化AndFixManager,等会再介绍          //getFileDir 获取的是/data/data/<application package>/files        //在这里是 /data/data/<application package>/files/apatch        new File(mContext.getFilesDir(), DIR);        // 支持并发访问的有序的补丁集合        new ConcurrentSkipListSet<Patch>();        // ClassLoader的集合,同样也是基于线程安全的        new ConcurrentHashMap<String, ClassLoader>();    }

3 Initialize patch version, code
 Public void Init(String appversion) {//Detect patch storage paths again        if(!mpatchdir.exists () &&!mpatchdir.mkdirs ()) {//Make directory failLOG.E (TAG,"Patch dir create error.");return; }Else if(!mpatchdir.isdirectory ()) {//Not directoryMpatchdir.delete ();return; }//Use Sharedpreferences to get the version of PathSharedpreferences sp = mcontext.getsharedpreferences (Sp_name, context.mode_private); String ver = sp.getstring (sp_version,NULL);if(ver = =NULL|| !ver.equalsignorecase (appversion)) {//If this is the first use or inconsistent version, remove all patches, where equalsignorecase is ignored equalsCleanpatch ();//Storage versionSp.edit (). putstring (Sp_version, appversion). commit (); }Else{//Load PatchesInitpatchs (); }    }Private void Initpatchs() {file[] files = mpatchdir.listfiles (); for(File file:files)        {addpatch (file); }    }

4 loading patches that have been added to the Patchmanager, code
/** * Load Patch,call when application start * Written here is also very clear, when the program starts to call * /     Public void Loadpatch() {//load the generic class loader firstMloaders.put ("*", Mcontext.getclassloader ());//WildcardSet<string> Patchnames; list<string> classes;//Iterate over the structure of each patch pack patch hashmap<string, list<string>> ()        //In practice, there will only be one key, which is the name of the apk you modified, and the list contains the modified classname        //fix----[Cv.cocoa.com.andfixdemo.MainActivity_CF]         for(Patch Patch:mpatchs) {patchnames = Patch.getpatchnames (); for(String patchname:patchnames) {classes = patch.getclasses (Patchname);//Update patchesMandfixmanager.fix (Patch.getfile (), Mcontext.getclassloader (), classes); }        }    }

5. The initialization code in application is complete, and one of the Andfixmanager does not say, Andfixmanager before the construction, will do a compatibility test, placed in the Compat class, the code
 Public  class Compat {     Public Static BooleanisChecked =false; Public Static BooleanIssupport =false;/** * Whether support on the device * requires compatibility detection, the detection is not the YunOS phone, the SDK version must be between 2.3-6.0 * @return True if the device support Andfix * /     Public Static synchronized Boolean Issupport() {if(isChecked)returnIssupport; isChecked =true;//Andfix.setup () determine whether Dalvik or art virtual machine, to register the native method        if(!isyunos () && andfix.setup () && issupportsdkversion ()) {Issupport =true; }if(Inblacklist ()) {Issupport =false; }returnIssupport; }}
/** * Initialize * * @return True if initialize success * * Judgment is Dalvik or art virtual machine, and initialize Nativ  E's method, * * Official document says Https://developer.android.com/guide/practices/verifying-apps-art.html * You can verify which Runtime is on use by calling System.getproperty ("Java.vm.version").     If ART is on use, the property's value is "2.0.0" or higher. *       */     Public Static Boolean Setup() {Try{FinalString vmversion = System.getproperty ("Java.vm.version");BooleanIsart = vmversion! =NULL&& Vmversion.startswith ("2");intAPILevel = Build.VERSION.SDK_INT;returnSetup (Isart, APILevel); }Catch(Exception e) {LOG.E (TAG,"Setup", e);return false; }    }
6. Then look at the Andfixmanager code
//The key is here, after acquiring the class object, use reflection to get the modified methodPrivate void Fixclass(class<?> clazz, ClassLoader ClassLoader) {method of obtaining class by//java reflectionMethod[] methods = Clazz.getdeclaredmethods ();        Methodreplace Methodreplace;        String CLZ; String meth; for(Method method:methods) {//Find annotations for MethodreplaceMethodreplace = Method.getannotation (Methodreplace.class);if(Methodreplace = =NULL)Continue;//control above the DEMO,CLZ is cv.cocoa.com.andfixdemo.MainActivityCLZ = Methodreplace.clazz ();//control above the Demo,meth is ShowtoastMeth = Methodreplace.method ();if(!isempty (CLZ) &&!isempty (Meth)) {//Replacement methodReplacemethod (ClassLoader, CLZ, Meth, method); }        }    }/** * Replace method * * @param classLoader classLoader * @param CLZ class *
     
       @param Meth name of target method *
       @param method Source Method *
      *    Private void Replacemethod(ClassLoader ClassLoader, String clz, String meth, method) {Try{String key = Clz +"@"+ classloader.tostring (); Class<?> clazz = Mfixedclass.get (key);if(Clazz = =NULL) {//Class not loadclass<?> clzz = Classloader.loadclass (CLZ);//Initialize target classClazz = Andfix.inittargetclass (clzz); }if(Clazz! =NULL) {//Initialize class OKMfixedclass.put (key, Clazz); Method src = clazz.getdeclaredmethod (Meth, method.getparametertypes ());//method to invoke JNIAndfix.addreplacemethod (src, method); }        }Catch(Exception e) {LOG.E (TAG,"Replacemethod", e); }    }

Android Hot Fix solution (Andfix)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.