android - getExtras() 在应用程序级别(-class)返回 null

标签 android android-intent android-activity android-package-managers android-application-class

在我的 Application 级别上,我收到 getExtras()null,但在 Activity 级别上我可以看到他们正确。

public class MyApplication extends Application 
{
    @Override
    public void onCreate() {
        super.onCreate();
        Intent intent = getPackageManager().getLaunchIntentForPackage("com.example.MyApp");
        if (intent != null){
            String mStaticWorldUrl = intent.getStringExtra("arg1Name");
            String mStaticWorldIconUrl = intent.getStringExtra("arg2Name");
            Log.i("LOG", mStaticWorldUrl + " ---  " + mStaticWorldIconUrl);
        }
    }
}

我正在通过这段代码创建的一些快捷方式调用应用程序:
(- 每个快捷方式都有不同的 Extras 发送到 Intent)

    // create a shortcut for the specific app
public static void createShortcutForPackage(Context context,
        String packageName, String className, String shortcutName,
        String arg1Name, String arg1Val, String arg2Name, String arg2Val,
        int iconID) {

    Intent intent = new Intent();
    intent.setComponent(new ComponentName(packageName, className));

    PackageManager pm = context.getPackageManager();

    Context pkgContext = createPackageContext(context, packageName);
    if (pkgContext == null)
        return;

    Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
    Intent shortcutIntent = pm.getLaunchIntentForPackage(packageName);

    if (arg1Name != null)
        shortcutIntent.putExtra(arg1Name, arg1Val);

    if (arg2Name != null)
        shortcutIntent.putExtra(arg2Name, arg2Val);

    shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
    shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, shortcutName);
    shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,Intent.ShortcutIconResource.fromContext(context, iconID));
    shortcut.putExtra("duplicate", false);
    context.sendBroadcast(shortcut);
}  

如何在Application 级别阅读这些Extras
或者是否有任何其他方法可以为应用程序创建不同的快捷方式并在 Application 上读取其“参数”数据?

最佳答案

Application 类对于应用程序是静态的:对于您的应用程序进程,它只有一个实例。如果您的应用是使用正常启动 Intent 启动的,而不是您创建的快捷方式,则不会出现任何额外内容。当按下 HOME 或 BACK 时,应用程序进程不会终止,因此用于启动程序包的 Intent 可能不是您认为应该的那样。

您不需要查看 Application 级别的 IntentIntent 对象不是要“发送”到那里,而是要发送到 ActivityServiceBroadcastReceiver

关于android - getExtras() 在应用程序级别(-class)返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38696195/

相关文章:

java - 从 Android 上的日历提供程序中删除事件

java - 使用 Java 而不是 xml 时多行文本中的不同行为

Android:如果我在具有 API 24 或 25 (Nougat) 的设备上运行该应用程序,它会崩溃

Android:搜索 Intent 不起作用

android - 再次打包相同对象时获取解码未知类型代码

java - 有很多 Activity 好吗

android - 是否有一致的方式将数据发送到 Android Activity ,如果 Activity 尚未打开则打开该 Activity ?

android - 无法扩展 ListFragment - "Call requires API level 11"

android - ADT 不会加载目标平台,即使它们已安装。怎么修?

java - 在 if else 的情况下 Intent 不起作用