本文共 2090 字,大约阅读时间需要 6 分钟。
当系统发送一个Intent时,哪些activity需要写响应呢?这部分是有Intent Filter决定的。 如下所示: <activity android:name="ShareActivity"> <intent-filter> <action android:name="android.intent.action.SEND"/> <category android:name="android.intent.category.DEFAULT"/> <data android:mimeType="text/plain"/> <data android:mimeType="image/*"/> </intent-filter> </activity> action 表示要响应的动作.例如ACTION_SEND/ACTION_VIEW。 data 表示Intent携带的数据.必须要用Android:mimeType来指定类型,如:text/plain,image/jpeg。 category:为了响应隐式Intent,一般设成CATEGORY_DEFAULT。 一个intent-filter 标签中只能有一个action ,如果有两个action,就分成两个 <intent-filter>. 如下所示: <activity android:name="ShareActivity"> <!-- filter for sending text; accepts SENDTO action with sms URI schemes --> <intent-filter> <action android:name="android.intent.action.SENDTO"/> <category android:name="android.intent.category.DEFAULT"/> <data android:scheme="sms" /> <data android:scheme="smsto" /> </intent-filter> <!-- filter for sending text or images; accepts SEND action and text or image data --> <intent-filter> <action android:name="android.intent.action.SEND"/> <category android:name="android.intent.category.DEFAULT"/> <data android:mimeType="image/*"/> <data android:mimeType="text/plain"/> </intent-filter> </activity> 为了决定activity 响应那个action,一般在onCreate方法中读取intent,如下所示: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Get the intent that started this activity Intent intent = getIntent(); Uri data = intent.getData(); // Figure out what to do based on the intent type if (intent.getType().indexOf("image/") != -1) { // Handle intents with image data ... } else if (intent.getType().equals("text/plain")) { // Handle intents with text ... } } 怎么返回结果给启动你activity呢? 一般调用还是返回一个Intent.然后调用finish() 结束本activity. // Create intent to deliver some kind of result data Intent result = new Intent("com.example.RESULT_ACTION", Uri.parse("content://result_uri")); setResult(Activity.RESULT_OK, result); finish(); 如果你仅仅需要一个整数也可以不要调用Intent,如下所示: setResult(RESULT_COLOR_RED); finish(); 不管是否调用startActivityForResult(),一般都要事先setResult()方法.转载地址:http://tvcmi.baihongyu.com/