使用隐式Intent,在AndroidManifest.xml通过在<activity>标签下配置<intent-filter>的内容,可以指定当前活动能够响应的action和category,我们不仅可以启动自己程序内的活动,还可以启动其他程序的活动,比如调用系统的浏览器来打开某网页
Intent intent = new Intent(Intent.ACTION_VIEW); //为Intent设置Action属性 intent.setData(Uri.parse("http://www.baidu.com")); //为Intent设置DATA属性
startActivity(intent);
Intent.ACTION_VIEW,这是一个Android系统内置的动作,其常量值为android.intent.action.VIEW。然后通过Uri.parse()方法,将一个网址字符串解析成一个Uri对象,再调用Intent的setData()方法将这个Uri对象传递进去。
在AndroidManifest.xml中为Activity进行注册。
<intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <data android:scheme="http" /> <!--响应所有的http协议的Intent--> </intent-filter>
运行后就可以看到打开了系统浏览器。
类似的,还可以指定很多其他协议,比如geo表示显示地理位置、tel表示拨打电话,比如使用intent调用系统拨号界面
Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse("tel:10086")); startActivity(intent);
ACTION_DIAL表示intent的action是拨号这也是Android系统的内置动作。然后在data指定了协议是tel,号码是10086