Android SIP(Session Initiation Protocol)

来源:互联网 发布:gif快手刷粉安卓软件 编辑:程序博客网 时间:2024/05/16 16:20

Session Initiation Protocol

In this document

  1. Requirements and Limitations
  2. Classes and Interfaces
  3. Creating the Manifest
  4. Creating a SIP Manager
  5. Registering with a SIP Server
  6. Making an Audio Call
  7. Receiving Calls
  8. Testing SIP Applications

Key classes

  1. SipManager
  2. SipProfile
  3. SipAudioCall

Related samples

  1. SipDemo

Android provides an API that supports the Session Initiation Protocol (SIP).This lets you add SIP-based internet telephony features to your applications.Android includes a full SIP protocol stack and integrated call managementservices that let applications easily set up outgoing and incoming voice calls,without having to manage sessions, transport-level communication, or audiorecord or playback directly.

Here are examples of the types of applications that might use the SIP API:

  • Video conferencing.
  • Instant messaging.

Requirements and Limitations

Here are the requirements for developing a SIP application:

  • You must have a mobile device that is running Android 2.3 or higher.
  • SIP runs over a wireless data connection, so your device must have a dataconnection (with a mobile data service or Wi-Fi). This means that youcan't test on AVD—you can only test on a physical device. For details, seeTesting SIP Applications.
  • Each participant in the application's communication session must have aSIP account. There are many different SIP providers that offer SIP accounts.

SIP API Classes and Interfaces

Here is a summary of the classes and one interface(SipRegistrationListener) that are included in the Android SIPAPI:

Class/InterfaceDescriptionSipAudioCallHandles an Internet audio call over SIP.SipAudioCall.ListenerListener for events relating to a SIP call, such as when a call is beingreceived ("on ringing") or a call is outgoing ("on calling").SipErrorCodeDefines error codes returned during SIP actions.SipManagerProvides APIs for SIP tasks, such as initiating SIP connections, and provides accessto related SIP services.SipProfileDefines a SIP profile, including a SIP account, domain and server information.SipProfile.BuilderHelper class for creating a SipProfile.SipSessionRepresents a SIP session that is associated with a SIP dialog or a standalone transactionnot within a dialog.SipSession.ListenerListener for events relating to a SIP session, such as when a session is being registered("on registering") or a call is outgoing ("on calling").SipSession.StateDefines SIP session states, such as "registering", "outgoing call", and "in call".SipRegistrationListenerAn interface that is a listener for SIP registration events.

Creating the Manifest

If you are developing an application that uses the SIP API, remember that thefeature is supported only on Android 2.3 (API level 9) and higher versions ofthe platform. Also, among devices running Android 2.3 (API level 9) or higher,not all devices will offer SIP support.

To use SIP, add the following permissions to your application's manifest:

  • android.permission.USE_SIP
  • android.permission.INTERNET

To ensure that your application can only be installed on devices that arecapable of supporting SIP, add the following to your application'smanifest:

  • <uses-sdk android:minSdkVersion="9" />. This indicates that your application requires Android 2.3 or higher. For moreinformation, seeAPILevels and the documentation for the<uses-sdk> element.

To control how your application is filtered from devices that do not supportSIP (for example, in Android Market), add the following to your application'smanifest:

  • <uses-feature android:name="android.hardware.sip.voip"/>. This states that your application uses the SIP API. Thedeclaration should include anandroid:required attribute thatindicates whether you want the application to be filtered from devices that donot offer SIP support. Other<uses-feature> declarationsmay also be needed, depending on your implementation. For more information,see the documentation for the<uses-feature> element.

If your application is designed to receive calls, you must also define a receiver (BroadcastReceiver subclass) in the application's manifest:

  • <receiver android:name=".IncomingCallReceiver" android:label="Call Receiver"/>

Here are excerpts from the SipDemo manifest:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"          package="com.example.android.sip">  ...     <receiver android:name=".IncomingCallReceiver" android:label="Call Receiver"/>  ...  <uses-sdk android:minSdkVersion="9" />  <uses-permission android:name="android.permission.USE_SIP" />  <uses-permission android:name="android.permission.INTERNET" />  ...  <uses-feature android:name="android.hardware.sip.voip" android:required="true" />  <uses-feature android:name="android.hardware.wifi" android:required="true" />  <uses-feature android:name="android.hardware.microphone" android:required="true" /></manifest>

Creating a SipManager

To use the SIP API, your application must create a SipManager object. TheSipManager takescare of the following in your application:

  • Initiating SIP sessions.
  • Initiating and receiving calls.
  • Registering and unregistering with a SIP provider.
  • Verifying session connectivity.

You instantiate a new SipManager as follows:

public SipManager mSipManager = null;...if(mSipManager == null) {    mSipManager = SipManager.newInstance(this);}

Registering with a SIP Server

A typical Android SIP application involves one or more users, each of whomhas a SIP account. In an Android SIP application, each SIP account isrepresented by aSipProfile object.

A SipProfile defines a SIP profile, including a SIPaccount, and domain and server information. The profile associated with the SIPaccount on the device running the application is called the localprofile. The profile that the session is connected to is called thepeer profile. When your SIP application logs into the SIP server withthe localSipProfile, this effectively registers thedevice as the location to send SIP calls to for your SIP address.

This section shows how to create a SipProfile,register it with a SIP server, and track registration events.

You create a SipProfile object as follows:

public SipProfile mSipProfile = null;...SipProfile.Builder builder = new SipProfile.Builder(username, domain);builder.setPassword(password);mSipProfile = builder.build();

The following code excerpt opens the local profile for making calls and/orreceiving generic SIP calls. The caller can make subsequent calls throughmSipManager.makeAudioCall. This excerpt also sets the actionandroid.SipDemo.INCOMING_CALL, which will be used by an intentfilter when the device receives a call (see Setting upan intent filter to receive calls). This is the registration step:

Intent intent = new Intent();intent.setAction("android.SipDemo.INCOMING_CALL");PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, Intent.FILL_IN_DATA);mSipManager.open(mSipProfile, pendingIntent, null);

Finally, this code sets a SipRegistrationListener on the SipManager. This tracks whether theSipProfile was successfully registered with your SIP serviceprovider:

mSipManager.setRegistrationListener(mSipProfile.getUriString(), new SipRegistrationListener() {public void onRegistering(String localProfileUri) {    updateStatus("Registering with SIP Server...");}public void onRegistrationDone(String localProfileUri, long expiryTime) {    updateStatus("Ready");}   public void onRegistrationFailed(String localProfileUri, int errorCode,    String errorMessage) {    updateStatus("Registration failed.  Please check settings.");}

When your application is done using a profile, it should close it to freeassociated objects into memory and unregister the device from the server. Forexample:

public void closeLocalProfile() {    if (mSipManager == null) {       return;    }    try {       if (mSipProfile != null) {          mSipManager.close(mSipProfile.getUriString());       }     } catch (Exception ee) {       Log.d("WalkieTalkieActivity/onDestroy", "Failed to close local profile.", ee);     }}

Making an Audio Call

To make an audio call, you must have the following in place:

  • A SipProfile that is making the call (the"local profile"), and a valid SIP address to receive the call (the"peer profile").
  • A SipManager object.

To make an audio call, you should set up a SipAudioCall.Listener. Much of the client's interaction withthe SIP stack happens through listeners. In this snippet, you see how the SipAudioCall.Listener sets things up after the call isestablished:

SipAudioCall.Listener listener = new SipAudioCall.Listener() {     @Override   public void onCallEstablished(SipAudioCall call) {      call.startAudio();      call.setSpeakerMode(true);      call.toggleMute();         ...   }      @Override   public void onCallEnded(SipAudioCall call) {      // Do something.   }};

Once you've set up the SipAudioCall.Listener, you canmake the call. TheSipManager methodmakeAudioCall takes the following parameters:

  • A local SIP profile (the caller).
  • A peer SIP profile (the user being called).
  • A SipAudioCall.Listener to listen to the callevents fromSipAudioCall. This can benull,but as shown above, the listener is used to set things up once the call isestablished.
  • The timeout value, in seconds.

For example:

 call = mSipManager.makeAudioCall(mSipProfile.getUriString(), sipAddress, listener, 30);

Receiving Calls

To receive calls, a SIP application must include a subclass of BroadcastReceiver that has the ability to respond to an intentindicating that there is an incoming call. Thus, you must do the following inyour application:

  • In AndroidManifest.xml, declare a<receiver>. In SipDemo, this is<receiver android:name=".IncomingCallReceiver"android:label="Call Receiver"/>.
  • Implement the receiver, which is a subclass of BroadcastReceiver. InSipDemo, this isIncomingCallReceiver.
  • Initialize the local profile (SipProfile) with apending intent that fires your receiver when someone calls the local profile.
  • Set up an intent filter that filters by the action that represents anincoming call. InSipDemo, this action isandroid.SipDemo.INCOMING_CALL.

Subclassing BroadcastReceiver

To receive calls, your SIP application must subclass BroadcastReceiver.TheAndroid system handles incoming SIP calls and broadcasts an "incomingcall" intent (as defined by the application) when it receivesa call. Here is the subclassedBroadcastReceivercode fromSipDemo. To see the full example, go to SipDemo sample, whichis included in the SDK samples. For information on downloading and installingthe SDK samples, seeGetting the Samples.

/*** Listens for incoming SIP calls, intercepts and hands them off to WalkieTalkieActivity. */public class IncomingCallReceiver extends BroadcastReceiver {    /**     * Processes the incoming call, answers it, and hands it over to the     * WalkieTalkieActivity.     * @param context The context under which the receiver is running.     * @param intent The intent being received.     */    @Override    public void onReceive(Context context, Intent intent) {        SipAudioCall incomingCall = null;        try {            SipAudioCall.Listener listener = new SipAudioCall.Listener() {                @Override                public void onRinging(SipAudioCall call, SipProfile caller) {                    try {                        call.answerCall(30);                    } catch (Exception e) {                        e.printStackTrace();                    }                }            };            WalkieTalkieActivity wtActivity = (WalkieTalkieActivity) context;            incomingCall = wtActivity.mSipManager.takeAudioCall(intent, listener);            incomingCall.answerCall(30);            incomingCall.startAudio();            incomingCall.setSpeakerMode(true);            if(incomingCall.isMuted()) {                incomingCall.toggleMute();            }            wtActivity.call = incomingCall;            wtActivity.updateStatus(incomingCall);        } catch (Exception e) {            if (incomingCall != null) {                incomingCall.close();            }        }    }}

Setting up an intent filter to receive calls

When the SIP service receives a new call, it sends out an intent with theaction string provided by the application. In SipDemo, this action string isandroid.SipDemo.INCOMING_CALL.

This code excerpt from SipDemo shows how the SipProfile object gets created with a pending intent based onthe action stringandroid.SipDemo.INCOMING_CALL. ThePendingIntent object will perform a broadcast when theSipProfile receives a call:

public SipManager mSipManager = null;public SipProfile mSipProfile = null;...Intent intent = new Intent(); intent.setAction("android.SipDemo.INCOMING_CALL"); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, Intent.FILL_IN_DATA); mSipManager.open(mSipProfile, pendingIntent, null);

The broadcast will be intercepted by the intent filter, which will then firethe receiver (IncomingCallReceiver). You can specify an intentfilter in your application's manifest file, or do it in code as in theSipDemosample application's onCreate() methodof the application'sActivity:

public class WalkieTalkieActivity extends Activity implements View.OnTouchListener {...    public IncomingCallReceiver callReceiver;    ...    @Override    public void onCreate(Bundle savedInstanceState) {       IntentFilter filter = new IntentFilter();       filter.addAction("android.SipDemo.INCOMING_CALL");       callReceiver = new IncomingCallReceiver();       this.registerReceiver(callReceiver, filter);       ...    }    ...}

Testing SIP Applications

To test SIP applications, you need the following:

  • A mobile device that is running Android 2.3 or higher. SIP runs overwireless, so you must test on an actual device. Testing on AVD won't work.
  • A SIP account. There are many different SIP providers that offer SIP accounts.
  • If you are placing a call, it must also be to a valid SIP account.

To test a SIP application:

  1. On your device, connect to wireless (Settings > Wireless & networks> Wi-Fi > Wi-Fi settings)
  2. Set up your mobile device for testing, as described in Developing on a Device.
  3. Run your application on your mobile device, as described in Developing on a Device.
  4. If you are using Eclipse, you can view the application log output in Eclipseusing LogCat (Window > Show View > Other > Android >LogCat).

原创粉丝点击