Implement Share App Facility in static Shortcuts

168 views Asked by At

I was trying to implement "Share App" facility as App Shortcut in Android (like iOS platform). This facility must exist immediately after installing even without opening app. I want to know how I can use this intent in shortcut xml file:

Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.putExtra(Intent.EXTRA_TEXT, "https://www.example.com");
        intent.setType("text/plain");
1

There are 1 answers

3
Nava On

I didn't find any way to put type attribute for intent in xml. But it seems an activity with invisible theme can simulate what I want.

As documentation said:

Start one activity from another

Static shortcuts cannot have custom intent flags. The first intent of a static shortcut will always have Intent.FLAG_ACTIVITY_NEW_TASK and Intent.FLAG_ACTIVITY_CLEAR_TASK set. This means, when the app is already running, all the existing activities in your app are destroyed when a static shortcut is launched. If this behavior is not desirable, you can use a trampoline activity, or an invisible activity that starts another activity in Activity.onCreate(Bundle), then calls Activity.finish():

In the AndroidManifest.xml file, the trampoline activity should include the attribute assignment android:taskAffinity="". In the shortcuts resource file, the intent within the static shortcut should reference the trampoline activity. For more information about trampoline activities, read Start one activity from another.

we can add android:taskAffinity="" to the InvisibleActivity in manifest file to prevent the app from going to background when home button clicked.

This is my invisible activity setup in AndroidManifest.xml

<activity
    android:name=".InvisibleActivity"
    android:excludeFromRecents="true"
    android:taskAffinity=""
    android:noHistory="true"
    android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen" />

This is the whole onCreate() method in my invisible activity:

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.putExtra(Intent.EXTRA_TEXT, "https://www.example.com");
    sendIntent.setType("text/plain");
    startActivity(sendIntent);
    finish();
}

and finally this is my static shortcut xml file:

<shortcut
    android:enabled="true"
    android:shortcutId="share_app_shortcut"
    android:icon="@drawable/ic_share"
    android:shortcutShortLabel="@string/shortcut_share_description">

    <intent
        android:action="android.intent.action.VIEW"
        android:targetClass=".InvisibleActivity"
        android:targetPackage="com.example.shortcut">
    </intent>

</shortcut>