Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Launch android app with parameters - shortcut

Tags:

android

I developed an Android app which read a config file.
Now, I would like load my app with another file config.

In fact, I would like create 2 shortcuts of my app:

  • myApp filepathconfig1
  • myApp filepathconfig2

Is it possible?
If yes, how get the parameters in my code?

Thanks for your help

like image 826
lg0173 Avatar asked Oct 18 '25 01:10

lg0173


1 Answers

This is easy to do on Android 7.1 Nougat API level 25 or higher.

There is a dedicated Shortcut API that lets you define shortcuts to you activity with specific Intent where you can add extras like this:

<intent
    android:action="android.intent.action.LAUNCH_WITH_CONFIG"
    android:targetPackage="com.example.myapplication"
    android:targetClass="com.example.myapplication.ComposeActivity" >

    <extra android:name="configFile" android:value="filepathconfig1" />

</intent>

The code above is base on an example here.

EDIT BASED ON COMMENT: You can also add and remove shortcuts dynamically as described here. You will need some UI in you app to manage the shortcuts if you want to change them as a user, without recompiling.

To access the extra in you code, just do this in you activity class:

String configPath = getIntent().getStringExtra("configFile");

How ever, if you need to support Android versions before 7.1, it gets more complicated.

There are two options I can think of: The first one is using <activity-alias> as described here.

Note however that the author of that question states that it is not guaranteed to work on all devices.

Another option is to create two dummy launcher activities that will be invisible and will finish() immediately after starting you real main activity with the correct parameter.

This is the ugliest hack in my opinion but also most reliable and universal one for this problem.

In your manifest, set activity theme to android:theme="@android:style/Theme.Translucent.NoTitleBar"

In this activity's onCreate add code like this:

Intent i = new Intent(this, RealMainActivity.class);
i.puStringExtra("configFile", "filepathconfig1");
startActivity(i);
finish();

I see from your comment you want this to work dynamically, without recompiling the APK, but Android launchers do not support such a feature. At least, I never heard of one that does.

It is possible to create such a launcher though.

The only way currently to start you activity with dynamic parameters is from adb:

adb shell am start com.myactivity --es configFile configFilePath

For more details read this.

like image 167
Lev M. Avatar answered Oct 20 '25 16:10

Lev M.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!