Android third-party app ad blocker enabled

Source: Internet
Author: User

Some time ago, the company made the application of the machine is equipped with bad advertising, seriously affect the child's customer's mental health, resulting in complaints. So there's the idea of developing an app similar to 360 ad masking. Well, that's the way it is, now cut into the subject.

There are a lot of security software on the market, and they can intercept third-party app ads in different ways, such as by using so injections to intercept pop-up ads .
Now let's look at the details of this approach:

To intercept, first we need to know how the ads are out, the original third-party applications are mostly to join the ad jar form to join the ad plugin, and then declare the ad service in Androidmanifest or execute the advertising API in the program, The ad plugin then goes through the HTTP request to load the ad . In Java, there are four kinds of interfaces to access the network, such as the Apache HTTP library (described below), these methods will first get the domain name address through the Getaddrinfo function, and then connect to the server through the Connect function to read the advertisement information.

  1. WebView (source file in Frameworks/base/core/java/android/webkit/webview.java). Through the WebView class of void Loadurl (string url), void PostURL (string url, byte[] postdata), void LoadData (String data, String MimeType , string encoding), void Loaddatawithbaseurl (String baseUrl, String data, String MimeType, String encoding, String Historyu RL), void Evaluatejavascript (String script, Valuecallback Resultcallback), and other loading pages.
  2. Apache-http (source directory in external/apache-http/, HttpGet and HttpPost classes). by external/apache-http/src/org/apache/http/impl/client/ HttpResponse execute for Defaultrequestdirector class in Defaultrequestdirector.java (Httphost target, HttpRequest request, HttpContext context) method performs the action of the network being accessed.
  3. Okhttp (source directory in external/okhttp/). Through the private of the HttpEngine class in External/okhttp/okhttp/src/main/java/com/squareup/okhttp/internal/http/httpengine.java void Connect (Request request) throws IOException method to connect to the network.
  4. URL (source code in Libcore/luni/src/main/java/java/net/url.java). URLConnection OpenConnection () throws through the URL class in Libcore/luni/src/main/java/java/net/url.java The IOException method connects the network with the URLConnection openconnection (proxy) throws IOException method.

Then the dynamic library injection, specifically what is the dynamic library injection, and how to inject, there are many articles on the web, here is not introduced. Dynamic library injection interception, mainly interception getaddrinfo, according to conditional return error to intercept network requests, to achieve interception. However, it is important to note that before you intercept, make sure that the dynamic library you are intercepting is the one you need to intercept? For example, a program calls the dynamic library Bo and Co, and Bo and co all call the Connect function, at which point the request to intercept Bo needs to be injected into the Bo Dynamic library and modify the got table instead of being injected into the Co.

Block HTTP ads in most ad packages, the application first downloads the ad data through the Apache HTTP library or the HTTP method in the JDK, and then displays it through WebView. This approach enables AD address interception by injecting/system/lib/libjavacore.so into the interception process.

Block WebView Advertising plug-ins can also be directly through the WebView load URL, through the analysis of webview loading process, it is known that its network processing process is given to the Libchromium_net library to complete. Thus, by injecting libjavacore.so, it is impossible to intercept, but to inject into/system/lib/libchromium_net.so.

This is a way to intercept third-party app ads completely, but there are some problems:

1. Advertisers can invoke system getaddrinfo with connect to implement their own dynamic library of parsing and connecting processes by JNI, thus skipping the libjavacore.so causes the interception to be invalid.
2. Block WebView mode ads Although you can not display ads, but usually still have a floating box that says "page cannot open", thus affecting aesthetics.
3. The most important thing is that we do not have root access to the machine!!

The third problem has directly led to the abandonment of this injection approach.
After coming and coming for a while, it is currently using the Android system to locally scan third-party app advertising forms. What to do, please look down!

If you are not familiar with this approach, it is recommended to take a look at this Android system scan with advertising app.

So the specific ad plugin scanning scheme is matching package name + class name form:
1. Scan all local third-party apps, list all classes in an app, match package name + class name to AD plugin feature library ;
2. Apply the matching ad features to the application, and provide the incoming interface through the system to set these rules in. (Of course, the system code is needed to change, do some processing, mainly in the above introduction of the several types of access to the network to do the judgment processing).

The key to this scheme is the improvement of the advertising feature library, the more the collection of Ad plugin feature library, the more accurate the scanned ad plugin can be. Fortunately, the company has several great gods, have done similar things, so the work is more simple.

Get third-party apps:

   /** * Inquiry machine not in the company application * /       PublicList<packageinfo>Getalllocalinstalledapps() {list<packageinfo> apps =NewArraylist<packageinfo> ();if(Pmanager = =NULL){returnApps }//Get all appslist<packageinfo> paklist = Pmanager.getinstalledpackages (0); for(inti =0; I < paklist.size (); i++) {PackageInfo Pak = (packageinfo) paklist.get (i);//Shield off company internal applications           //...           //Determine if a non-system preinstalled application            if((Pak.applicationInfo.flags & Pak.applicationInfo.FLAG_SYSTEM) <=0) {//Customs applicationsApps.add (Pak); }          }returnApps }

Get ad features for an app:

public static list<String> Getclassnamebydex (Context Context,StringPackageName) {list<String> datalist =Newarraylist<String> ();StringPath =NULL;Try{path = Context.getpackagemanager (). Getapplicationinfo (PackageName,0). SourceDir;//Get the APK path for a program}Catch(Namenotfoundexception e)        {E.printstacktrace (); }Try{if(Textutils.isempty (path)) {returnDataList } dexfile Dexfile =NewDexfile (path);//Get dex file of APKenumeration<String> entries = dexfile.entries (); while(Entries.hasmoreelements ()) {// Travel All Classes                StringClassName = (String) entries.nextelement ();StringTotalname = PackageName +"."+classname;            Datalist.add (Totalname); }        }Catch(IOException e)        {E.printstacktrace (); }returnDataList }

Match all the class names in your app to the feature library:

 for(PackageInfo info:infolsit) {if(Info = =NULL) {Continue; } data = Getclassnamebydex (Context,info.packagename);if(Data = =NULL) {LOG.D (TAG,"Getadflagforlocalapp () class name resolution Error"+info.packagename);Continue; } Sgpgmap =Newhashmap<String,String> (); for(StringClsname:data) { for(Adsinfo adinfo:flaglist) {StringFlag = Adinfo.getadflag ();//A logo for the AD sample library                StringADPG = Adinfo.getadname ();//AD sample library for a package name                if(Clsname.contains (ADPG)) {//Match the class name with the match in the ad feature library to see if the relationship is includedSgpgmap.put (Flag,info.packagename); }            }        }if(Sgpgmap.size () >0){//adspginfo How many identities are included in a corresponding applicationAdspginfo =NewAdspginfo (Info.packagename, Sgpgmap);        Pglist.add (Adspginfo); }    }

PS: In the match, there is a very attention to the point, sometimes the class name matching is not allowed, or will miss some ads, so should add the package name, and then to match the character library match, so as to hundred no leakage.

In this example, a reference to the characteristics of intelligent advertising (feature display form can be customized, as long as it conforms to its own analytical strategy):

ads.banner.zhidian#指智广告#com/adzhidian/#ad.zhidian3g.cn
    • Ads.banner.zhidian for this type of advertising logo, mainly to match when the application of the corresponding identity of the simplicity, do not have to follow a group of features run around.
    • The name of the ad for smart ads
    • com/adzhidian/The ad is used to match the name of the class in the app, and when one (package name + class name) contains the match, the app contains the ad
    • ad.zhidian3g.cn A rule feature that needs to be passed to the system.

After matching all of the application's rule characteristics, the next need to pass to the system, the system will meet the requirements of several interfaces provided. This involves modifying the system layer code, I will mainly talk about the implementation of ideas, will post a few key code.
Implementation of the idea: the system according to the application Layer incoming application package name and rules, the cache, at the WebView or HTTP request, it is judged processing.

Add an app Rule interface:

/** * Add Adblock URL of package pkgname * / Private Boolean Addadblockurlinner(string pkgname, string url) {synchronized(madblockentries) {hashmap<string, urlentry> pkgentry = Madblockentries.get (pkgname);if(Pkgentry = =NULL) {Pkgentry =NewHashmap<string, urlentry> ();if(Pkgentry = =NULL) {SLOG.E (TAG,"Addadblockurl (): New hashmap<string, urlentry> () fail!");return false;     } madblockentries.put (Pkgname, pkgentry); } Urlentry entry = Pkgentry.get (URL);if(Entry = =NULL) {pkgentry.put (URL,NewUrlentry (0,false)); }Else{entry.deleted =false; }   }return true;}

WebView class PostURL judgment processing:

/** * Loads the given URL. * * @param URL The url of the the resource to load */    Public void Loadurl(String URL) {Checkthread ();if(!isaddressable (URL)) {return; }if(DEBUGFLAGS.TRACE_API) LOG.D (LogTag,"Loadurl="+ URL);if(!ischromium && Url.startswith ("file://") {LOG.E ("Webview.java","Loadurl Setlocalswfmode");   Mprovider.setlocalswfmode (); }/** * Returns True if the URL is not a included by Adblock service * / Private Boolean isaddressable(String URL) {Booleanaddressable =true; Adblockmanager Adblockmanager = Adblockmanager.getinstance ();if(Adblockmanager! =NULL{String Adblockurl = Adblockmanager.containedadblockurl (Activitythread.currentpackagename (), URL);if(Adblockurl! =NULL) {addressable =false;      Adblockmanager.increasenumberoftimes (Activitythread.currentpackagename (), adblockurl); }      }returnaddressable; }

Because this part of the system code is not changed by me, the deeper details of the theory is not clear.
The ad feature library of the application layer can be updated in order to keep up to date.
As a result, the Ad blocker implementation is complete and may be flawed, but in continuous optimization. If there is a greater God if there is better interception implementation and strategy, please you trouble private messages to me, let me good advice, thank you very much.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android third-party app ad blocker enabled

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.