Launching an Activity with an Intent

2019-07-23 06:13发布

问题:

I have the following in my AndroidManifest:

<activity android:name="IntentChild"
          android:label="@string/app_name">
    <intent-filter>
        <action android:name="android.intent.action.EDIT" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="vnd.intent.cursor.item/intent_example"
              android:host="example.intent"
              android:path="intent_example"
              android:scheme="content"
        />
    </intent-filter>
</activity>

I launch the activity with

Uri uri = new Uri.Builder().scheme("content").authority("example.intent").appendPath("intent_example").build(); 
Intent intent = new Intent(Intent.ACTION_EDIT, uri); 
IntentExample.this.startActivity(intent);

But I get:

E/AndroidRuntime( 865): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.EDIT dat=content:// 
example.intent/intent_example }

What am I doing wrong? Also, does Uri.Builder.authority() refer to the same thing as the android:host attribute of the <data> tag in my manifest?

回答1:

Prompted by the comment by @A--C, I ended up adding a call to Intent.setType() to set the desired MIME type:

Uri uri = new Uri.Builder().scheme("content").authority("example.intent").appendPath("intent_example").build(); 
Intent intent = new Intent(Intent.ACTION_EDIT, uri); 
intent.setType("vnd.intent.cursor.item/intent_example");
IntentExample.this.startActivity(intent);

For simplicity, I also pruned my <intent-filter> to only declare the android:mimeType. I guess, but not entirely certain, that this isn't as important as the previous change.

<activity android:name="IntentChild"
          android:label="@string/app_name">
    <intent-filter>
        <action android:name="android.intent.action.EDIT" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="vnd.intent.cursor.item/intent_example"/>
    </intent-filter>
</activity>