Friday, 23 November 2012
Intent Quick Guide
Intents
Intent are difficult to understand first. I wanted to mention some straightforward uses for Intent. Here it is.
1. Used for communicating between activities.
2. Intent allows to start an activity explicitly or implicit( for this we need to register for particular action)
3. Broadcast message sending is possible with intent.
for example a new SMS comes. applications can register for such events and act accordingly.
Example 1. Explicitly opening an activity.
I this like calling dialog.DoModel() (or modeless) in Windows applications. If you are(was) a MFC programmer , you can remember this that way.
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button id1 = (Button)findViewById(R.id.Button01);
id1.setOnClickListener(new OnClickListener()
{
@Override public void onClick(View v)
{
Intent startSecond = new Intent(IntentDemo.this,SecondActivity.class);
startActivityForResult(startSecond, 101);
}
}
);
Number 101 identifies the request code. When the "SecondActivity" terminates, framework will call a function onActivityResult in the parent activity to inform about the termination of the SecondActivity.
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 101)
{
// SecondActivity is just terminated. Do some useful things here.
}
}
There you can use the that request code to identify the activity which just get terminated.
This is useful in situations where the main activity launches multiple sub activity, and on terminating those main activity need to know it to do some other useful actions..
Example 2. Implicitly opening an activity.
This allows to launch some activity based on some action. Action strings are defined in the Intent class. Lot of actions are available in-order to meet the basic programming requirements.
Say to call a number from your activity , you call Intent like below
This will popup the dialer activity , Of-course you need to have some balance to make further calls.
Intent intent = new Intent(Intent.ACTION_DIAL,Uri.parse("tel:4545-1334"));
startActivity(intent);
While creating a new Intent , we can pass Uri as data. Uri is very generic. So for each intent you need to find the correct Uri data in-order to use it correctly.
Subscribe to:
Comments (Atom)