Home » Android » When to use which constructor for ComponentName in Android?

When to use which constructor for ComponentName in Android?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I am a little bit confused about the ComponentName class in Android.

There are different ways to get to a component name object, but I don’t know when to use which… and why!

Example:

  • Application package is de.zordid.sampleapp
  • but widget provider class is de.zordid.sampleapp.widget.WidgetProvider

Using

ComponentName cn = new ComponentName("de.zordid.sampleapp.widget",
    "WidgetProvider");

I got this component info: ComponentInfo{de.zordid.sampleapp.widget/WidgetProvider}, but I could not use this – the component is unknown!
But the JavaDoc says I should give the package and the class within that package – and that is what I did, didn’t I??

Using

ComponentName cn = new ComponentName(context, WidgetProvider.class);

yields ComponentInfo{de.zordid.sampleapp/de.zordid.sampleapp.widget.WidgetProvider} – and that works fine!!

There is even another way to get a ComponentName – by context and a string.
Which one should be used where and when??

Thanks!

How to&Answers:

The ComponentName constructor taking two Strings can be used to refer to a component in another application. But, the first argument is not the package name of the class; it is the package name of the application—the package attribute of the manifest element in that application’s AndroidManifest.xml. So your first example should be

ComponentName cn = new ComponentName("de.zordid.sampleapp",
    "de.zordid.sampleapp.widget.WidgetProvider");

That constructor could certainly be used to refer to components in your own application, but since you already have hold of a Context from your own application you might as well use it and use one of the other constructors. In my opinion, the one taking a Class should be preferred whenever usable. You could use the one taking a String if you only know the class dynamically for some reason; in that case, it should take the fully-qualified class name as above.

Answer:

Robert Tupelo-Schneck‘s answer is right about preferring objects against Strings. Here’s how I see it.

  • To refer to your own components, use:

    new ComponentName(getApplicationContext(), WidgetProvider.class);
    
  • To refer to some dynamically referenced component in your own app, use:

    // values/strings.xml: <string name="provider">de.zordid.sampleapp.widget.WidgetProvider</string>
    String fqcn = getResources().getString(R.string.provider);
    new ComponentName(getApplicationContext(), fqcn);
    

    This is useful when you want to use Android’s resource qualifiers to decide which component to use, you can override the default string in values-*/strings.xml.

  • To refer to another application’s component, use:

    int componentFlags = GET_ACTIVITIES | GET_PROVIDERS | GET_RECEIVERS | GET_SERVICES;
    PackageInfo otherApp = context.getPackageManager().getPackageInfo("com.other.app", componentFlags);
    ComponentInfo info = otherApp.activities[i]; // or providers/receivers/...
    new ComponentName(info.packageName, info.name);
    

About .Names and <manifest package="

There may be some confusion here because I think historically Robert’s statement was true:

it is the package name of the application—the package attribute of the manifest element in that application’s AndroidManifest.xml

but not any more. Since the new Gradle build system was introduced there has been some changes around here.

If you have an android.defaultConfig.applicationId specified in your build.gradle that’ll be the app package name, and then package attribute in manifest is a separate thing when building your app. The first argument of ComponentName now refers to applicationId + applicationIdSuffix. The tricky thing is that after the final manifest merge and packaging the APK will have <manifest package=applicationId + applicationIdSuffix and all the .Names will be expanded to FQCNs.

Example app for learning name resolution

Here’s an example structure based on the structure of one of my apps. Consider the following classes in a hypothetical app called “app”:

  • net.twisterrob.app.android.App
  • net.twisterrob.app.android.GlideSetup
  • net.twisterrob.app.android.subpackage.SearchResultsActivity
  • net.twisterrob.app.android.subpackage.Activity
  • net.twisterrob.app.android.content.AppProvider

on the server side backend of the app and/or some shared model classes:

  • net.twisterrob.app.data.*
  • net.twisterrob.app.backend.*
  • net.twisterrob.app.web.*

in my Android helper library:

  • net.twisterrob.android.activity.AboutActivity

other libraries:

  • android.support.v4.content.FileProvider

This way everything is namespaced in net.twisterrob.app. The android app being just a single part of the whole inside it’s own subpackage.

AndroidManifest.xml (irrelevant parts omitted)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="net.twisterrob.app.android">
    <!--
    `package` above defines the base package for .Names
    to simplify reading/writing the manifest.
    Notice that it's different than the `applicationId` in build.gradle
    and can be independently changed in case you want to refactor your packages.
    This way you can still publish the same app with the same name.
    -->

    <!-- Will be expanded to net.twisterrob.app.android.App in the manifest merging phase. -->
    <application android:name=".App">
        <!-- meta-data needs FQCNs because the merger can't know if you want to expand them or not.
             Also notice that name and value both can contain class names, depending on what you use. -->
        <meta-data android:name="net.twisterrob.app.android.GlideSetup" android:value="GlideModule" />
        <meta-data android:name="android.app.default_searchable" android:value="net.twisterrob.app.android.subpackage.SearchResultsActivity" />
        <!-- Will be expanded to net.twisterrob.app.android.subpackage.Activity in the manifest merging phase. -->
        <activity android:name=".subpackage.Activity" />
        <!-- Needs full qualification because it's not under the package defined on manifest element. -->
        <activity android:name="net.twisterrob.android.activity.AboutActivity" />
        <!-- Will be expanded to net.twisterrob.app.android.content.AppProvider in the manifest merging phase. -->
        <provider android:name=".content.AppProvider" android:authorities="${applicationId}" />
        <!-- Needs full qualification because it's not under the package defined on manifest element. -->
        <provider android:name="android.support.v4.content.FileProvider" android:authorities="${applicationId}.share" />
    </application>
    <!-- ${applicationId} will be replaced with what's defined in `build.gradle` -->
</manifest>

build.gradle

android {
    defaultConfig {
        // this is what will be used when you upload it to the Play Store
        applicationId 'net.twisterrob.app'
    }
    buildTypes {
        debug {
            // The neatest trick ever!
            // Released application: net.twisterrob.app
            // IDE built debug application: net.twisterrob.app.debug
            // This will allow you to have your installed released version
            // and sideloaded debug application at the same time working independently.
            // All the ContentProvider authorities within a system must have a unique name 
            // so using ${applicationId} as authority will result in having two different content providers.
            applicationIdSuffix '.debug'
        }
    }
}

To check out what your final manifest will look like after all the merging open build\intermediates\manifests\full\debug\AndroidManifest.xml.

Answer:

Or you can use like this inside BroadcastReceiver :

ComponentName smsReceiver = new ComponentName(this, SMSReceiver.class);