Android广播发送应用包名

Android Broadcast Sending app's package name

我知道 BroadcastReceiver feature/functionality 在 Android 中是如何工作的,并且我已经实现了我的应用程序将接收或发送的多个操作。

但是,每当我的某个应用程序收到广播时,我想知道是哪个应用程序发送了该广播。

例子(我有三个应用):
Application AApplication B 可以向 Application C 发送广播。

Application C收到广播时,我想知道这个广播是哪个应用发出的,是Application A还是Application B

注意:我知道我可以在 Intent 中添加 extra 并发送包名称,但是我正在寻找 "auto-generated" 的字段。我不想每次都执行以下操作:

intent.putExtra("package_name", getPackageName());

理由,你问?以上只是一个例子。可能有两个以上的应用程序发送广播,我不希望它们每次都在 Intent 中发送包名。

我也注意到 IntentgetPackage() 方法,但是总是 returns null.

@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    switch (action) {
        case MY_GLOBAL_ACTION:
            // this is where I want the package name of the application that sent the broadcast
            intent.getPackage(); // this is always null
            break;
        default:
            break;
    }
}

I want to know which application sent this broadcast, either Application A or Application B?

将其添加为额外内容。

I am looking for a field that is "auto-generated".

有none。默认情况下,Intent 不包含有关创建 Intent 的应用的信息,HashMap 包含的信息也不多。

I also noticed there is getPackage() method for Intent, however that always returns null.

据推测,那是因为您没有调用 setPackage()。而且,由于该包裹无法识别发件人,因此对您没有帮助。