在我的 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
级别的 Intent
。 Intent
对象不是要“发送”到那里,而是要发送到 Activity
、Service
或 BroadcastReceiver
。
关于android - getExtras() 在应用程序级别(-class)返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38696195/