本章节翻译自《Beginning-Android-4-Application-Development》,如有翻译不当的地方,敬请指出。
原书购买地址http://www.amazon.com/Beginning-Android-4-Application-Development/dp/1118199545/通过使用Intent-Filter中的<category>元素,我们可以把activities进行分组。假设已经在AndroidManifest.xml中添加了<category>元素:
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.manoel.Intents"
- android:versionCode="1"
- android:versionName="1.0" >
- <uses-sdk android:minSdkVersion="14" />
- <uses-permission android:name="android.permission.CALL_PHONE" />
- <uses-permission android:name="android.permission.INTERNET" />
- <application
- android:icon="@drawable/ic_launcher"
- android:label="@string/app_name" >
- <activity
- android:name=".IntentsActivity"
- android:label="@string/app_name" >
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- <activity
- android:name=".MyBrowserActivity"
- android:label="@string/app_name" >
- <intent-filter>
- <action android:name="android.intent.action.VIEW" />
- <action android:name="net.learn2develop.MyBrowser" />
- <category android:name="android.intent.category.DEFAULT" />
- <category android:name="com.manoel.Apps" />
- <data android:scheme="http" />
- </intent-filter>
- </activity>
- </application>
- </manifest>
- Intent i = new
- Intent(android.content.Intent.ACTION_VIEW,
- Uri.parse("http://www.amazon.com"));
- nbsp;// 注意这句代码
- i.addCategory("com.manoel.Apps");
- startActivity(Intent.createChooser(i, "Open URL using..."));
但是,如果指定了一个并没有在Intent-Filter中定义的Category,那么,将不会有Activity被调用:
- Intent i = new
- Intent(android.content.Intent.ACTION_VIEW,
- Uri.parse("http://www.amazon.com"));
- // i.addCategory("net.learn2develop.Apps");
- // 这个category不匹配Intent-Filter中的任何category
- i.addCategory("net.learn2develop.OtherApps");
- startActivity(Intent.createChooser(i, "Open URL using..."));
但是,如果在AndroidManifest.xml中添加如下代码,之前的代码就可以运行了:
- <activity android:name=".MyBrowserActivity"
- android:label="@string/app_name">
- <intent-filter>
- <action android:name="android.intent.action.VIEW" />
- <action android:name="net.learn2develop.MyBrowser" />
- <category android:name="android.intent.category.DEFAULT" />
- <category android:name="net.learn2develop.Apps" />
- <!-- 添加这句代码 -->
- <category android:name="net.learn2develop.OtherApps" />
- <data android:scheme="http" />
- </intent-filter>
- </activity>
也可以为Intent对象添加多重Category属性,举个例子:
- Intent i = new
- Intent(android.content.Intent.ACTION_VIEW,
- Uri.parse("http://www.amazon.com"));
- // 多重的Category
- i.addCategory("com.manoel.Apps");
- i.addCategory("com.manoel.OtherApps");
- i.addCategory("com.manoel.SomeOtherApps");
- startActivity(Intent.createChooser(i, "Open URL using..."));