Share your knowledge

Saturday 11 March 2017

Android Implicit and Explicit Intents

Intents: Intents are used to start components (activity, service, or broadcast receivers) or send data between one component to other component.

Here is the output:



Download source code from here: Intents example

Explicit Intent: 
1. We need to specify name of the component.
2. Explicit intents are used to start the components in the same application
3. Below is the example to start WelcomeActivity



Intent explicitIntent = new Intent(MainActivity.this, WelcomeActivity.class);
startActivity(explicitIntent);



Implicit Intent:


1. Will not specify name of the component
2. System automatically shows the applications(using data in intent filters of other applications) which can handle our task.
3. when starting implicit intent, and if there is no application which can handle your task, then app may crash, so before starting the activity, we have to check whether any application is there to handle our task using resolveActivity.





Example:1

1. suppose we want to view my blogspot("http://andytechs.blogspot.in/")
2. we need webview to load this url
3. instead of using our own webview, i will ask for the system to open any application which canhandle my task(opening that url in the webview)
4. this can be done by using Actions
5. During an implicit intent, the Android system searches for all the registered
components(through intent filters) for the specific action and data type.


If only one component is found, that is triggered but when several of them are identified a dialog ispresented to the user from which he can make a suitable selection.

Intent implicitIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://andytechs.blogspot.in/"));
startActivity(implicitIntent);

  
Example2:

1. let suppose we want to share(send) data in gmail, whatsapp, facebook etc...
2. specify the action(send)
3. setType is used to set the MIME type(In the previous example, we passed url and the system determines theappropriate MIME type required bye the intent.
4. But in the second example we should specify the MIME type using setType(which helps android in determiningwhich activivities should recieve the intent.
5. put extra is used to put the data which we want to share


Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT,"Welcome to android learning tutorials by suresh yadam");

startActivity(shareIntent);


                


No comments:

Post a Comment