How to start an activity in an android Application from the Library

后端 未结 4 564
不思量自难忘°
不思量自难忘° 2021-02-11 07:22

I have an Android application in Android Studio. And I\'ve added a library into the application. The button, view, and activities are defined in the library. When I click on the

4条回答
  •  有刺的猬
    2021-02-11 08:03

    The normal way for doing this is to do this:

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

    This is an explicit reference to an activity within your library. You should ensure that when starting this Activity that you catch the ActivityNotFoundException as this can happen when the Activity does not exist in the system.

    Ideally when building this Intent you should insure that you can resolve it by using PackageManager APIs.

    However you should try to avoid hardcoding packages, but when it comes to a library, sometimes you don't have a choice.

    Also one thing to note is that within the library you need to ensure that the Activity is exported so that you can access it outside of your application.

    android:exported

    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).

    Ref

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

提交回复
热议问题