Регистрация профиля SIP с использованием стека Android SIP - PullRequest
0 голосов
/ 06 апреля 2020

Я разрабатывал приложение, которое позволяет пользователю звонить и принимать звонки, используя SIP, вдохновленный SIPDemo, в котором до тех пор, пока я не удалил приложение с моего телефона, оно работало нормально, оно выполняло регистрацию, показывало сообщение " Готово ", а затем приступил к обработке вызова. Теперь он не входит в Sipregistrationlistener и отображает ошибку «Ошибка при попытке закрыть менеджер 1 SipException: Не удалось создать SipSession; сеть недоступна?».

Из того, что я понимаю, я подозреваю, что проблема связана с тем, что предыдущий SIP-аккаунт все еще связан и поэтому автоматически открывается в приложении, не давая никакой регистрации, как указано в решении этого поста " Android Собственный стек SIP не регистрирует клиента", но я понятия не имею, как с этим справиться, представляя функцию closelocalprofile в onDestroy, onPause не действует. Кроме того, до недавнего времени он отображал сообщения «SipManager готов к вызовам» и был открыт, но теперь он не изменяет ничего в коде, поэтому проблема может быть не в этом.

В терминах печати отображаются следующие сообщения: - не отображаются сообщения, связанные со статусом; - журнал показывает «Создание менеджера» и «Создание нового профиля»;

Более того, у меня уже есть разрешения и кодированный манифест для поддержки SIP-коммуникаций.

Теперь я знаю, что этот стек не самый лучший, но я бы не хотел отказываться от этого проекта, поэтому любая помощь или советы будут высоко оценены. В последнем случае, в процессе подготовки, если не найдено никакого решения / прогресса, если бы кто-либо из вас мог также дать рекомендации альтернативному стеку, который был бы аналогичным, который также был бы оценен.

Вот код:

public SipManager sipManager = null;//SIPMANAGER
public SipProfile sipProfile = null;//SIPPROFILE
public SipAudioCall call = null;//SIPAUDIOCALL
public IncomingCallReceiver callReceiver;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    Permissions();
    Supported();

    initManager();

    MakeCallButton.setOnClickListener(new View.OnClickListener() /onclick event
    {
        @Override
        public void onClick(View view)
        {
           initCall();
        }
    });
    EndCallButton.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view) {
            try
            {
                call.endCall();
            }
            catch (SipException e)
            {
                status("Error when trying to end call. " + e);
            }
        }
    });
}

public void initManager()//SIPMANAGER
{
    if(sipManager == null)
    {
        sipManager = SipManager.newInstance(this); //Creates a manager instance. Returns null if SIP API is not supported
        Log.d("Manager", "Creating Manager");
    }

    initLocalProfile();
}
public void initLocalProfile()
{
    if (sipManager == null)
    {
        Log.d("Manager", "There is no manager");
        return;
    }
    if (sipProfile != null)
    {
        Log.d("Profile", "There is already a profile 1");
        closeLocalProfile();
    }

   //localprofiledata
   String user = "x";
   String domain = "xxx";
   String pass = "zzzz";

   try
   {
       Log.d("Profile", "Building a new profile");
       SipProfile.Builder builder = new SipProfile.Builder(user, domain); //user of the SIP account & the SIP server domain
       builder.setPassword(pass);//Sets the password of the SIP account
       builder.setOutboundProxy(domain);//Sets the outbound proxy of the SIP server
       builder.setPort(5060);//port number
       builder.setProtocol("UDP");
       builder.setAutoRegistration(false);

       sipProfile = builder.build();//Builds and returns the SIP profile object.

       Intent sipIntent = new Intent();//intent for the calls
       sipIntent.setAction("android.Login.INCOMING_CALL");
       PendingIntent pi = PendingIntent.getBroadcast(this, 0, sipIntent, Intent.FILL_IN_DATA);
       sipManager.open(sipProfile, pi, null);//Opens the profile for making calls and/or receiving generic SIP calls

       //Sets the listener to listen to registration events. No effect if the profile has not been opened to receive call

       sipManager.setRegistrationListener(sipProfile.getUriString(), new SipRegistrationListener()
        {
           public void onRegistering(String localProfileUri)
           {
               //Called when a registration request is sent
               status("Registering");
           }
           public void onRegistrationDone(String localProfileUri, long expiryTime)
           {
               //Called when the registration succeeded
                status("Ready");
           }
           public void onRegistrationFailed(String localProfileUri, int errorCode, String errorMessage)
           {
               //Called when the registration failed
                status("Registration Failed " + localProfileUri + errorCode + errorMessage );
           }
       });
       if (sipManager.isRegistered(sipProfile.getUriString()))
       {
           Log.d("Profile","SipManager is ready for calls");
       }
       if (sipManager.isOpened(sipProfile.getUriString()))
       {
           Log.d("Profile","SipManager is open");
       }
   }
   catch (ParseException pe)
   {
        status("Connection Error");
   }
   catch (SipException sipe)//if calling the SIP service results in an error
   {
       status("Error with SIP " + sipe);
   }
   catch (SecurityException se)
   {
       status("Error with security" + se);
   }
   catch (RuntimeException re)
   {
       status("Error with runtime" + re);
   }
   catch (Exception e)
   {
       status("Error" + e);
   }
}
public void closeLocalProfile()
{
    if (sipManager == null)
    {
        Log.d("Manager", "There is no manager 1");
        return;
    }
    try
    {
        if (sipProfile != null)
        {
            Log.d("Profile", "There is already a profile 2");
            sipManager.close(sipProfile.getUriString()); //Closes the specified profile to not make/receive calls
        }
    }
    catch (SipException se)//if calling the SIP service results in an error
    {
        status("Error while closing SIP" + se);
    }
}

public void initCall()
{
    callstatus("Adress: " + sipAddress);

    try
    {
        SipAudioCall.Listener listener = new SipAudioCall.Listener() //Listener for events relating to a SIP call, such as when a call is being recieved ("on ringing") or a call is outgoing ("on calling")
        {
            @Override
            public void onCalling(SipAudioCall call)
            {
                Log.d("initCall", "Initiating session! " + sipAddress);
            }
            @Override
            public void onCallEstablished(SipAudioCall call)
            {
                Log.d("initCall", "Call started! " + sipAddress);
                call.startAudio();//Starts the audio for the established call. This method should be called after onCallEstablished(SipAudioCall) is called
                Enter();
            }
            @Override
            public void onRinging(SipAudioCall call, SipProfile caller)
            {
                Log.d("initCall", "Ringing " + sipAddress);
            }
            @Override
            public void onRingingBack(SipAudioCall call) //Called when a RINGING response is received for the INVITE request sent
            {
                Log.d("initCall", "Ringing back " + sipAddress);
            }
            @Override
            public void onCallBusy(SipAudioCall call)
            {
                Log.d("initCall", "Call busy " + sipAddress);
            }
            @Override
            public void onCallEnded(SipAudioCall call)
            {
                    Log.d("initCall", "Call Over ");
                    call.close();
            }
            @Override
            public void onError(SipAudioCall call, int errorCode, String errorMessage)
            {
                //super.onError(call, errorCode, errorMessage);
                Log.d("initCall", "Error! " + errorMessage + errorCode);
            }
        };
        //the call object that carries out the audio call
        call = sipManager.makeAudioCall(sipProfile.getUriString(), sipAddress, listener, 30);
    }
    catch (Exception e)
    {
        status("Error when trying to close manager 1. " + e);
        if (sipProfile != null)
        {
            try
            {
                sipManager.close(sipProfile.getUriString());
            }
            catch (Exception ee)
            {
                status("Error when trying to close manager 2. " + ee);
            }
        }
        if (call != null)
        {
            call.close();
        }
    }
}

public void status(final String status)//status about the program
{
    StatusTextView = (TextView) findViewById(R.id.StatusTextView);
    StatusTextView.setText(status);
}

public void callstatus(final String callstatus)//status about the call
{
    CallTextView = (TextView) findViewById(R.id.CallTextView);
    CallTextView.setText(callstatus);
}

Спасибо за ваше время и внимание.

1 Ответ

0 голосов
/ 08 апреля 2020

Обновление

Удалось обойти эти предыдущие ошибки путем комбинации перезагрузки устройства после переустановки приложения и повторной отправки кода из Android Studio на телефон. Мои подозрения относительно источника ошибки, как я уже говорил выше, связаны с ошибками, которые есть в этом стеке, тем не менее, теперь он работает, и я доволен готовым продуктом.

Несмотря на то, что я не получил никакого ответа здесь Надеюсь, что эта тема кому-нибудь пригодится.

Спасибо за ваше время и внимание.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...