Android中Scheme跳转协议

来源:互联网 发布:it发展规划 编辑:程序博客网 时间:2024/05/22 06:04

简书地址
http://www.jianshu.com/p/7b56ed162a63

Android中Activity之间的跳转我们可以直接使用显示或者隐式意图跳转都可以
但是实际开发过程中可能会碰到这类问题
比如App做活动,通过推送过来的消息告诉客户端跳转到某某界面,客户端本地自然不能写死,不然就麻烦了
今天小结一下开发过程中碰到的这类问题的解决方式:
我们都知道网站都是通过URL的形式访问的
同样的我们App也完全可以通过这种方式进行跳转
举个小例子

<a href='andy://domain/path?params'>点我试试</a>   andy为自定义的scheme,固定字符串。

在清单文件中加入IntentFilter

这里写图片描述

在TextView中显示
这里写图片描述

当然这里设置了当前的Activity的启动模式为singleTask,防止MainActivity重复启动
然后在MainActivtiy中重写onNewIntent方法,获取参数

@Override    protected void onNewIntent(Intent intent) {        super.onNewIntent(intent);        Uri uri = intent.getData();        if (uri != null) {            System.out.println(uri.toString());        }    }

这里写图片描述

断点可以看到已经有数据传递过来了
这个时候我们只需要根据Uri获取里面的参数然后做相应的动作即可
Uri结构的基本形式

[scheme:][//domain][path][?query][#fragment]  

Uri结构参考http://blog.csdn.net/harvic880925/article/details/44679239

现在我们定义具体的参数
比如我们跳转的页面是SchemeActivtiy参数buffer
domain=scheme_activity
buffer=这是个字符串

<a href='andy://scheme_activity?type=0&buffer=这是个字符串'>点我一下</a>
private static final String SCHEME_DOMAIN = "scheme_activity";private static final String TAG = MainActivity.class.getSimpleName();

相关解析代码

 @Override    protected void onNewIntent(Intent intent) {        super.onNewIntent(intent);        Uri uri = intent.getData();        if (uri != null) {            dispatchUri(uri);        } else {            Log.e(TAG, "Uri is null");        }    }    private void dispatchUri(Uri uri) {        try {            final String domain = uri.getAuthority();            if (TextUtils.equals(SCHEME_DOMAIN, domain)) {                final String buffer = uri.getQueryParameter("buffer");                final int type = Integer.valueOf(uri.getQueryParameter("type"));                Toast.makeText(this, type + "  " + buffer, Toast.LENGTH_SHORT).show();            }        } catch (Exception e) {            Log.e(TAG, "Uri Parse Error");        }    }

点击测试

这里写图片描述

完整Demo地址

0 0