Robolectric: Question: Resolve activity for intent

Created on 10 May 2019  路  3Comments  路  Source: robolectric/robolectric

Question

What is the non-deprecated way to make the following return not null?

intent.resolveActivity(requireContext().packageManager)

Deprecated method

I am currently making this work using the following in the ShadowPackageManager

val info = ResolveInfo()

info.activityInfo = ActivityInfo().apply {
    applicationInfo = ApplicationInfo().apply { packageName = "com.example" }
    name = "Example"
}

val shadowPackageManager = Shadows.shadowOf(application.packageManager)
shadowPackageManager.addResolveInfoForIntent(Intent(MediaStore.ACTION_IMAGE_CAPTURE), info)

The method addResolveInfoForIntent(...) has been marked as deprecated and I can't figure out how to use the alternatives it suggested to make the intent resolvable.

Robolectric & Android Version

Robolectric 4.2
Android 28

Most helpful comment

@rashikaranpuria

val shadowPackageManager = Shadows.shadowOf(application.packageManager)

val component = ComponentName("com.example", "Example")
shadowPackageManager.addActivityIfNotPresent(component)
shadowPackageManager.addIntentFilterForActivity(component, IntentFilter(MediaStore.ACTION_IMAGE_CAPTURE).apply { addCategory(Intent.CATEGORY_DEFAULT) })

The part required to make it work was to add the category to the Intent Filter otherwise it still wouldn't resolve.

All 3 comments

Try doing
ComponentName activityComponent = new ComponentName("com.example", "Example")
ShadowPackageManager.addActivityIfNotPresent(activityComponent)
addIntentFilterForComponent(activityComponent, new IntentFilter(MediaStore.ACTION_IMAGE_CAPTURE)

@brettchabot The method you mentioned addIntentFilterForComponent is private method and addIntentFilterForActivity does not resolve the issue. How would you suggest doing it now? The JavaDocs point to the private method. I tried using setResolveInfosForIntent but that is also deprecated.

@rashikaranpuria

val shadowPackageManager = Shadows.shadowOf(application.packageManager)

val component = ComponentName("com.example", "Example")
shadowPackageManager.addActivityIfNotPresent(component)
shadowPackageManager.addIntentFilterForActivity(component, IntentFilter(MediaStore.ACTION_IMAGE_CAPTURE).apply { addCategory(Intent.CATEGORY_DEFAULT) })

The part required to make it work was to add the category to the Intent Filter otherwise it still wouldn't resolve.

Was this page helpful?
0 / 5 - 0 ratings