How to export an activity so other apps can call it?

为君一笑 提交于 2019-11-28 01:49:54

You need to declare an intent-filter in your Manifest (I took the following example from Barcode Scanner) :

<activity android:name="...">
    <intent-filter>
        <action android:name="com.google.zxing.client.android.SCAN" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

Then create an intent with the same action string :

Intent intent = new Intent("com.google.zxing.client.android.SCAN");
startActivityForResult(intent, code);

Android should start your activity (or it will show a drop-down box if there are multiple apps sharing the same action string).

As an alternate to Dalmas' answer, you can actually export an Activity without creating an <intent-filter> (along with the hassle of coming up with a custom action).

In the Manifest edit your Activity tag like so:

<activity
    android:name=".SomeActivity"
    ....
    android:exported="true" />

The important part is android:exported="true", this export tag determines "whether or not the activity can be launched by components of other applications". If your <activity> contains an <intent-filter> then this tag is set to true automatically, if it does not then it is set to false by default.

Then to launch the Activity do this:

Intent i = new Intent();
i.setComponent(new ComponentName("package name", "fully-qualified name of activity"));
startActivity(i);

Of course with this method you will need to know the exact name of the Activity you are trying to launch.

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