Android Product Development (11)-in-app jump scheme protocol

Source: Internet
Author: User

Reprint please indicate the source: a column of Maple Leaf

In the previous article we explained the actual development of Android app, try not to save data in static variables, global variables, because the app process may be unsafe, in some phones it may be killed by the system, resulting in static global variable reinitialization. The activity of the app's current page is also stored in memory, causing the app not to be restarted, but only the displayed page is not killed, and the process is actually restarted. There are some unpredictable errors in using static variables that have been reinitialized, as you can see here: Android Product development (10) –> do not use static variables to save data

And this article is about an app page jump protocol, where the jump includes in-app jump, H5 and native jump, the server notifies the client how to jump and so on.

Before we explain the in-app jump protocol, let's first explain the relevant knowledge points of H5 and native jumping to each other. More and more apps are being developed using the native + H5 approach, where does native interact with H5 pages? Google provides a common way: JS and native Intermodulation, that is, JS can call the native method, native can also invoke the JS method;

But there are a number of problems with this interactive approach:
1, Java call JS inside the function, efficiency is not very high, estimated to 200ms about it, do a very strong interaction, this speed is very difficult to accept, and JS to tune Java method, fast, 50ms around, so try to use JS call Java method
2, Java call JS function, no return value, call to control the
3, Js call Java method, return value if it is a string, you will find that the string is native, turn to the locale for normal use, using the tolocalestring () function can be, but this function is not fast, the conversion of the string if a lot of, It's going to be time-consuming.
4, try not to use jquery in the Web page, it takes 5-6 seconds to execute, it is best to use the native JS write business script to improve loading speed, improve the user experience.
5, android4.2 below the system exists webview JS Object Injection Vulnerability ... (not clear can Google)

For this reason, we do not use this method for native interaction with WebView, but instead of using scheme + cookie method;

The scheme here is an intra-page jump protocol that is mainly used to support several scenarios:

    • Server issued a jump path, the client according to the server issued a jump path to jump to the corresponding page;

    • H5 page Click on the anchor point, depending on the anchor point specific jump path app end to jump to specific pages;

    • The app side receives the server-side push notification bar message and jumps to the relevant page according to the message's Click Jump Path.

Below I will briefly introduce the basic concepts of scheme and the specific application of scheme in the above three scenarios.

URL Scheme Overview URL scheme's role

A client app can register a URL scheme with the operating system that is used to launch the app from a browser or other app. The specified URL field allows the app to open certain pages directly after it has been called, such as the vehicle Details page, the Order Details page, the message notification page, the promotional ad page, and so on. You can also perform certain actions, such as order payment. You can also directly invoke a page within the app by using an HTML page.

Format of URL scheme

The client-defined URL is used as the basis for calling another from one app, following the RFC 1808 (Relative Uniform Resource Locators) standard. This is the same as our common URL format for Web content.

A common URL is divided into sections,,,, and scheme host relativePath query .

For example:, this URL, for, for, for http://www.baidu.com/s?rsv_bp=1&rsv_spt=1&wd=NSurl&inputT=2709 scheme http host www.baidu.com relativePath /s , query for rsv_bp=1&rsv_spt=1&wd=NSurl&inputT=2709 .

An example of the URL used in an app (the URL will be picked up on the vehicle Details page):, which is, for, for uumobile://mobile/carDetail?car_id=123456 scheme uumobile host mobile relativePath /carDetail , query for car_id=123456 .

Scheme defines activity

1) define scheme in Androidmanifest.xml

<!--scheme Protocol --        <activityandroid:name=". UI.translate.NativeAppActivity "android:label=" @string/app_name ">                                    <!--to be able to successfully tune apps on another app, you must add a intent filter--            <intent-filter>                <!--protocol section, whatever you want to set--                <data android:scheme="Uumobile" />                <!--The following lines also have to be set --                <category android:name="Android.intent.category.DEFAULT" />                <category android:name="Android.intent.category.BROWSABLE" />                <action android:name="Android.intent.action.VIEW" />            </intent-filter>        </activity>

This allows us to define an activity instance that can accept the scheme request, and can lift the nativeappactivity when the Web page or the Android code sends a request for such a rule scheme.

2) Of course is to achieve nativeappactivity

/** * Created by admin * * Public  class nativeappactivity extends Activity{     PublicString tag ="Nativeappactivity"; PublicActivity Mcontext =NULL; Public void onCreate(Bundle b) {Super. OnCreate (b); Mcontext = This; Uri uri = getintent (). GetData ();if(URI! =NULL) {list<string> pathsegments = uri.getpathsegments ();            String uriquery = Uri.getquery (); Intent Intent;if(Pathsegments! =NULL&& pathsegments.size () >0) {//Parse scheme                if(Someif)                {dosomething (); }Else{//If the scheme is not resolved, the nativeappactivity is closed;Finish (); }            }Else{Finish (); }        }Else{Finish (); }    }}

Nativeappactivity This class is mainly used to implement the parsing scheme, and then make corresponding actions, such as the request scheme Jump login page, we can define

uumobile://appname/gotoLogin

Then we parse out scheme if this is the structure on the Jump login page ...

Briefly here, we can get information such as the host of the scheme called by the intent object.

this.getIntent().getScheme();//获得Scheme名称  this.getIntent().getDataString();//获得Uri全部路径 

3) jump to the corresponding page via the server

startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("uumobile://yongche/123123123")));

Here "uumobile://yongche/123123123" is the server issued by the jump path, when we execute the startactivity will be nativeappactivity, We then jump to the corresponding page by parsing scheme content in nativeappactivity.

4) jump to the corresponding page by the anchor point on the H5 page

@Override public boolean shouldoverrideurlloading (WebView view,StringURL) {//Parse scheme        if(Url.indexof (h5constant.scheme)! =-1) {Try{URI uri = uri.parse (URL);String[] Urlsplit = Url.split ("\\?"); map<String,String> QueryMap =Newhashmap<String,String> ();StringH5url =NULL;if(Urlsplit.length = =2) {QueryMap = H5constant.parseuriquery (urlsplit[1]);                H5url = Querymap.get (H5constant.murl); }//Jump nativeappactivity parsing{//If refresh is set, refresh the page                    if(Querymap.containskey (H5constant.reloadpre) &&"1". Equals (Querymap.get (H5constant.reloadpre))) {H5fragment.isneedflushpreh5 =true; } Intent Intent =NewIntent (Intent.action_view, URI);                H5activity.startactivityforresult (Intent, H5constant.h5requestcode); }            }Catch(Exception e)            {E.printstacktrace (); }return true; }//Call        Else if(Url.indexof ("tel://") != -1) {FinalStringNumber = Url.substring ("tel://". Length ()); Config.callphonebynumber (h5activity, number);return true; }Else if(Url.indexof ("Tel:") != -1) {FinalStringNumber = Url.substring ("Tel:". Length ()); Config.callphonebynumber (h5activity, number);return true; }//Other ways to jump        Else{view.loadurl (URL);//Returns TRUE if no other processing of the click-Link event is required, otherwise false            return false; }    }

We can find that we set the webviewclient for WebView and rewrite the Webviewclient shouldoverrideurlloading method, and then we parse the URL of the anchor point, And according to the content of the analysis, nativeappactivity scheme Activity is adjusted, then the content of scheme is parsed and the corresponding page is nativeappactivity.

5) According to the server issued notification bar message, the app jumps the corresponding page

 Public  class notificationactivity extends Activity {    @Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); L.i ("received notification Click event ..."); Intent realintent = Getintent (). Getparcelableextra (notifeconstant.real_intent);//parse scheme and jumpGotorealscheme ( This, realintent); }/** * Notification jump scheme, according to the effective time to determine the jump URL address * Jump after a network request to determine the user's current status */    Private void Gotorealscheme(context context, Intent realintent) {if(Realintent = =NULL|| Context = =NULL) {finish ();return; }Try{L.i ("Start resolving parameters in notification ...");LongStartshowtime = Realintent.getlongextra (Notifeconstant.start_show_time,0);//Expiry time, Unit: s (sec)            LongValidtime = Realintent.getlongextra (Notifeconstant.valid_time,0);LongCurrentTime = System.currenttimemillis ();            String Validactionurl = Realintent.getstringextra (Notifeconstant.valid_action_url);            String Invalidactionurl = Realintent.getstringextra (Notifeconstant.invalid_action_url);            Intent schemeintent; L.i ("Start building intent objects based on URLs ...");if((currenttime-startshowtime)/ +L <= validtime) {schemeintent = H5constant.buildschemefromurl (Validactionurl); }Else{schemeintent = H5constant.buildschemefromurl (Invalidactionurl); }if(Schemeintent! =NULL) {//Set current page to open for notification barConfig.isnotificationopen =true;                Context.startactivity (schemeintent); Finish ();//To the notification bar click event StatsMobclickagent.onevent (context, Umcountconstant.push_notification_click); }Else{Finish (); }        }Catch(Exception e) {//exit Current activity under exceptional circumstancesFinish (); }    }}

All the notifications that the server sends are the first to jump to the notificationactivity here, then execute the logic of jumping to other activity here, And here the H5constant Buildschemefromurl method is to construct the jump page intent object, we can see a buildschemefromurl method of the specific implementation:

/** * Build Intent from Scheme URL for interface Jump * * @param URL * @return  */     Public StaticIntentBuildschemefromurl(String URL) {if(URL! =NULL&& url.indexof (h5constant.scheme)! =-1{URI uri = uri.parse (URL); string[] Urlsplit = Url.split ("\\?"); map<string, string> QueryMap =NewHashmap<string, string> (); String H5url =NULL;if(Urlsplit.length = =2) {QueryMap = H5constant.parseuriquery (urlsplit[1]);            H5url = Querymap.get (H5constant.murl); } Intent Intent =NewIntent (Intent.action_view, URI);if(!            Textutils.isempty (H5url)) {Intent.putextra (H5constant.murl, H5url); }returnIntent }return NULL; }

So we're going to construct a intent object in addition to the jump nativeappactivity, and pass the scheme string to nativeappactivity, This allows you to parse the scheme string and execute the corresponding jump logic in nativeappactivity.

Summary:
The scheme in Android is a very good implementation mechanism, through the definition of their scheme protocol, it is very convenient to jump to the various pages in the app;
Through the scheme protocol, the server can be customized to tell the app to jump that page, you can customize the jump page through the notification bar message, you can jump through the H5 page page.

In addition to product development technology, skills, practice interested students can refer to my:
Android Product Development (i) –> Practical development Code
Android product Development (ii) –> start Page optimization
Android Product Development (iii) –> base class activity
Android product Development (iv) –> reduce APK size
Android Product Development (v) –> multi-channel packaging
Android product Development (vi) –>APK confusion
Android Product Development (vii) –>APK hot fix
Android product Development (eight) –>app data statistics
Android product Development (ix) –>APP Network Transfer Protocol
Android Product Development (10) –> do not use static variables to save data

This article synchronizes to GitHub: Https://github.com/yipianfengye/androidProject, Welcome to star and follow

Android Product Development (11)-in-app jump scheme protocol

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.