I am trying to test how implicit intent can be used to invoke a component within the same app (I am using Android 4.4).

I have a MainActivity and a Activity2. In the AndroidManifest.xml,

 <activity
        android:name="com.android.intenttest.Activity2"
        android:label="@string/title_activity_activity2" >
        <intent-filter>
            <action android:name="com.android.intesttest.Activity2Action"/>                
        </intent-filter>
 </activity>

In the MainActivity, I tried using:

 Intent intentObj = new Intent();
 intentObj.setAction("com.android.intesttest.Activity2Action");

 if(intentObj.resolveActivity(getPackageManager()) != null){
      startActivity(intentObj);
 }
 else{
      Toast.makeText(getApplicationContext(), "No matching activity found", Toast.LENGTH_SHORT).show();
 }

It's unable to invoke Activity2 (I can see the Toast). Can someone please point out what I am doing wrong ?

Thanks.

Edit :

I modified the scenario a bit and can't explain what I observe. I have two apps : App 1 and App 2.

App 1 has :

  • Activity 2 : intent filter with action 'com.android.intenttest.testAction' and category DEFAULT
  • Activity 3 : no intent filter

App 2 has :

  • Activity 2 : intent filter with action 'com.android.intenttest.testAction' and category DEFAULT

In App 1's Activity 3, I have :

 Intent intentObj = new Intent();
 intentObj.setAction("com.android.intesttest.testAction");

 if(intentObj.resolveActivity(getPackageManager()) != null){
      startActivity(intentObj);
 }
 else{
      Toast.makeText(getApplicationContext(), "No matching activity found", Toast.LENGTH_SHORT).show();
 }

I would expect a chooser dialog to pop up and ask to choose between App 1's Activity2 and App 2's Activity2.

But it always displays Activity2 from App2. Can someone explain why ?

Thanks.

有帮助吗?

解决方案

For first part of the question, the intent filter needs to be as follows :

 <activity
        android:name="com.android.intenttest.Activity2"
        android:label="@string/title_activity_activity2" >
        <intent-filter>
            <action android:name="com.android.intesttest.Activity2Action"/>
            <category android:name="android.intent.category.DEFAULT"/>
        </intent-filter>
  </activity>

From Android's documentation :

In order to receive implicit intents, you must include the CATEGORY_DEFAULT 
category in the intent filter. The methods startActivity() and 
startActivityForResult() treat all intents as if they declared the 
CATEGORY_DEFAULT category. If you do not declare this category in your intent 
filter, no implicit intents will resolve to your activity.
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top