How to open my app activity from app shortcut selection?

2.6k views Asked by At

i have small practice app. i put some dynamic shortcut for my app.all shortcut works like i can able to open site from shortcut(google docs example) but now i want to open particular activity from this shorcut .so how can i do this.

here is image of shortcuthere is what i have now

and here is code of my work.

  findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //open activity.
            Intent intent=new Intent(MainActivity.this,Main2Activity.class);                   
            ShortcutManager shortcutManager= (ShortcutManager) getSystemService(SHORTCUT_SERVICE);

            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N_MR1) {
                ShortcutInfo shortcutInfo=new ShortcutInfo.Builder(MainActivity.this,"shortcutID")
                        .setShortLabel("Shortcut Label")
                        .setIcon(Icon.createWithResource(MainActivity.this, R.drawable.ic_message))
                        .setIntent(new Intent(Intent.ACTION_VIEW))                         
                        .setActivity()
                        .build();  
                      shortcutManager.addDynamicShortcuts(Arrays.asList(shortcutInfo));
            }       
        }
    });

so how can i open activity from first shortcut selection .waiting for reply

2

There are 2 answers

2
JingJoeh On BEST ANSWER

Create your intent for a specific component with a specified action and data like this.

 Intent intent = new Intent(Intent.ACTION_VIEW, null, MainActivity.this, Main2Activity.class);

And your shortcut set it with

.setIntent(intent)
1
Andrew Steinmetz On

You have a couple of options to launch an activity from a dynamic shortcut.

In your .setActivity(), you can pass the desired activity class.

https://developer.android.com/reference/android/content/pm/ShortcutInfo.Builder.html#setActivity(android.content.ComponentName)

Or if you app links setup with intent filters to that activity, how I've done it passing in a URI.

setIntent(Intent(Intent.ACTION_VIEW,
                    Uri.parse("youapplication.uri.com/myintentfilter)))

https://developer.android.com/reference/android/content/pm/ShortcutInfo.Builder.html#setIntent(android.content.Intent)

Or you can launch multiple intents if you wanted activities to be on the backstack by using the setIntents()

https://developer.android.com/reference/android/content/pm/ShortcutInfo.Builder.html#setIntents(android.content.Intent[])

JingJoeH also had a good answer that is slightly simpler in implementation https://stackoverflow.com/a/48092366/7900721