how to start an activity in another module explicitly

拈花ヽ惹草 提交于 2020-02-26 08:00:05

问题


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?

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.


回答1:


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();
    }



回答2:


first module activity launch then second module activity launch and write a line of code is perfectly fine.

 Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.your.packagename");
            if (launchIntent != null) {
                startActivity(launchIntent);//null pointer check in case package name was not found
            }



回答3:


The explicit assignment:

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

should work fine provided you have added the import for HelloWorldActivity.class with the full package name of your module viz. ir.sibvas.testlibary1.HelloWorldActivity



来源:https://stackoverflow.com/questions/33429784/how-to-start-an-activity-in-another-module-explicitly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!