Java 使用wifi通过SIP呼叫

Java 使用wifi通过SIP呼叫,java,android,android-intent,sip,android-wifi,Java,Android,Android Intent,Sip,Android Wifi,实际上,我正在通过wifi使用sip进行通话。bt在这个程序中,问题是当我选择要呼叫的人的sip帐户时,但当我选择号码并按ok时,然后在第二部电话上,没有通知显示他们的来电即将到来。请帮帮我,我被困在这里了 public class WalkieTalkieActivity extends Activity implements View.OnTouchListener { public String sipAddress = null; String DummyNum;

实际上,我正在通过wifi使用sip进行通话。bt在这个程序中,问题是当我选择要呼叫的人的sip帐户时,但当我选择号码并按ok时,然后在第二部电话上,没有通知显示他们的来电即将到来。请帮帮我,我被困在这里了

public class WalkieTalkieActivity extends Activity implements View.OnTouchListener {

    public String sipAddress = null;
    String DummyNum;
    SipManager manager=null;
    public SipProfile me = null;
    public SipAudioCall call = null;
    public IncomingCallReceiver callReceiver;
    Button contact;
    TextView tv;
    private static final int CALL_ADDRESS = 1;
    private static final int SET_AUTH_INFO = 2;
    private static final int UPDATE_SETTINGS_DIALOG = 3;
    private static final int HANG_UP = 4;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.walkietalkie);
        // PickContact();
        contact = (Button) findViewById(R.id.button1);
        contact.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                // BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
                intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
                startActivityForResult(intent, 1);
            }
        });
        tv = (TextView) findViewById(R.id.textView1);
        ToggleButton pushToTalkButton = (ToggleButton) findViewById(R.id.pushToTalk);
        pushToTalkButton.setOnTouchListener(this);

        // Set up the intent filter.  This will be used to fire an
        // IncomingCallReceiver when someone calls the SIP address used by this
        // application.
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.SipDemo.INCOMING_CALL");
        callReceiver = new IncomingCallReceiver();
        this.registerReceiver(callReceiver, filter);

        // "Push to talk" can be a serious pain when the screen keeps turning off.
        // Let's prevent that.
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        initializeManager();
    }

    @Override
    public void onStart() {
        super.onStart();
        // When we get back from the preference setting Activity, assume
        // settings have changed, and re-login with new auth info.
        initializeManager();
    }

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (call != null) {
            call.close();
        }

        closeLocalProfile();

        if (callReceiver != null) {
            this.unregisterReceiver(callReceiver);
        }
    }

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public void initializeManager() {
        if (manager == null) {
            manager = SipManager.newInstance(this);
        }

        initializeLocalProfile();
    }

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public void initializeLocalProfile() {
        if (manager == null) {
            return;
        }

        if (me != null) {
            closeLocalProfile();
        }

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        String username = prefs.getString("namePref", "");
        String domain = prefs.getString("domainPref", "");
        String password = prefs.getString("passPref", "");

        if (username.length() == 0 || domain.length() == 0 || password.length() == 0) {
            showDialog(UPDATE_SETTINGS_DIALOG);
            return;
        }

        try {
            SipProfile.Builder builder = new SipProfile.Builder(username, domain);
            builder.setPassword(password);
            me = builder.build();

            Intent i = new Intent();
            i.setAction("android.SipDemo.INCOMING_CALL");
            PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, Intent.FILL_IN_DATA);
            manager.open(me, pi, null);

            // This listener must be added AFTER manager.open is called,
            // Otherwise the methods aren't guaranteed to fire.

            manager.setRegistrationListener(me.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.");
                }
            });
        } catch (ParseException pe) {
            updateStatus("Connection Error.");
        } catch (SipException se) {
            updateStatus("Connection error.");
        }
    }

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public void closeLocalProfile() {
        if (manager == null) {
            return;
        }
        try {
            if (me != null) {
                manager.close(me.getUriString());
            }
        } catch (Exception ee) {
            Log.d("WalkieTalkieActivity/onDestroy", "Failed to close local profile.", ee);
        }
    }

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public void initiateCall() {

        updateStatus(sipAddress);

        try {
            SipAudioCall.Listener listener = new SipAudioCall.Listener() {
                // Much of the client's interaction with the SIP Stack will
                // happen via listeners.  Even making an outgoing call, don't
                // forget to set up a listener to set things up once the call is established.
                @TargetApi(Build.VERSION_CODES.GINGERBREAD)
                @Override
                public void onCallEstablished(SipAudioCall call) {
                    call.startAudio();
                    call.setSpeakerMode(true);
                    call.toggleMute();
                    updateStatus(call);
                }

                @TargetApi(Build.VERSION_CODES.GINGERBREAD)
                @Override
                public void onCallEnded(SipAudioCall call) {
                    updateStatus("Ready.");
                }
            };

            call = manager.makeAudioCall(me.getUriString(), sipAddress, listener, 30);

        } catch (Exception e) {
            Log.i("WalkieTalkieActivity/InitiateCall", "Error when trying to close manager.", e);
            if (me != null) {
                try {
                    manager.close(me.getUriString());
                } catch (Exception ee) {
                    Log.i("WalkieTalkieActivity/InitiateCall",
                            "Error when trying to close manager.", ee);
                    ee.printStackTrace();
                }
            }
            if (call != null) {
                call.close();
            }
        }
    }

    public void updateStatus(final String status) {
        // Be a good citizen.  Make sure UI changes fire on the UI thread.
        this.runOnUiThread(new Runnable() {
            public void run() {
                TextView labelView = (TextView) findViewById(R.id.sipLabel);
                labelView.setText(status);
            }
        });
    }

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public void updateStatus(SipAudioCall call) {
        String useName = call.getPeerProfile().getDisplayName();
        if (useName == null) {
            useName = call.getPeerProfile().getUserName();
        }
        updateStatus(useName + "@" + call.getPeerProfile().getSipDomain());
    }

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public boolean onTouch(View v, MotionEvent event) {
        if (call == null) {
            return false;
        } else if (event.getAction() == MotionEvent.ACTION_DOWN && call != null && call.isMuted()) {
            call.toggleMute();
        } else if (event.getAction() == MotionEvent.ACTION_UP && !call.isMuted()) {
            call.toggleMute();
        }
        return false;
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, CALL_ADDRESS, 0, "Call someone");
        menu.add(0, SET_AUTH_INFO, 0, "Edit your SIP Info.");
        menu.add(0, HANG_UP, 0, "End Current Call.");

        return true;
    }

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case CALL_ADDRESS:
                showDialog(CALL_ADDRESS);
                break;
            case SET_AUTH_INFO:
                updatePreferences();
                break;
            case HANG_UP:
                if (call != null) {
                    try {
                        call.endCall();
                    } catch (SipException se) {
                        Log.d("WalkieTalkieActivity/onOptionsItemSelected",
                                "Error ending call.", se);
                    }
                    call.close();
                }
                break;
        }
        return true;
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case CALL_ADDRESS:

                LayoutInflater factory = LayoutInflater.from(this);
                final View textBoxView = factory.inflate(R.layout.call_address_dialog, null);
                return new AlertDialog.Builder(this)
                        .setTitle("Call Someone.")
                        .setView(textBoxView)
                        .setPositiveButton(
                                android.R.string.ok, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int whichButton) {
                                        EditText textField = (EditText)
                                                (textBoxView.findViewById(R.id.calladdress_edit));
                                        DummyNum = textField.getText().toString();
                                        tv.setText(DummyNum);
                                        SendMessageWebTask webTask1 = new SendMessageWebTask(WalkieTalkieActivity.this);
                                        webTask1.execute();
                                        initiateCall();

                                    }
                                }
                        )
                        .setNegativeButton(
                                android.R.string.cancel, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int whichButton) {
                                        // Noop.
                                    }
                                }
                        )
                        .create();

            case UPDATE_SETTINGS_DIALOG:
                return new AlertDialog.Builder(this)
                        .setMessage("Please update your SIP Account Settings.")
                        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                updatePreferences();
                            }
                        })
                        .setNegativeButton(
                                android.R.string.cancel, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int whichButton) {
                                        // Noop.
                                    }
                                }
                        )
                        .create();
        }
        return null;
    }

    public void updatePreferences() {
        Intent settingsActivity = new Intent(getBaseContext(),
                SipSettings.class);
        startActivity(settingsActivity);
    }

    public void PickContact() {


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null) {
            Uri uri = data.getData();

            if (uri != null) {
                Cursor c = null;
                try {
                    c = getContentResolver().query(uri, new String[]{
                                    ContactsContract.CommonDataKinds.Phone.NUMBER,
                                    ContactsContract.CommonDataKinds.Phone.TYPE},
                            null, null, null
                    );

                    if (c != null && c.moveToFirst()) {
                        String number = c.getString(0);
                        int type = c.getInt(1);
                        // showSelectedNumber(type, number);
                        tv.setText(number);
                    }
                } finally {
                    if (c != null) {
                        c.close();
                    }
                }
            }
        }
    }

    public void showSelectedNumber(int type, String number) {
    }

    public class SendMessageWebTask extends AsyncTask<String, Void, String> {

        private static final String TAG = "WebTask";
        private ProgressDialog progressDialog;
        private Context context;
        private String status;

        public SendMessageWebTask(Context context) {
            super();
            this.context = context;

            this.progressDialog = new ProgressDialog(context);
            this.progressDialog.setCancelable(true);
            this.progressDialog.setMessage("Checking User using Connecto...");
        }

        @Override
        protected String doInBackground(String... params) {
            status = invokeWebService();
            return status;
        }

        @Override
        protected void onPreExecute() {
            Log.i(TAG, "Showing dialog...");
            progressDialog.show();
        }

        @Override
        protected void onPostExecute(String params) {
            super.onPostExecute(params);
            progressDialog.dismiss();

            //params = USER_NOT_EXIST_CODE;
            if (params.equals("008")) {
                Toast toast = Toast.makeText(WalkieTalkieActivity.this, "Requested user is not using Connecto", 7000);
                toast.show();
                MediaPlayer mp1 = MediaPlayer.create(WalkieTalkieActivity.this, R.raw.button_test);
                mp1.start();
                sipAddress = DummyNum;
                performDial(DummyNum);

            } else if (params.equals("001")) {

                Toast toast = Toast.makeText(WalkieTalkieActivity.this, "Requested user is not using Connecto... Now Call is through GSM Network", 7000);
                toast.show();
                //      sipAddress = DummyNum;
                performDial(DummyNum);
                //      initiateCall();
            } else if (params.equals("100")) {

                Toast toast = Toast.makeText(WalkieTalkieActivity.this, "Server Error... Now Call is through GSM Network", 7000);
                toast.show();
                //  sipAddress = DummyNum;
                performDial(DummyNum);
                //          initiateCall();
            } else {
                Toast toast = Toast.makeText(WalkieTalkieActivity.this, "Your Call is Staring...", 7000);
                toast.show();
                sipAddress = DummyNum;
                //          performDial(DummyNum);
                initiateCall();
            }
            //  tv.setText(params);
        }

        private String invokeWebService() {
            final String NAMESPACE = "http://tempuri.org/";
            final String METHOD_NAME = Utility.verify_sip;
            final String URL = Utility.webServiceUrl;
            final String SOAP_ACTION = "http://tempuri.org/" + Utility.verify_sip;
            try {
                SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
                request.addProperty("phone", DummyNum);

                Log.v("XXX", tv.getText().toString());
                //request.addProperty("password", inputParam2);

                SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                envelope.dotNet = true;
                envelope.setOutputSoapObject(request);

                HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
                androidHttpTransport.call(SOAP_ACTION, envelope);

                SoapPrimitive result = (SoapPrimitive) envelope.getResponse();
                String status = result.toString();
                Log.v("RESULT: ", status);
                return status;
            } catch (Exception e) {
                Log.e("exception", e.toString());
                StackTraceElement elements[] = e.getStackTrace();
                for (int i = 0, n = elements.length; i < n; i++) {
                    Log.i("File", elements[i].getFileName());
                    Log.i("Line", String.valueOf(elements[i].getLineNumber()));
                    Log.i("Method", elements[i].getMethodName());
                    Log.i("------", "------");
                }
                return "EXCEPTION";
            }
        }
    }

    private void performDial(String numberString) {
        if (!numberString.equals("")) {
            Uri number = Uri.parse("tel:" + numberString);
            Intent dial = new Intent(Intent.ACTION_CALL, number);
            startActivity(dial);
        }
    }
}
公共类WalkieTalkieActivity扩展了活动实现View.OnTouchListener{
公共字符串sipAddress=null;
字符串DummyNum;
SipManager=null;
公共SipProfile me=null;
公共SipAudioCall call=null;
公众收入收受人;
按钮触点;
文本视图电视;
专用静态最终整型调用_地址=1;
私有静态最终整数集\u AUTH\u INFO=2;
私有静态最终整数更新设置对话框=3;
专用静态最终int挂起=4;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.walkietalkie);
//PickContact();
联系人=(按钮)findViewById(R.id.button1);
contact.setOnClickListener(新的OnClickListener(){
@凌驾
公共void onClick(视图v){
//TODO自动生成的方法存根
意向意向=新意向(意向.行动\u获取\u内容);
//BoD条款:内容类型而非内容项目类型
intent.setType(ContactsContract.CommonDataTypes.Phone.CONTENT\u ITEM\u TYPE);
startActivityForResult(意向,1);
}
});
tv=(TextView)findViewById(R.id.textView1);
ToggleButton pushToTalkButton=(ToggleButton)findViewById(R.id.pushToTalk);
pushToTalkButton.setOnTouchListener(此);
//设置意图筛选器。这将用于激发
//当有人呼叫此服务器使用的SIP地址时,输入CallReceiver
//应用程序。
IntentFilter=newintentfilter();
filter.addAction(“android.SipDemo.INCOMING_CALL”);
callReceiver=新入职callReceiver();
此注册表接收程序(callReceiver,filter);
//当屏幕不断关闭时,“一键通”可能是一种严重的疼痛。
//让我们防止这种情况。
getWindow().addFlags(WindowManager.LayoutParams.FLAG\u保持屏幕打开);
初始化管理器();
}
@凌驾
public void onStart(){
super.onStart();
//当我们从偏好设置活动返回时,假设
//设置已更改,请使用新的身份验证信息重新登录。
初始化管理器();
}
@TargetApi(构建版本代码姜饼)
@凌驾
公共空间{
super.ondestory();
如果(调用!=null){
call.close();
}
closeLocalProfile();
if(callReceiver!=null){
这是未注册的接收者(callReceiver);
}
}
@TargetApi(构建版本代码姜饼)
公共无效初始值设定项管理器(){
if(manager==null){
manager=SipManager.newInstance(此);
}
初始化ELOCALPROFILE();
}
@TargetApi(构建版本代码姜饼)
public void initializeLocalProfile(){
if(manager==null){
回来
}
如果(me!=null){
closeLocalProfile();
}
SharedReferences prefs=PreferenceManager.GetDefaultSharedReferences(getBaseContext());
字符串username=prefs.getString(“namePref”和“”);
String domain=prefs.getString(“domainPref”和“”);
字符串密码=prefs.getString(“passPref”,“passPref”);
if(username.length()==0 | | domain.length()==0 | | | password.length()==0){
showDialog(更新设置对话框);
回来
}
试一试{
SipProfile.Builder=新的SipProfile.Builder(用户名,域);
builder.setPassword(密码);
me=builder.build();
意图i=新意图();
i、 setAction(“android.SipDemo.INCOMING_CALL”);
pendingent pi=pendingent.getBroadcast(this,0,i,Intent.FILL_IN_数据);
manager.open(me、pi、null);
//必须在调用manager.open后添加此侦听器,
//否则,这些方法就不能保证触发。
manager.setRegistrationListener(me.getUriString(),新SipRegistrationListener()){
注册时的公共void(字符串localProfileUri){
updateStatus(“向SIP服务器注册…”);
}
public void onRegistrationDone(字符串localProfileUri,长过期时间){
更新状态(“就绪”);
}
public void onRegistrationFailed(字符串localProfileUri,int errorCode,
字符串错误消息){
updateStatus(“注册失败,请检查设置”);
}
});
}捕获(解析异常pe){
updateStatus(“连接错误”);
}捕获(SIPSE){
updateStatus(“连接错误”);
}
}
@TargetApi(构建版本代码姜饼)
public void closeLocalProfile(){
if(manager==null){
回来
}
试一试{
如果(me!=null){
manager.close(me.getUriString());
}
}捕获(异常ee){
Log.d(“Walkietalkie活动/onDestroy”,“未能关闭本地配置文件”,ee);
}
}
@TargetApi(构建版本代码姜饼)
public void initiateCall(){
更新状态(sipAddress);
试一试{
SipAudioCall.Listener侦听器=新的SipAudioCall.Listener(){
//客户端与SIP堆栈的大部分交互将
//通过听众发生。即使打外线电话,也不要