gpt4 book ai didi

android - 如何从库中启动 android 应用程序中的 Activity

转载 作者:搜寻专家 更新时间:2023-11-01 07:50:22 25 4
gpt4 key购买 nike

我在 Android Studio 中有一个 Android 应用程序。我在应用程序中添加了一个库。按钮、 View 和 Activity 在库中定义。当我单击按钮时,我需要导航到应用程序中定义的 Activity 。

通常,为了导航到另一个页面,我们使用这样的 Intent :

Intent intent = new Intent(MainActivity.this, Activity.class);
startActivity(intent);

但这不是从库中调用应用程序 Activity 的充分方法。

问题是库和应用是独立的;他们有不同的包裹。因此应用程序中的 Activity 无法被库识别。

我如何处理库和应用程序之间的通信?

最佳答案

通常的做法是:

Intent intent = new Intent();
intent.setComponent(new ComponentName("com.my.package","com.my.package.activity.ActivityName");
startActivity(intent);

这是对您图书馆内 Activity 的明确引用。您应该确保在启动此 Activity 时捕获 ActivityNotFoundException,因为当系统中不存在该 Activity 时可能会发生这种情况。

理想情况下,在构建此 Intent 时,您应该确保可以使用 PackageManager API 解析它。

然而,您应该尽量避免对包进行硬编码,但是当涉及到库时,有时您别无选择。

还需要注意的一件事是,在库中,您需要确保 Activity 已导出,以便您可以在应用程序之外访问它。

android:导出

Whether or not the activity can be launched by components of other applications — "true" if it can be, and "false" if not. If "false", the activity can be launched only by components of the same application or applications with the same user ID. The default value depends on whether the activity contains intent filters. The absence of any filters means that the activity can be invoked only by specifying its exact class name. This implies that the activity is intended only for application-internal use (since others would not know the class name). So in this case, the default value is "false". On the other hand, the presence of at least one filter implies that the activity is intended for external use, so the default value is "true".

This attribute is not the only way to limit an activity's exposure to other applications. You can also use a permission to limit the external entities that can invoke the activity (see the permission attribute).

引用

http://developer.android.com/guide/topics/manifest/activity-element.html

关于android - 如何从库中启动 android 应用程序中的 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35593835/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com