Call events in android

Android — Event Handling

Events are a useful way to collect data about a user’s interaction with interactive components of Applications. Like button presses or screen touch etc. The Android framework maintains an event queue as first-in, first-out (FIFO) basis. You can capture these events in your program and take appropriate action as per requirements.

There are following three concepts related to Android Event Management −

Event Listeners − An event listener is an interface in the View class that contains a single callback method. These methods will be called by the Android framework when the View to which the listener has been registered is triggered by user interaction with the item in the UI.

Event Listeners Registration − Event Registration is the process by which an Event Handler gets registered with an Event Listener so that the handler is called when the Event Listener fires the event.

Event Handlers − When an event happens and we have registered an event listener for the event, the event listener calls the Event Handlers, which is the method that actually handles the event.

Event Listeners & Event Handlers

This is called when the user either clicks or touches or focuses upon any widget like button, text, image etc. You will use onClick() event handler to handle such event.

This is called when the user either clicks or touches or focuses upon any widget like button, text, image etc. for one or more seconds. You will use onLongClick() event handler to handle such event.

This is called when the widget looses its focus ie. user goes away from the view item. You will use onFocusChange() event handler to handle such event.

This is called when the user is focused on the item and presses or releases a hardware key on the device. You will use onKey() event handler to handle such event.

This is called when the user presses the key, releases the key, or any movement gesture on the screen. You will use onTouch() event handler to handle such event.

This is called when the user selects a menu item. You will use onMenuItemClick() event handler to handle such event.

This is called when the context menu is being built(as the result of a sustained «long click)

There are many more event listeners available as a part of View class like OnHoverListener, OnDragListener etc which may be needed for your application. So I recommend to refer official documentation for Android application development in case you are going to develop a sophisticated apps.

Event Listeners Registration

Event Registration is the process by which an Event Handler gets registered with an Event Listener so that the handler is called when the Event Listener fires the event. Though there are several tricky ways to register your event listener for any event, but I’m going to list down only top 3 ways, out of which you can use any of them based on the situation.

Using an Anonymous Inner Class

Activity class implements the Listener interface.

Using Layout file activity_main.xml to specify event handler directly.

Below section will provide you detailed examples on all the three scenarios −

Touch Mode

Users can interact with their devices by using hardware keys or buttons or touching the screen.Touching the screen puts the device into touch mode. The user can then interact with it by touching the on-screen virtual buttons, images, etc.You can check if the device is in touch mode by calling the View class’s isInTouchMode() method.

Focus

A view or widget is usually highlighted or displays a flashing cursor when it’s in focus. This indicates that it’s ready to accept input from the user.

isFocusable() − it returns true or false

isFocusableInTouchMode() − checks to see if the view is focusable in touch mode. (A view may be focusable when using a hardware key but not when the device is in touch mode)

onTouchEvent()

Event Handling Examples

Event Listeners Registration Using an Anonymous Inner Class

Here you will create an anonymous implementation of the listener and will be useful if each class is applied to a single control only and you have advantage to pass arguments to event handler. In this approach event handler methods can access private data of Activity. No reference is needed to call to Activity.

But if you applied the handler to more than one control, you would have to cut and paste the code for the handler and if the code for the handler is long, it makes the code harder to maintain.

Following are the simple steps to show how we will make use of separate Listener class to register and capture click event. Similar way you can implement your listener for any other required event type.

Event Handler Event Listener & Description
onClick()
Step Description
1 You will use Android studio IDE to create an Android application and name it as myapplication under a package com.example.myapplication as explained in the Hello World Example chapter.
2 Modify src/MainActivity.java file to add click event listeners and handlers for the two buttons defined.
3 Modify the detault content of res/layout/activity_main.xml file to include Android UI controls.
4 No need to declare default string constants.Android studio takes care default constants.
5 Run the application to launch Android emulator and verify the result of the changes done in the aplication.

Following is the content of the modified main activity file src/com.example.myapplication/MainActivity.java. This file can include each of the fundamental lifecycle methods.

Following will be the content of res/layout/activity_main.xml file −

Here abc indicates about tutorialspoint logo

Following will be the content of res/values/strings.xml to define two new constants −

Following is the default content of AndroidManifest.xml

Let’s try to run your myapplication application. I assume you had created your AVD while doing environment setup. To run the app from Android Studio, open one of your project’s activity files and click Run icon from the toolbar. Android Studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −

Now you try to click on two buttons, one by one and you will see that font of the Hello World text will change, which happens because registered click event handler method is being called against each click event.

Exercise

I will recommend to try writing different event handlers for different event types and understand exact difference in different event types and their handling. Events related to menu, spinner, pickers widgets are little different but they are also based on the same concepts as explained above.

Источник

Input Events in Android with Example

In Android, there’s quite a method to intercept the events from a user’s interaction with your application. When considering events within your interface, the approach is to capture the events from the precise View object that the user interacts with. The View class provides the means to try to do so. Within the varied View classes that you’re going to use to compose your layout, you’ll notice several public callback methods that look useful for UI events. These methods are called by the Android framework when the respective action occurs thereon object. For instance, when a View (such as a Button) is touched, the onTouchEvent() method is named thereon object. However, to intercept this, you must extend the class and override the method. However, extending every View object to handle such an event would not be practical. This is why the View class also contains a set of nested interfaces with callbacks that you simply can far more easily define. These interfaces, called Event listeners, are your ticket to capturing the user interaction together with your UI.

For Example, if a button is to reply to a click event it must register to look at the .onClickListener event listener and implement the corresponding onClick() callback method. In an application when a button click event is detected, the Android framework will call the onClick() method of that particular view.

Android Event Listeners

Event Listener is an interface within the View class that contains one call-back method. These methods are going to be called by the Android framework when the View which is registered with the listener is triggered by user interaction with the item in UI. Included in the event listener interfaces are the following callback methods:

Description

onClick()

This method is called when the user touches the item or focuses upon the item with the navigation-keys or trackball and presses the suitable “enter” key or presses down on the trackball.

onLongClick()

This is called when the user either touches and holds the item, or focuses upon the item with the navigation-keys or trackball and presses and holds the suitable “enter” key or presses and holds down on the trackball (for one second).

onFocusChange()

This is called when the user navigates onto or away from the item, using the navigation-keys or trackball.

onKey()

This is called when the user is focused on the item and presses or releases a hardware key on the device.

onTouch()

This is called when the user acts qualified as a touch event, including a press, a release, or any movement gesture on the screen (within the bounds of the item).

onCreateContextMenu()

This is called when a Context Menu is being built (as the result of a sustained “long click”).

onClick() callback does not return any value. But onLongClick(), onKey(), onTouch() callback returns a boolean value that indicates that you simply have consumed the event and it should not be carried further; That is, return true to indicate that you have handled the event and it should stop here; return false if you’ve not handled it and/or the event should continue to any other on-click listeners.

Android Event Listener Registration

Event Registration is the process by which an Event Handler gets registered with an Event Listener so that the handler is called when the Event Listener fires the event. This example illustrates how to register an on-click listener for a Button

Источник

How to Make Calls and Use SMS in Android Apps

In this tutorial, you’ll learn about the Android Telephony and SMS API. You’ll learn how to make a call from your app and how to monitor phone call events, as well as how to send and receive SMS.

1. How to Make A Call

To start off, I’ll show you how to initiate a call from your application either by using the phone dialer app or directly from your app to make it easier for your users.

Create a New Android Studio Project

Fire up Android Studio and create a new project with an empty activity called MainActivity .

Lay Out the Screen

For now, our layout will just have an EditText field and a Dial button:

Modify the MainActivity Class

In the code block below, we are creating an ACTION_DIAL intent to display the phone dialer. The phone number is parsed from our tel URI scheme: tel:XXXXXXXX . Note that you don’t need any permission for this to work:

If you run the app and click the dial button, you’ll be taken to the dialer app, and from there you have to actually dial the number. You can change this flow to actually make the call from within your app by simply changing the ACTION_DIAL intent to ACTION_CALL instead. This will require the android.permission.CALL_PHONE permission, though.

2. Monitoring Phone Call Events

In this section, we are going to learn how to monitor phone call events in the Android system. The phone can be in three states:

  1. idle (when it is unused)
  2. ringing (when there is an incoming call)
  3. off-hook (when the call is answered)

Add the Permission

We need the permission READ_PHONE_STATE to be able to monitor the phone state. Add it to AndroidManifest.xml:

Create the PhoneStateListener Object

We create an object of the PhoneStateListener class, and then override its onCallStateChanged() method (in IntelliJ it is easy to do this with Control-O, and then select or search for the method to override). We’ll handle changes to the call state changes by displaying a Toast . Note that we can also access the incoming phone numbers when this method is triggered:

Depending on your application needs, you could also override one of these other event methods: onCellInfoChanged() , onCallForwardingIndicatorChanged() , onCellLocationChanged() , or onSignalStrengthChanged() .

Listening to the Phone Call State

In order to begin listening to the phone call state, we need to get the TelephonyManager from the system service and initialize it in onCreate() .

In the onResume() method, we can begin to listen using the TelephonyManager listen() method, passing it the PhoneStateListener instance and the static LISTEN_CALL_STATE . We stop listening in the onStop() method by passing the LISTEN_NONE as the second argument to listen() .

Other phone listening options possible are LISTEN_CELL_LOCATION , LISTEN_SIGNAL_STRENGTH , LISTEN_CALL_FORWARDING_INDICATOR , and LISTEN_CELL_INFO .

Finally, run the app and make sure an incoming call comes in.

This monitoring will only work when the app is in the foreground. For this to work in the background (when our application is not running), we would need to create a BroadcastReceiver so that even if the app isn’t running, we can still monitor for phone call states. Depending on your app requirements, that could be a much better way to listen for phone call state changes. I’ll show you how to do this in the next section.

Be aware that we are only monitoring incoming calls. For us to monitor outgoing calls, we need additional permissions. To monitor outgoing calls, include the following line in your AndroidManifest.xml file.

How to Use the Emulator to Make Calls and Send SMS Messages

You can use your emulator to simulate making a call or sending an SMS message, but you’ll need to do a little setup. Open your emulator, click the last button on the right-side navigation bar to open the extended control dialog, and then select the phone control button.

3. Monitoring Phone Call Events in the Background

Create a BroadcastReceiver

Just like in the previous section, we need to create an event listener to monitor phone state changes. The major difference is that this time we’ll extend the BroadcastReceiver base class so we can listen for the phone call state even if the application is not running. Be sure not to register the listener more than once! Our check for this is on line 36.

Modify AndroidManifest.xml

A broadcast receiver works only if it is registered. We need to tell the Android system about our broadcast receiver by registering it in the AndroidManifest.xml file by connecting our PhoneCallStateReceiver class to the that describes the system broadcast we wish to receive—in this case, PHONE_STATE .

Monitoring Outgoing Calls

For outgoing calls, you need to include the NEW_OUTGOING_CALL action intent in the of the receiver in AndroidManifest.xml.

To get the phone number of the intended outgoing call, inside the onReceive(Context, Intent) method, we get the number from the intent as an extra. To prevent that intended call from going through, we can call setResultData() and pass it a null argument. The resultData is used as the actual number to call.

You can learn more about broadcasts and broadcast receivers in our tutorial here on Envato Tuts+:

4. Sending SMS Messages

You have just two major choices for sending SMS: using the device SMS client application or skipping the client by sending the SMS directly from your app. We’ll look at both scenarios, and you can decide which one is better for your use case. Let’s start by sending an SMS using the device SMS client.

Set Up the Layout

First, we need to modify our main layout to have an EditText field for the message and a Send Message button.

Modify the MainActivity

Inside our onCreate() method in our MainActivity class, create an intent with ACTION_SENDTO as the first argument and a smsto:

URI as the second argument. The text message will be the value of the sms_body extra:

Here, the SMS client will monitor the status of the message delivery.

Run the App

When all required fields are entered, clicking the Send SMS button will open the user’s SMS client, or will give the user options to select an app if one hasn’t already been chosen.

5. Sending SMS Messages Directly

Next let’s see how to send the SMS directly from our application instead of using the device SMS client.

Add Permission in AndroidManifest.xml

As usual, we need to register the permission in AndroidManifest.xml.

Modify the MainActivity class

Next, for Android 6.0 (API level 23) and above, we need to request the SEND_SMS permission during runtime.

To learn more about Android runtime permissions and how they’ve changed in version 6.0, check out our tutorial here on Envato Tuts+:

To send an SMS, we get the default SmsManager instance and then call its sendTextMessage() method, passing in the phone number as the first argument and the message as the second argument:

To monitor the status of delivery, the SMSManager sendTextMessage() method has two optional PendingIntent parameters: sentIntent and deliveryIntent .

If you want to use sentIntent , watch for the result code Activity.RESULT_OK on success, or one of RESULT_ERROR_GENERIC_FAILURE , RESULT_ERROR_RADIO_OFF , and RESULT_ERROR_NULL_PDU to indicate an error.

6. Receiving an SMS Message

For your app to begin receiving SMS messages from the user’s phone, its best to have a broadcast receiver registered so that it can be alerted when a new SMS arrives even if your app is not running in the foreground.

Add the Permission

Add the RECEIVE_SMS permission to AndroidManifest.xml:

Next, we need to check and see if the app has permission to receive SMS messages at runtime. So in the MainActivity class, check for the RECEIVE_SMS permission. If it is not found, request it.

Create a Broadcast Receiver

We are retrieving each object of the SmsMessage class by using the method createFromPdu(byte[] pdu) , passing it a PDU (protocol data unit). We are then adding it to our messages array.

To support API 23 and above, you should include the format String extra (either «3gpp» for GSM/UMTS/LTE messages in 3GPP format or «3gpp2» for CDMA/LTE messages in 3GPP2 format).

Now, run the app, close it, and send your emulated phone an SMS.

Conclusion

In this tutorial, you learned about:

  • making a call from your app
  • monitoring phone call events
  • sending SMS messages using either the device messaging app or directly from your own app
  • receiving SMS messages in the background

There’s lots more you can do with phone calls and SMS messages in Android. Visit the Android Telephony API and the SMSManager API documentation to learn more.

In the meantime, check out some of our other posts on Android development!

Android Sensors in Depth: Proximity and Gyroscope

6 Do’s and Don’ts for a Great Android User Experience

Background Audio in Android With MediaSessionCompat

Migrate an Android App to Material Design

Источник

Читайте также:  Квик саппорт для андроид
Оцените статью