We can also communicate with the other apps activities using Intent. This is done using the implicit Intent.
Before using the implicit intent these are some of the question you need to answer.
Q.1 How do we know activities are available on the user’s device?
Q 2. How do we know which of these activities are appropriate for what we want to do?
Q 3. How do we know how to use these activities?
The answer to all these question is 'actions'.
Actions are a way of telling Android what standard operations activities can perfom. As an example, Android knows that all activities registered for a send action are capable of sending messages.
Create the implicit intent:
Intent intent = new Intent(action);
where action is the type of activity action you want to perform. Android provides you with a number of standard actions you can use. As an example, you can use Intent.ACTION_DIAL to dial a number, Intent.ACTION_WEB_SEARCH to perform a web search, and Intent.ACTION_SEND to send a message. So if you want to create an intent that specifies you want to send a message, you use
Intent intent = new Intent(Intent.ACTION_SEND);
Adding extra information:
Once you have specified the action you want to use then you can add extra data to it.
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, messageText);
where messageText is the text you want to send. This tells Android that you want the activity to be able to handle data with a MIME data-type of “text/plain”, and also tells it what the text is. You can make extra calls to the putExtra() method if there’s additional information you want to add. As an example, if you want to specify the subject of the message, you can also use
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
where subject is the message subject.
The attritubes such as Intent.EXTRA_TEXT are only associated with the ACTION_SEND not with the other types of actions.
As we are also specifies then android will only target those app that also takes subject along with message such as gmail ignore other apps like WhatsApp which do not support subject.
Finally,
startActivity(intent);
To start the activity.
How the code works:
1)The Intent object is created. startActivity() passes the intent to the android.
2)Android analyse the intent checks which type of action the intent wants the android to perform.Then android checks all the apps activities that are able to receive the intent. If no activities are present to handle that intent it will then throw ActivityNotFoundException.
3) If just one activity is able to handle these intent, Android directly start the intent.If multiple activities are there,Android display an activity chooser dialog and asks the user to choose one.
4)When the user chooses the activity she wants to use, Android tells the activity to start and passes it the intent.

Comments
Post a Comment