android scheme

有时候我们开发的应用希望让其他应用也可以访问,Android平台而言,可以通过Uri(统一资源标识符Uniform Resource Identifier)来实现.

Android中 URI的组成部分scheme, authority and path,其中authority又分为host和port。格式如下: scheme://host:port/path
举个实际的例子:
content://com.dx.test:2020/folder/myfolder/dir
其中scheme 对应 content://
authority 对应 com.dx.test:2020
host 对应 com.dx.test
port 对应 2020
path 对应 /folder/myfolder/dir
这时候我们想到在mainifest.xml里面定义的activity标签下的intent-filter子标签data里面的各个属性,实际上与上面是有对应关系的

<data android:host="string"    
   android:mimeType="string"    
   android:path="string"    
   android:pathPattern="string"  
   android:pathPrefix="string"
   android:port="string" 
   android:scheme="string" /> 

比如有在A应用程序的mainifest.xml中有这么个Activity

     <activity android:name=".TestActivity">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:scheme="sharetest" android:host="data" />
            </intent-filter>
        </activity>

如上所示,在data里设置了 scheme和host,则该Activity可以接收和处理类似于 "sharetest://data/XXX"的链接。
在A应用程序的TestActivity中编写处理Scheme的逻辑

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

/**
 * Created by dengxuandeng on 16-3-9.
 */
public class TestActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_layout);
        Intent a = getIntent();
        Log.d("scheme", a.toString());
    }
}

这里为了方便 直接用log打出来了.
到这里 A 程序就准备OK了.

在B应用程序中,可以直接写一个函数 调起A引用程序中的这个TestActivity

public void gotoScheme(String url) {
        Intent intent = new Intent(Intent.ACTION_DEFAULT, Uri.parse(url));
        Bundle bundle = new Bundle();
        intent.putExtras(bundle);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        this.startActivity(intent);
    }

调起的时候直接写

gotoScheme("sharetest://data/123141")

那么使用B程序使用Scheme调起 A程序的TestActivity的时候,可以看到A程序的TestActivity打出来的log

03-09 11:35:48.126 1088-1088/com.dear.schemetest D/scheme: Intent { act=android.intent.action.VIEW dat=sharetest://data/123141 flg=0x24000000 cmp=com.dear.schemetest/.TestActivity (has extras) }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 大家都知道,如果我们想要打开手机本地的其他应用,我们可以通过intent的隐式启动,添加相关界面activity的...
    Jafir阅读 27,753评论 8 50
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,923评论 18 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,284评论 25 708
  • Uri的格式:scheme://host:port/path or pathPrefix or pathPatte...
    柒黍阅读 6,114评论 0 3
  • 一、我俗?请问:谁不俗? 最近,我换了工作,从体制里出来,就好像每天的头条新闻预测的一般,传统媒体人杀出围城,大踏...
    左十Hani阅读 412评论 0 1