Android Generic User Agent (UA)

前端 未结 5 1754
你的背包
你的背包 2020-12-31 12:27

I am building an Android app to display content feed from a server. The server is a mobile website (like http://m.google.com) which tracks the traffic from various mobile cl

5条回答
  •  旧巷少年郎
    2020-12-31 13:06

    You can totally do that and at developer.android.com suggest it as well, when they talk about the WebView, especially if you want to build a web app for your web view. Reference here: http://developer.android.com/guide/webapps/webview.html

    Id suggest not only to keep reference to the application in your User Agent but to also keep track of the version as well.

    Anyways, I was looking to change my UA too and the discussions here and the encouraged me to do so as well.

    Here is my implementation:

    On your Android APP:

    String versionName="";
    int versionCode=0;
    try {
        versionName = getBaseContext().getPackageManager().getPackageInfo(getBaseContext().getPackageName(), 0 ).versionName;
        versionCode = getBaseContext().getPackageManager().getPackageInfo(getBaseContext().getPackageName(), 0 ).versionCode;
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }
    

    If you want to auto increment the build number aka. versionCode you may take a look to this other Stack Overflow post as well, the C# solution.

    Afterwards you just change the User Agent.

    WebView mywebview = (WebView)findViewById(R.id.webView);
    String myUserAgent = " MyFancyAPPName  V."+versionName+"."+versionCode;
    
    mywebview.getSettings().setUserAgentString(mywebview.getSettings().getUserAgentString()+myUserAgent);
    

    On your Web Application: In PHP

    
    

    Or In JavaScript

    var ua = navigator.userAgent.toLowerCase();
    var isAndroid = ua.indexOf("MyFancyAPPName") > -1;
    if(isAndroid) { 
        //do whatever you wish here
    }
    

    Or you can directly detect it from the .htaccess file:

    RewriteCond %{HTTP_USER_AGENT} ^.*MyFancyAPPName.*$
    RewriteRule ^(.*)$ http://www.MyWebSite/MyFancyAPPName [R=301]
    

提交回复
热议问题