Pages

Saturday, May 14, 2016

Android Intents part 1

In this post we are going to explore the concept of intents in Android.

Intents are used by an application to interact with the phones hardware components or other applications, or to start a service or activity with a certain peice of data or to broadcast that an event has occurred.

Using Intents to launch phone activities:
we can use Intents to launch the phones basic activities such as the phone dialer, the browser or search.

these intents are called implicit intents cause you dont specify the activity you want to launch, rather Android determines the proper activity to launch based on the required action. also when the launched activity finisheds its work, the original activity has no information that the launched activity has finished its work

in this example we create an intent that performs a phone number dial action. we don not specify that we want the dialer activity to launch, rather we specify that we want to dial a number and Android launches the dialer activity to perform this action

consider this activity: consists of a TextView and a button to dial the number in the text view.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android_orientation="vertical"
android_layout_width="fill_parent"
android_layout_height="fill_parent"
>
<TextView
android_layout_width="fill_parent"
android_layout_height="wrap_content"
android_text="Enter the phone number"
/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/txtNumber"
android:inputType="phone"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dial"
android:id="@+id/btnDial"
/>
</LinearLayout>




When you press the button the phone dialer launches and then you can call the number.
this is done using the following code
btnDial.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
// TODO Auto-generated method stub

Intent dialIntent=new Intent(Intent.ACTION_DIAL,Uri.parse("tel:"+(txtNumber.getText()).toString()));

startActivity(dialIntent);
}
});

notice that the dialer has been launched but the user has to press the call button to make a call.



if you want the phone to dial the number autom atically you could have used this intent
Intent.ACTION_CALL
but this requires ading the following permission to the manifest file:
<uses-permission android_name="android.permission.CALL_PHONE">
and that was how to launch the phone activities using intents.
for a list of available phone actions, check this link

Related Posts by Categories

0 comments:

Post a Comment