Unable to create application's shortcut on Hom

2019-08-23 06:53发布

问题:

I want to create a shortcut of the application on home screen when it is installed.

I added this to AndroidManifest.xml

<activity
        android:name="com.example.test.ShortCutActivity"
        android:icon="@drawable/ic_launcher"
        android:label="@string/title_activity_short_cut" >

        <intent-filter>
            <action android:name="android.intent.action.CREATE_SHORTCUT" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>

</activity>

Also I have a Actvity created with ShortCutActivity name in my project.

ShortCutActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ShortcutIconResource icon =
            Intent.ShortcutIconResource.fromContext(this, R.drawable.ic_launcher);

        Intent intent = new Intent();

        Intent launchIntent = new Intent(this,MainActivity.class);

        intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launchIntent);
        intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "ShortCut");
        intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);

        setResult(RESULT_OK, intent);
}

But it is not creating any shortcut. Am I missing something ?

回答1:

Use this sample code in your activity which is set as a LAUNCHER and MAIN in AndroidManifest.xml

private void createShortcut(){
     Intent shortcutIntent = new Intent(getApplicationContext(),MainActivity.class);
     shortcutIntent.setAction(Intent.ACTION_MAIN);
     Intent intent = new Intent();
     intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
     intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "ShortcutDemo");
     intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.drawable.ic_launcher));
     intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
     getApplicationContext().sendBroadcast(intent);
}

Also apply following permissions in your AndroidManifest.xml

  <uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />

Hope this will work for you



回答2:

Intent shortcutIntent = new Intent(Intent.ACTION_MAIN);     
shortcutIntent.setClassName(this, this.getClass().getName()); 

Intent intent = new Intent();     
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);     
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "hello");     
Parcelable iconResource = Intent.ShortcutIconResource.fromContext(this, R.drawable.icon);

intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);  
intent.setAction(Intent.ACTION_CREATE_SHORTCUT);

getApplicationContext().sendBroadcast(intent);