先来看下面的例子:
Uri uri = Uri.parse("http://www.google.com");
Intent it = new Intent(Intent.ACTION_VIEW,uri);
startActivity(it);
这段代码将调用系统内的浏览器,并且打开 google.com 网页。
仔细的分析一下代码,你会发现,这里除了指定了网址,指定了浏览方式外,并没有提到与浏览器程序本身有关的内容。
与 Windows 下的 ShellExecute() 函数相比较,ShellExecute() 也不需要指定打开方式,系统会自动打开与文件或协议关联的应用程序。Android 下的 Intent 与 ShellExecute() 有着异曲同工之妙
下面就来看一下 Android 下的实现方式:
打开 AndroidManifest.xml ,找到 <Activity> 节点,在下面有 <intent-filter> 节点。如果没有的话也不要紧,可以自己加的。添加如下内容:
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<data android:schema="http" />
</intent-filter>
利用 <intent-filter> 就可以把应用程序的操作注册到系统中,当用户调用 Intent 时,就可以跟据输入的 ACTION 和 URI 参数来找到这个应用程序。
这里以 http 协议为例,其实所谓的“协议”在 Android 里都可以随便定义。
比如说打开 Google Map 可以用 URI: geo:38.899533,-77.036476
你自己也可以写一个例如打开文件的关联 Intent,如 file:///sdcard/abc.txt
除此之外,还可以用 type 来进行关联,如下:
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<type android:value="test.item"/>
</intent-filter>
此时只需要通过以下代码就能定位到应用了:
Intent it = new Intent(Intent.ACTION_VIEW);
it.setType("test.item");
startActivity(it);
使用Intent-Filter来决定打开方式
最新推荐文章于 2022-05-29 08:00:00 发布