How to launch an Activity from another Application in Android
In order to launch an Activity from another app, you need to create an Intent
and set its ComponentName
to the package and Activity class name of the external app:
Remember, the exported attribute of the target Activity should be set to true in the external app's AndroidManifest.xml
. Alternatively, if you are launching the Activity outside an Activity context, use intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.
To launch the main Activity of the other app, use the getLaunchIntentForPackage
method:
Best practices for app-to-app interaction
When initiating activity launch from another application, a few best practices would ensure smooth operation:
- Before invoking
startActivity
, check thatlaunchIntent
isn't null to avoid crashes. - Implement a try-catch when using
getPackageManager()
to handle instances where the package isn't found (NameNotFoundException
). - Should the desired app be absent from the device, you could consider redirecting the user to the Play Store for app installation. This can be achieved using
Intent.ACTION_VIEW
and a specific app market URI.
Handling varied scenarios
Launching activities from another application may vary significantly based on different situations. Here are a few common cases:
When the package may not be installed:
To start a specific Activity within an app:
To check if an app is enabled before launching:
Enhancing reusability and compatibility
In the spirit of DRY code, consider embodying all these checks within a re-usable function. Here is an example:
Accessing apps through unique identifiers
In Android, every app is identified by its unique package name. This means we can pinpoint the exact app we're looking for by using the package name.
Common pitfalls and prevention techniques
Adhering to best practices when launching an app from another will prevent errors:
- Use
getLaunchIntentForPackage
to get the main activity, or define the component name for a specific activity. - Include null checks and exception handling to avoid crashes.
- Seek the help of
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
when you want to launch an activity from a non-activity context. - If the target app isn't installed, consider redirecting the user to the Play Store.
Was this article helpful?