记录下Android和iOS的深度链接接入详情

现在很多app都要支持一键拉起App,并在唤醒App后直达游戏房间(指定场景)

IOS的是Universal Links,可以参考文章

https://www.jianshu.com/p/77b530f0c67b

Android的是Deep Links 和 App Links

https://www.jianshu.com/p/1632be1c2451

首先介绍2个免费的sdk,可以直接拉起App,推荐 openinstall

1.Android 配置Deep Links和 App Links

启动MainActivity配置 AndroidManifest.xml, 其中的 xxxxx 换成自定义的就行了

        <activity 
			android:name=".MainActivity"
			android:screenOrientation="landscape"
            android:launchMode="singleTask"
            android:usesCleartextTraffic="true"
            android:resizeableActivity="true"
			android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen"
			android:hardwareAccelerated="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
                <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.BROWSABLE" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:scheme="xxxxx"/>
            </intent-filter>
            <!-- APP Links方式,Android 23版本及以后支持 -->
            <intent-filter android:autoVerify="true">
                <action android:name="android.intent.action.VIEW"/>
                <category android:name="android.intent.category.DEFAULT"/>
                <category android:name="android.intent.category.BROWSABLE"/>
                <data
                    android:host="www.xxxxx.com"
                    android:scheme="http"/>
                <data
                    android:host="www.xxxxx.com"
                    android:scheme="https"/>
            </intent-filter>

            <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
        </activity>

MainActivity中配置

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // 在这接收启动参数,我们这里传递的是 roomNum=1111
    Intent intent = getIntent();
    Uri uri = intent.getData();
    if (uri != null)
    {
        Log.d(TAG,"deeplink scheme:"+uri.getScheme());
        String roomNum = uri.getQueryParameter("roomNum");
        Log.d(TAG,"deeplink roomNum:"+roomNum);
    }
}

// 需要注意的是要重写 onNewIntent方法
@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    setIntent(intent);
    Uri uri = intent.getData();
    if (uri != null)
    {
        Log.d(TAG,"deeplink scheme:"+uri.getScheme());
        String roomNum = uri.getQueryParameter("roomNum");
        Log.d(TAG,"deeplink roomNum:"+roomNum);
    }
}

web端生成深度链接, xxxxx 换成自几定义的名称, 注意 xxxxx://?roomNum 这个问号一定要加

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
    <meta name="viewport"
          content="width=device-width, height=device-height, user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0">
    <meta name="format-detection" content="telephone=no">
    <style>
        html, body, iframe, .page {
            height: 100%;
            width: 100%;
            border: 0;
            margin: 0;
            padding: 0;
            font-family: Tahoma, "Hiragino Sans GB", "Microsoft YaHei", "WenQuanYi Micro Hei", sans-serif !important;
            font-weight: 400;
        }

        h1, img, p, a, span {
            border: 0;
            margin: 0;
            padding: 0;
        }

        .tip {
            color: #666;
            font-size: 18px;
            padding-top: 18px;
            display: block;
        }

        .page {
            text-align: center;
        }

        .page h1 {
            margin: 0 0 35px;
            font-size: 24px;
            line-height: 32px;
            color: #666;
            font-weight: normal;
        }

        .content {
            position: absolute;
            left: 0;
            top: 50%;
            margin-top: -142px;
            width: 100%;
            z-index: 1;
        }

        .page img.logo {
            width: 70px;
            margin: 0 auto 35px;
            display: block;
        }

        .open-button {
            display: block;
            margin: 0 auto;
            width: 260px;
            height: 44px;
            line-height: 44px;
            color: #00B9C8;
            font-size: 16px;
            text-decoration: none;
            border-radius: 5px;
            border: 1px solid #00B9C8;
        }

        .download-button {
            margin-bottom: 20px;
            background: #00B9C8;
            color: #fff;
        }
    </style>
</head>
<body>
<div class="page">
        <div class="content">
        <img src="http://www.xxxxx.com/[email protected]" alt="" class="logo">
        <h1>xxxxx</h1>
                    <a href="http://www.xxxxx.com/gamedownload/index.html" class="open-button download-button">
                立即安装
            </a>
                            <p>
                <a href=""
                   class="open-button"
                   id="call_app_url">
                    打开 APP 继续
                </a>
            </p>
        </div>
</div>
</body>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script>
            /*获取到Url里面的参数*/
    (function ($) {
    $.getUrlParam = function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
        }
    })(jQuery);

    var roomNum = $.getUrlParam('roomNum');
    console.log(roomNum)
    if(roomNum != null){
        $('#call_app_url').attr('href','ylscqp://?roomNum='+roomNum); 
    }

    function openWithIFrame(uri) {
        let ifr = document.createElement('iframe');
        ifr.style.cssText = 'opacity:0;width=1px;height=1px;';
        ifr.src = uri;
        document.body.appendChild(ifr);

        setTimeout(function () {
            document.body.removeChild(ifr);
        }, 2000);
        return ifr;
    }

    setTimeout(function () {
        openWithIFrame("xxxxx://?roomNum="+roomNum);
    }, 100);
</script>
</html>

App Links 直接去 谷歌提供的tool直接生成并且测试

https://developers.google.com/digital-asset-links/tools/generator

必须要在服务器上操作,示范url如下

https://yaoyi.ypzdw.com/.well-known/assetlinks.json
如果是win系统建立 .well-known 建立不了,需要在 .well-known 后面加个点,比如: .well-known. 这样就能建立成功了
assetlinks.json

[{
  "relation": ["delegate_permission/common.handle_all_urls"],
  "target": {
    "namespace": "android_app",
    "package_name": "com.example",
    "sha256_cert_fingerprints":
    ["14:6D:E9:83:C5:73:06:50:D8:EE:B9:95:2F:34:FC:64:16:A0:83:42:E6:1D:BE:A8:8A:04:96:B2:3F:CF:44:E5"]
  }
}]

2.ios配置待续。。。。

创建一个文件 apple-app-site-association ,可以将这个文件放到服务器的根目录下,也可以放到.well-known这个子目录下

{
        "applinks": {
            "apps": [],
            "details": [
                        {
                            "appID": "teamID.bundleId”,
                            "paths": ["/deaplink","/wwdc/news/","*"]
                        },
                        {
                            "appID": "ABCD1234.com.apple.wwdc",
                            "paths": [ "*" ]
                        }
                        ]
        }
    }

appID 的 格式为 teamID.bundleId形式。
paths配置,实际上就是限制哪些路径可以唤醒app,哪些路径不能唤醒app。使用*配置,则整个网站都可以使用
在这里插入图片描述

注意:这里的domains一定要 applinks: 开头

-(BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray * _Nullable))restorationHandler{
    
//    NSLog(@"userActivity : %@",userActivity.webpageURL.description);
//    NSLog(@"continueUserActiity enter");
//    NSLog(@"\tAction Type : %@", userActivity.activityType);
//    NSLog(@"\tURL         : %@", userActivity.webpageURL);
//    NSLog(@"\tuserinfo :%@",userActivity.userInfo);
    NSURL* url = userActivity.webpageURL;
    
    
    NSMutableDictionary *parm = [[NSMutableDictionary alloc]init];
    
    //传入url创建url组件类
    NSURLComponents *urlComponents = [[NSURLComponents alloc] initWithString:url.absoluteString];
    
    //回调遍历所有参数,添加入字典
    [urlComponents.queryItems enumerateObjectsUsingBlock:^(NSURLQueryItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [parm setObject:obj.value forKey:obj.name];
    }];
    
    NSString* roomNum = [parm valueForKey:@"roomNum"];
    NSString* name = @"ThirdpartyManager";
    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
    [dictionary setValue:@1 forKey:@"Platformtype"];
    [dictionary setValue:@100 forKey:@"code"];
    [dictionary setValue:roomNum forKey:@"msg"];

    //转成JSON
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];
    if (error)
    {
        NSLog(@"dic->%@",error);
    }

    NSString * jsonString  =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"jsonString3->%@",jsonString);

    UnitySendMessage([name cStringUsingEncoding:NSUTF8StringEncoding],
                     "ThridToUnity",
                     [jsonString cStringUsingEncoding:NSUTF8StringEncoding]);
    
    return YES;
}

IOS Deep Link的配置

在这里插入图片描述
Info.plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>CADisableMinimumFrameDuration</key>
	<false/>
	<key>CFBundleDevelopmentRegion</key>
	<string>en</string>
	<key>CFBundleDisplayName</key>
	<string>xxxxx</string>
	<key>CFBundleExecutable</key>
	<string>${EXECUTABLE_NAME}</string>
	<key>CFBundleIdentifier</key>
	<string>com.ylzx.${PRODUCT_NAME}</string>
	<key>CFBundleInfoDictionaryVersion</key>
	<string>6.0</string>
	<key>CFBundleName</key>
	<string>${PRODUCT_NAME}</string>
	<key>CFBundlePackageType</key>
	<string>APPL</string>
	<key>CFBundleShortVersionString</key>
	<string>1.0</string>
	<key>CFBundleURLTypes</key>
	<array>
		<dict>
			<key>CFBundleTypeRole</key>
			<string>Editor</string>
			<key>CFBundleURLName</key>
			<string>weixin</string>
			<key>CFBundleURLSchemes</key>
			<array>
				<string>wx123213123312321312</string>
			</array>
		</dict>
		<dict>
			<key>CFBundleTypeRole</key>
			<string>Editor</string>
			<key>CFBundleURLSchemes</key>
			<array>
				<string>ylscqp</string>
			</array>
		</dict>
	</array>
	<key>CFBundleVersion</key>
	<string>0</string>
	<key>LSApplicationQueriesSchemes</key>
	<array>
		<string>ylscqp</string>
		<string>wechat</string>
		<string>weixin</string>
	</array>
	<key>LSRequiresIPhoneOS</key>
	<true/>
	<key>NSAppTransportSecurity</key>
	<dict>
		<key>NSAllowsArbitraryLoads</key>
		<true/>
	</dict>
	<key>NSCameraUsageDescription</key>
	<string>是否允许此App使用你的相机?</string>
	<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
	<string>AMapLocationKit需要定位权限才可以正常使用,如果您需要使用后台定位功能请选择“始终允许”。</string>
	<key>NSLocationAlwaysUsageDescription</key>
	<string>AMapLocationKit需要定位权限才可以使用</string>
	<key>NSLocationWhenInUseUsageDescription</key>
	<string>AMapLocationKit需要定位权限才可以正常使用</string>
	<key>NSMicrophoneUsageDescription</key>
	<string>是否允许此App获取你的麦克风?</string>
	<key>UIApplicationExitsOnSuspend</key>
	<false/>
	<key>UIBackgroundModes</key>
	<array>
		<string>location</string>
	</array>
	<key>UILaunchStoryboardName~ipad</key>
	<string>LaunchScreen-iPad</string>
	<key>UILaunchStoryboardName~iphone</key>
	<string>LaunchScreen-iPhone</string>
	<key>UILaunchStoryboardName~ipod</key>
	<string>LaunchScreen-iPhone</string>
	<key>UIPrerenderedIcon</key>
	<false/>
	<key>UIRequiredDeviceCapabilities</key>
	<array>
		<string>armv7</string>
	</array>
	<key>UIRequiresFullScreen</key>
	<true/>
	<key>UIRequiresPersistentWiFi</key>
	<false/>
	<key>UIStatusBarHidden</key>
	<true/>
	<key>UIStatusBarStyle</key>
	<string>UIStatusBarStyleDefault</string>
	<key>UISupportedInterfaceOrientations</key>
	<array>
		<string>UIInterfaceOrientationLandscapeRight</string>
		<string>UIInterfaceOrientationLandscapeLeft</string>
	</array>
	<key>UnityCloudProjectID</key>
	<string></string>
	<key>UnityCrashSubmissionURL</key>
	<string>https://a:[email protected]/symbolicate</string>
	<key>Unity_LoadingActivityIndicatorStyle</key>
	<integer>-1</integer>
</dict>
</plist>

入口文件.m or .mm

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    
    if ([url.scheme isEqualToString:@"ylscqp"]) {
        NSMutableDictionary *parm = [[NSMutableDictionary alloc]init];
        
        //传入url创建url组件类
        NSURLComponents *urlComponents = [[NSURLComponents alloc] initWithString:url.absoluteString];
        
        //回调遍历所有参数,添加入字典
        [urlComponents.queryItems enumerateObjectsUsingBlock:^(NSURLQueryItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [parm setObject:obj.value forKey:obj.name];
        }];
        
        NSString* roomNum = [parm valueForKey:@"roomNum"];
        NSString* name = @"ThirdpartyManager";
        NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
        [dictionary setValue:@1 forKey:@"Platformtype"];
        [dictionary setValue:@100 forKey:@"code"];
        [dictionary setValue:roomNum forKey:@"msg"];
        
        //转成JSON
        NSError *error = nil;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary
                                                           options:NSJSONWritingPrettyPrinted
                                                             error:&error];
        if (error)
        {
            NSLog(@"dic->%@",error);
        }
        
        NSString * jsonString  =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"jsonString3->%@",jsonString);
        
        UnitySendMessage([name cStringUsingEncoding:NSUTF8StringEncoding],
                         "ThridToUnity",
                         [jsonString cStringUsingEncoding:NSUTF8StringEncoding]);

    }
    
    return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
}

over

发布了69 篇原创文章 · 获赞 10 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/mhtqq809201/article/details/88757951
今日推荐