如何显式启动另一个模块中的活动 [英] how to start an activity in another module explicitly

查看:53
本文介绍了如何显式启动另一个模块中的活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个aar并将其作为模块添加到我的项目中.在此模块中,我具有要运行的HelloWorldActivity.

I created an aar and i added it to my project as an module. in this module i have a HelloWorldActivity that i want to run.

我的模块清单看起来像这样.

my module manifest looks like this.

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="ir.sibvas.testlibary1.HelloWorldActivity"
        android:label="@string/app_name" >

        <intent-filter>
            <action android:name="ir.sibvas.testlibary1.HelloWorldActivity" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

    <activity
        android:name=".MainActivity"
        android:label="@string/title_activity_main" >

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>


    </activity>
</application>

现在,我可以使用此代码从我的项目开始此活动

Now i can start this activity from my project using this code

 Intent intent = new Intent("ir.sibvas.testlibary1.HelloWorldActivity");
 startActivity(intent);

但是如您所见,此代码是隐式的,隐式调用的问题是,如果我在多个应用程序中使用此模块,两个模块都安装在用户设备上,则会向用户显示一个应用程序选择器对话框.那么如何使该调用变得明确,从而防止用户切换应用程序?

but as you can see this code is implicit and problem with implicit calling is that if i use this module in more than one app, both installed on user device it will show an app chooser dialog to user. So how can make this call explicit, preventing user from switching app?

此代码将无法运行,因为HelloWorldActivity与调用活动不在同一个程序包中

this code will not run since HelloWorldActivity is not in the same package as calling activity

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

我真的不想为每个使用它的项目更改模块.

I really don't want to change my module for each project that uses it.

推荐答案

您可以使用Class.forName(),它在需要我启动项目中另一个模块中的活动时对我有用.

You can use the Class.forName(), it worked for me when i was needed to start activity which is in another module in my project.

 Intent intent = null;
    try {
        intent = new Intent(this, 
           Class.forName("ir.sibvas.testlibary1.HelloWorldActivity"));
        startActivity(intent);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

这篇关于如何显式启动另一个模块中的活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆