您的位置:首页 > 移动开发

从程序外部(浏览器)吊起app

2016-01-22 09:35 211 查看
有些项目可能要求从程序外部吊起自己的app,实现做法十分简单。

首先。在AndroidManifest文件中,你想吊起的Activity标签中加入intent-filter。内容如下:

<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="freeman" android:host="showInfos"/>
</intent-filter>


以下是一些注解(引用自:https://developers.google.com/app-indexing/android/app?hl=zh-cn)

标记描述
<action>指定 ACTION_VIEW Intent
操作,以便能够从 Google 搜索中访问该 Intent 过滤器。
<data>Activity 接受的每种 URI 格式都有一个这样的标记。此 <data> 标记必须至少包括
android:scheme
属性。

您可以添加额外的属性,以进一步细化 Activity 接受的 URI 类型。例如,您可能有多个接受类似 URI 的 Activity,但其不同之处只是在于路径名。在这种情况下,可以使用
android:path
属性或者其变体(pathPattern
或 pathPrefix)来区分对于不同的 URI 路径,系统应打开哪个 Activity。
<category>定义了 BROWSABLE 和 DEFAULT 这两种 Intent 的 Activity:

BROWSABLE:若要能够从 Web 浏览器执行该 Intent,则必须将其设为
BROWSABLE。如果未设置,点击浏览器中的链接将无法解析到您的应用(在这种情况下,只有当前的移动 Web 浏览器能响应该 URL)。
DEFAULT:只有当您希望自己的 Android 应用能够响应任何引用网站中的
HTTP 链接时,才需要设为 DEFAULT。在 Google 搜索结果中使用的 Intent 包含您的应用标识信息,以便将您的应用明确指定为接收方。指向您的网站的其他链接不知道您的应用标识,因此 DEFAULT 类别声明了您的应用可以对隐式 Intent 做出响应。

接着写一个测试的html,例如:
<a href="freeman://showInfos/name/familyname/?name=freeman&family_name=wu">open app</a>
可以看到,里面包含了"freeman://showInfos/name/familyname/?name=freeman&family_name=wu"这一串东西。

我做一个简要说明:

开头的freeman也就是和AndroidManifest文件中的android:scheme对应的,可以理解是一个协议名称;

showInfos和android:host对应,可理解为主机(主要方法)。

showInfos后面的/name/familyname/与android:path对应,可理解为路径。

贴上Android的代码:

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;

import java.util.List;

public class MainActivity extends AppCompatActivity {
TextView textView;

private final static String NAME = "name";
private final static String LASTNAME = "family_name";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.text);

Intent intent = getIntent();
Uri uri = intent.getData();
Log.d("uri", uri.toString());
if(uri != null) {
if("freeman".equals(uri.getScheme())) {
Log.d("host", uri.getHost());
List<String> list = uri.getPathSegments();
if(list != null && list.size() == 2) {
showInfos(uri.getQueryParameter(NAME), uri.getQueryParameter(LASTNAME));
}
}
}
}

private void showInfos(String name , String last_name) {
textView.setText("姓:" + last_name +", 名:" + name);
}
}


代码炒鸡简单,不做赘述。经过我测试,在模拟器自带的浏览器打开上面的html之后,点击open app,可以顺利地吊起app。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: