I want to make a voip Call using my program - android

I'm currently developing an application for making VoIP/SIP calls, but I don't know why I cannot make a call to a number using my program. I have a valid SIP server_id, password and domain. Using that domain call can be made. Programming code is given below. Can anyone help me out?
public class CallActivity extends Activity {
public String sipAddress = "nizamcs#sip2sip.info";
public SipManager manager = null;
public SipProfile me = null;
public SipAudioCall call = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.calling);
initializeManager();
}
public void initializeManager() {
if (manager == null) {
manager = SipManager.newInstance(this);
}
initializeLocalProfile();
}
public void initializeLocalProfile() {
if (manager == null) {
return;
}
if (me != null) {
closeLocalProfile();
}
String username = "my_username";
String domain = "my_domain";
String password = "my_password";
if (username.length() == 0 || domain.length() == 0 || password.length() == 0) {
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);
manager.setRegistrationListener(me.getUriString(), new SipRegistrationListener() {
public void onRegistering(String localProfileUri) {
Log.d("onRegistering", "Registering with SIP Server...");
}
public void onRegistrationDone(String localProfileUri, long expiryTime) {
Log.d("onRegistrationDone", "RegistrationDone..Ready");
}
public void onRegistrationFailed(String localProfileUri, int errorCode,
String errorMessage) {
Log.d("onRegistrationFailed", "RegistrationFailed");
}
});
} catch (ParseException pe) {
} catch (SipException se) {
}
initiateCall();
}
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);
}
}
public void initiateCall() {
try {
SipAudioCall.Listener listener = new SipAudioCall.Listener() {
#Override
public void onCallEstablished(SipAudioCall call) {
call.startAudio();
call.setSpeakerMode(true);
call.toggleMute();
// updateStatus(call);
}
#Override
public void onCallEnded(SipAudioCall call) {
}
};
call = manager.makeAudioCall(me.getUriString(), sipAddress, listener, 300);
}
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();
}
}
}
}

Please check if your request is being send by using wireshark and see the response you get from the sip server. By doing it you can make sure if the request is actually being send or not.

Related

Detecting incoming call [duplicate]

This question already has answers here:
How to detect incoming calls, in an Android device?
(13 answers)
Closed 6 years ago.
Here, I'm creating a application to start flash when an sms is recieved and an incoming call is recieved. The flash is working on recieving sms but not on call, why? Can anyone help? I'm stuck on this since many days. Thanks in advance, my code is given below. Flash only performs on recieving sms but not on recieving calls. Expecting your guidence. When I searched regarding this I am getting only the Classes and methods to create my own app. Requesting for the explanation
public class SMSReceiver extends BroadcastReceiver {
Boolean call;
private Camera camera;
int count;
long delaytime;
Editor editor;
String flashtype;
private boolean hasFlash;
private boolean isFlashOn;
private boolean isFlashblinking;
private boolean mActive;
private Handler mHander;
private final Runnable mRunnable;
private boolean mSwap;
private Context mcontext;
AudioManager myAudioManager;
String noofblinks;
int numbofblink;
Parameters params;
SharedPreferences pref;
StringBuilder result;
Boolean ring;
Boolean silent;
Boolean sms;
String timetoblink;
Boolean vibrate;
public class PhoneListener extends PhoneStateListener {
private Context context;
public PhoneListener(Context c) {
Log.i("CallRecorder", "PhoneListener constructor");
this.context = c;
}
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case 0:
try {
SMSReceiver.this.mHander
.removeCallbacks(SMSReceiver.this.mRunnable);
if (SMSReceiver.this.camera != null) {
SMSReceiver.this.camera.release();
}
} catch (Exception e) {
try {
SMSReceiver.this.camera.release();
} catch (Exception e2) {
}
}
case 1:
try {
if (SMSReceiver.this.call.booleanValue()) {
if (SMSReceiver.this.myAudioManager.getRingerMode() == 0
&& SMSReceiver.this.silent.booleanValue()) {
SMSReceiver.this.flash();
}
if (SMSReceiver.this.myAudioManager.getRingerMode() == 1
&& SMSReceiver.this.vibrate.booleanValue()) {
SMSReceiver.this.flash();
}
if (SMSReceiver.this.myAudioManager.getRingerMode() == 2
&& SMSReceiver.this.ring.booleanValue()) {
SMSReceiver.this.flash();
}
}
} catch (Exception e3) {
}
case 2:
try {
SMSReceiver.this.mHander
.removeCallbacks(SMSReceiver.this.mRunnable);
if (SMSReceiver.this.camera != null) {
SMSReceiver.this.camera.release();
}
} catch (Exception e4) {
try {
SMSReceiver.this.camera.release();
} catch (Exception e5) {
}
}
default:
}
}
}
public SMSReceiver() {
this.mHander = new Handler();
this.mActive = false;
this.mSwap = true;
this.isFlashblinking = true;
this.count = 0;
this.mRunnable = new Runnable() {
#Override
// TODO Auto-generated method stub
public void run() {
try {
SMSReceiver sMSReceiver = SMSReceiver.this;
sMSReceiver.count++;
} catch (Exception e) {
}
if (SMSReceiver.this.mActive) {
if (SMSReceiver.this.count >= SMSReceiver.this.numbofblink * 2) {
try {
SMSReceiver.this.mHander
.removeCallbacks(SMSReceiver.this.mRunnable);
SMSReceiver.this.camera.release();
} catch (Exception e2) {
}
}
if (SMSReceiver.this.isFlashOn) {
SMSReceiver.this.turnOffFlash();
} else {
SMSReceiver.this.turnOnFlash();
}
try {
SMSReceiver.this.mHander.postDelayed(
SMSReceiver.this.mRunnable,
SMSReceiver.this.delaytime);
} catch (Exception e3) {
}
}
}
};
}
public void onReceive(Context context, Intent intent) {
try {
this.mcontext = context;
this.count = 0;
try {
this.pref = PreferenceManager
.getDefaultSharedPreferences(this.mcontext);
this.editor = this.pref.edit();
this.call = Boolean.valueOf(this.pref.getBoolean("call", true));
this.sms = Boolean.valueOf(this.pref.getBoolean("sms", true));
this.timetoblink = this.pref.getString("blinktime", "200");
this.noofblinks = this.pref.getString("noofblinks", "5");
this.ring = Boolean.valueOf(this.pref.getBoolean("ring", true));
this.vibrate = Boolean.valueOf(this.pref.getBoolean("vibrate",
true));
this.silent = Boolean.valueOf(this.pref.getBoolean("silent",
true));
this.flashtype = this.pref.getString("flashtype", "1");
this.delaytime = Long.parseLong(this.timetoblink);
this.numbofblink = Integer.parseInt(this.noofblinks);
this.myAudioManager = (AudioManager) this.mcontext
.getSystemService("audio");
} catch (Exception e) {
}
((TelephonyManager) this.mcontext.getSystemService("phone"))
.listen(new PhoneListener(context), 32);
} catch (Exception e2) {
}
}
public void flash() {
try {
this.hasFlash = this.mcontext.getPackageManager().hasSystemFeature(
"android.hardware.camera.flash");
if (this.hasFlash) {
getCamera();
startStrobe();
return;
}
AlertDialog alert = new Builder(this.mcontext).create();
alert.setTitle("Error");
alert.setMessage("Sorry, your device doesn't support flash light!");
alert.setButton("OK", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
alert.show();
} catch (Exception e) {
}
}
private void getCamera() {
if (this.camera == null) {
try {
this.camera = Camera.open();
this.params = this.camera.getParameters();
} catch (Exception e) {
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
}
}
}
private void turnOnFlash() {
try {
if (!this.isFlashOn && this.camera != null && this.params != null) {
this.params = this.camera.getParameters();
if (this.flashtype.equals("2")) {
this.params.setFlashMode("torch");
} else if (this.flashtype.equals("3")) {
this.params.setFlashMode("torch");
} else {
this.params.setFlashMode("torch");
}
this.camera.setParameters(this.params);
this.camera.startPreview();
this.isFlashOn = true;
}
} catch (Exception e) {
}
}
private void turnOffFlash() {
try {
if (this.isFlashOn && this.camera != null && this.params != null) {
this.params = this.camera.getParameters();
this.params.setFlashMode("off");
this.camera.setParameters(this.params);
this.camera.stopPreview();
this.isFlashOn = false;
}
} catch (Exception e) {
}
}
private void startStrobe() {
try {
this.mActive = true;
this.mHander.post(this.mRunnable);
} catch (Exception e) {
}
}
}
This is doable
follow this link for the same
http://androidexample.com/Incomming_Phone_Call_Broadcast_Receiver__-_Android_Example/index.php?view=article_discription&aid=61
Make a broadcast receiver to know about incoming call
write that code in AndroidManifes.xml
<receiver android:name=".ServiceReceiver" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
and make a new a class like that.
public class ServiceReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(new PhoneStateListener(){
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if(state.equals(TelephonyManager.EXTRA_STATE_RINGING)){
// Run the flash in that line
}
}
},PhoneStateListener.LISTEN_CALL_STATE);
}
}

Chromecast - SIGN_IN_REQUIRED

Only a small portion of my users are getting this error and I can't for the life of me figure it out. I use GooglePlayServicesUtil.isGooglePlayServicesAvailable(downloadService) to test whether or not Play Services is available, and it always returns SUCCESS. I setup the channel to connect to the Chromecast, and everything works fine up until the point where I try to use RemoteMediaPlayer.load. The result is always SIGN_IN_REQUIRED for some users, with resolution: null. The status.toString() is Failed to load: Status{statusCode=SIGN_IN_REQUIRED, resolution=null}. I'm really not sure what I am supposed to with this or how to get rid of the error for my few users who are getting this.
I don't know what portion is related, so I am just posting my entire controller class:
public class ChromeCastController extends RemoteController {
private static final String TAG = ChromeCastController.class.getSimpleName();
private CastDevice castDevice;
private GoogleApiClient apiClient;
private ConnectionCallbacks connectionCallbacks;
private ConnectionFailedListener connectionFailedListener;
private Cast.Listener castClientListener;
private boolean applicationStarted = false;
private boolean waitingForReconnect = false;
private boolean error = false;
private boolean ignoreNextPaused = false;
private String sessionId;
private FileProxy proxy;
private String rootLocation;
private RemoteMediaPlayer mediaPlayer;
private double gain = 0.5;
public ChromeCastController(DownloadService downloadService, CastDevice castDevice) {
this.downloadService = downloadService;
this.castDevice = castDevice;
SharedPreferences prefs = Util.getPreferences(downloadService);
rootLocation = prefs.getString(Constants.PREFERENCES_KEY_CACHE_LOCATION, null);
}
#Override
public void create(boolean playing, int seconds) {
downloadService.setPlayerState(PlayerState.PREPARING);
connectionCallbacks = new ConnectionCallbacks(playing, seconds);
connectionFailedListener = new ConnectionFailedListener();
castClientListener = new Cast.Listener() {
#Override
public void onApplicationStatusChanged() {
if (apiClient != null && apiClient.isConnected()) {
Log.i(TAG, "onApplicationStatusChanged: " + Cast.CastApi.getApplicationStatus(apiClient));
}
}
#Override
public void onVolumeChanged() {
if (apiClient != null && applicationStarted) {
try {
gain = Cast.CastApi.getVolume(apiClient);
} catch(Exception e) {
Log.w(TAG, "Failed to get volume");
}
}
}
#Override
public void onApplicationDisconnected(int errorCode) {
shutdownInternal();
}
};
Cast.CastOptions.Builder apiOptionsBuilder = Cast.CastOptions.builder(castDevice, castClientListener);
apiClient = new GoogleApiClient.Builder(downloadService)
.addApi(Cast.API, apiOptionsBuilder.build())
.addConnectionCallbacks(connectionCallbacks)
.addOnConnectionFailedListener(connectionFailedListener)
.build();
apiClient.connect();
}
#Override
public void start() {
if(error) {
error = false;
Log.w(TAG, "Attempting to restart song");
startSong(downloadService.getCurrentPlaying(), true, 0);
return;
}
try {
mediaPlayer.play(apiClient);
} catch(Exception e) {
Log.e(TAG, "Failed to start");
}
}
#Override
public void stop() {
try {
mediaPlayer.pause(apiClient);
} catch(Exception e) {
Log.e(TAG, "Failed to pause");
}
}
#Override
public void shutdown() {
try {
if(mediaPlayer != null && !error) {
mediaPlayer.stop(apiClient);
}
} catch(Exception e) {
Log.e(TAG, "Failed to stop mediaPlayer", e);
}
try {
if(apiClient != null) {
Cast.CastApi.stopApplication(apiClient);
Cast.CastApi.removeMessageReceivedCallbacks(apiClient, mediaPlayer.getNamespace());
mediaPlayer = null;
applicationStarted = false;
}
} catch(Exception e) {
Log.e(TAG, "Failed to shutdown application", e);
}
if(apiClient != null && apiClient.isConnected()) {
apiClient.disconnect();
}
apiClient = null;
if(proxy != null) {
proxy.stop();
proxy = null;
}
}
private void shutdownInternal() {
// This will call this.shutdown() indirectly
downloadService.setRemoteEnabled(RemoteControlState.LOCAL, null);
}
#Override
public void updatePlaylist() {
if(downloadService.getCurrentPlaying() == null) {
startSong(null, false, 0);
}
}
#Override
public void changePosition(int seconds) {
try {
mediaPlayer.seek(apiClient, seconds * 1000L);
} catch(Exception e) {
Log.e(TAG, "FAiled to seek to " + seconds);
}
}
#Override
public void changeTrack(int index, DownloadFile song) {
startSong(song, true, 0);
}
#Override
public void setVolume(boolean up) {
double delta = up ? 0.1 : -0.1;
gain += delta;
gain = Math.max(gain, 0.0);
gain = Math.min(gain, 1.0);
getVolumeToast().setVolume((float) gain);
try {
Cast.CastApi.setVolume(apiClient, gain);
} catch(Exception e) {
Log.e(TAG, "Failed to the volume");
}
}
#Override
public int getRemotePosition() {
if(mediaPlayer != null) {
return (int) (mediaPlayer.getApproximateStreamPosition() / 1000L);
} else {
return 0;
}
}
#Override
public int getRemoteDuration() {
if(mediaPlayer != null) {
return (int) (mediaPlayer.getStreamDuration() / 1000L);
} else {
return 0;
}
}
void startSong(DownloadFile currentPlaying, boolean autoStart, int position) {
if(currentPlaying == null) {
try {
if (mediaPlayer != null && !error) {
mediaPlayer.stop(apiClient);
}
} catch(Exception e) {
// Just means it didn't need to be stopped
}
downloadService.setPlayerState(PlayerState.IDLE);
return;
}
downloadService.setPlayerState(PlayerState.PREPARING);
MusicDirectory.Entry song = currentPlaying.getSong();
try {
MusicService musicService = MusicServiceFactory.getMusicService(downloadService);
String url;
// Offline, use file proxy
if(Util.isOffline(downloadService) || song.getId().indexOf(rootLocation) != -1) {
if(proxy == null) {
proxy = new FileProxy(downloadService);
proxy.start();
}
url = proxy.getPublicAddress(song.getId());
} else {
if(proxy != null) {
proxy.stop();
proxy = null;
}
if(song.isVideo()) {
url = musicService.getHlsUrl(song.getId(), currentPlaying.getBitRate(), downloadService);
} else {
url = musicService.getMusicUrl(downloadService, song, currentPlaying.getBitRate());
}
url = fixURLs(url);
}
// Setup song/video information
MediaMetadata meta = new MediaMetadata(song.isVideo() ? MediaMetadata.MEDIA_TYPE_MOVIE : MediaMetadata.MEDIA_TYPE_MUSIC_TRACK);
meta.putString(MediaMetadata.KEY_TITLE, song.getTitle());
if(song.getTrack() != null) {
meta.putInt(MediaMetadata.KEY_TRACK_NUMBER, song.getTrack());
}
if(!song.isVideo()) {
meta.putString(MediaMetadata.KEY_ARTIST, song.getArtist());
meta.putString(MediaMetadata.KEY_ALBUM_ARTIST, song.getArtist());
meta.putString(MediaMetadata.KEY_ALBUM_TITLE, song.getAlbum());
String coverArt = "";
if(proxy == null) {
coverArt = musicService.getCoverArtUrl(downloadService, song);
coverArt = fixURLs(coverArt);
meta.addImage(new WebImage(Uri.parse(coverArt)));
} else {
File coverArtFile = FileUtil.getAlbumArtFile(downloadService, song);
if(coverArtFile != null && coverArtFile.exists()) {
coverArt = proxy.getPublicAddress(coverArtFile.getPath());
meta.addImage(new WebImage(Uri.parse(coverArt)));
}
}
}
String contentType;
if(song.isVideo()) {
contentType = "application/x-mpegURL";
}
else if(song.getTranscodedContentType() != null) {
contentType = song.getTranscodedContentType();
} else if(song.getContentType() != null) {
contentType = song.getContentType();
} else {
contentType = "audio/mpeg";
}
// Load it into a MediaInfo wrapper
MediaInfo mediaInfo = new MediaInfo.Builder(url)
.setContentType(contentType)
.setStreamType(MediaInfo.STREAM_TYPE_BUFFERED)
.setMetadata(meta)
.build();
if(autoStart) {
ignoreNextPaused = true;
}
mediaPlayer.load(apiClient, mediaInfo, autoStart, position * 1000L).setResultCallback(new ResultCallback<RemoteMediaPlayer.MediaChannelResult>() {
#Override
public void onResult(RemoteMediaPlayer.MediaChannelResult result) {
if (result.getStatus().isSuccess()) {
// Handled in other handler
} else if(result.getStatus().getStatusCode() != ConnectionResult.SIGN_IN_REQUIRED) {
Log.e(TAG, "Failed to load: " + result.getStatus().toString());
failedLoad();
}
}
});
} catch (IllegalStateException e) {
Log.e(TAG, "Problem occurred with media during loading", e);
failedLoad();
} catch (Exception e) {
Log.e(TAG, "Problem opening media during loading", e);
failedLoad();
}
}
private String fixURLs(String url) {
// Only change to internal when using https
if(url.indexOf("https") != -1) {
SharedPreferences prefs = Util.getPreferences(downloadService);
int instance = prefs.getInt(Constants.PREFERENCES_KEY_SERVER_INSTANCE, 1);
String externalUrl = prefs.getString(Constants.PREFERENCES_KEY_SERVER_URL + instance, null);
String internalUrl = prefs.getString(Constants.PREFERENCES_KEY_SERVER_INTERNAL_URL + instance, null);
url = url.replace(internalUrl, externalUrl);
}
// Use separate profile for Chromecast so users can do ogg on phone, mp3 for CC
return url.replace(Constants.REST_CLIENT_ID, Constants.CHROMECAST_CLIENT_ID);
}
private void failedLoad() {
Util.toast(downloadService, downloadService.getResources().getString(R.string.download_failed_to_load));
downloadService.setPlayerState(PlayerState.STOPPED);
error = true;
}
private class ConnectionCallbacks implements GoogleApiClient.ConnectionCallbacks {
private boolean isPlaying;
private int position;
private ResultCallback<Cast.ApplicationConnectionResult> resultCallback;
ConnectionCallbacks(boolean isPlaying, int position) {
this.isPlaying = isPlaying;
this.position = position;
resultCallback = new ResultCallback<Cast.ApplicationConnectionResult>() {
#Override
public void onResult(Cast.ApplicationConnectionResult result) {
Status status = result.getStatus();
if (status.isSuccess()) {
ApplicationMetadata applicationMetadata = result.getApplicationMetadata();
sessionId = result.getSessionId();
String applicationStatus = result.getApplicationStatus();
boolean wasLaunched = result.getWasLaunched();
applicationStarted = true;
setupChannel();
} else {
shutdownInternal();
}
}
};
}
#Override
public void onConnected(Bundle connectionHint) {
if (waitingForReconnect) {
Log.i(TAG, "Reconnecting");
reconnectApplication();
} else {
launchApplication();
}
}
#Override
public void onConnectionSuspended(int cause) {
Log.w(TAG, "Connection suspended");
isPlaying = downloadService.getPlayerState() == PlayerState.STARTED;
position = getRemotePosition();
waitingForReconnect = true;
}
void launchApplication() {
try {
Cast.CastApi.launchApplication(apiClient, CastCompat.APPLICATION_ID, false).setResultCallback(resultCallback);
} catch (Exception e) {
Log.e(TAG, "Failed to launch application", e);
}
}
void reconnectApplication() {
try {
Cast.CastApi.joinApplication(apiClient, CastCompat.APPLICATION_ID, sessionId).setResultCallback(resultCallback);
} catch (Exception e) {
Log.e(TAG, "Failed to reconnect application", e);
}
}
void setupChannel() {
if(!waitingForReconnect) {
mediaPlayer = new RemoteMediaPlayer();
mediaPlayer.setOnStatusUpdatedListener(new RemoteMediaPlayer.OnStatusUpdatedListener() {
#Override
public void onStatusUpdated() {
MediaStatus mediaStatus = mediaPlayer.getMediaStatus();
if (mediaStatus == null) {
return;
}
switch (mediaStatus.getPlayerState()) {
case MediaStatus.PLAYER_STATE_PLAYING:
if (ignoreNextPaused) {
ignoreNextPaused = false;
}
downloadService.setPlayerState(PlayerState.STARTED);
break;
case MediaStatus.PLAYER_STATE_PAUSED:
if (!ignoreNextPaused) {
downloadService.setPlayerState(PlayerState.PAUSED);
}
break;
case MediaStatus.PLAYER_STATE_BUFFERING:
downloadService.setPlayerState(PlayerState.PREPARING);
break;
case MediaStatus.PLAYER_STATE_IDLE:
if (mediaStatus.getIdleReason() == MediaStatus.IDLE_REASON_FINISHED) {
downloadService.setPlayerState(PlayerState.COMPLETED);
downloadService.onSongCompleted();
} else if (mediaStatus.getIdleReason() == MediaStatus.IDLE_REASON_INTERRUPTED) {
if (downloadService.getPlayerState() != PlayerState.PREPARING) {
downloadService.setPlayerState(PlayerState.PREPARING);
}
} else if (mediaStatus.getIdleReason() == MediaStatus.IDLE_REASON_ERROR) {
Log.e(TAG, "Idle due to unknown error");
downloadService.setPlayerState(PlayerState.COMPLETED);
downloadService.next();
} else {
Log.w(TAG, "Idle reason: " + mediaStatus.getIdleReason());
downloadService.setPlayerState(PlayerState.IDLE);
}
break;
}
}
});
}
try {
Cast.CastApi.setMessageReceivedCallbacks(apiClient, mediaPlayer.getNamespace(), mediaPlayer);
} catch (IOException e) {
Log.e(TAG, "Exception while creating channel", e);
}
if(!waitingForReconnect) {
DownloadFile currentPlaying = downloadService.getCurrentPlaying();
startSong(currentPlaying, isPlaying, position);
}
if(waitingForReconnect) {
waitingForReconnect = false;
}
}
}
private class ConnectionFailedListener implements GoogleApiClient.OnConnectionFailedListener {
#Override
public void onConnectionFailed(ConnectionResult result) {
shutdownInternal();
}
}
}
Edit for logs:
03-28 19:04:49.757 6305-6305/github.daneren2005.dsub I/ChromeCastController﹕ onApplicationStatusChanged: Chromecast Home Screen
03-28 19:04:52.280 6305-6305/github.daneren2005.dsub I/ChromeCastController﹕ onApplicationStatusChanged: null
03-28 19:04:54.162 6305-6305/github.daneren2005.dsub I/ChromeCastController﹕ onApplicationStatusChanged: Ready To Cast
03-28 19:05:05.194 6305-6305/github.daneren2005.dsub E/ChromeCastController﹕ Failed to load: Status{statusCode=SIGN_IN_REQUIRED, resolution=null}
It is strange that you are getting such status code at that time. What comes to mind is that the user may have not logged into his/her gmail account or something along those lines. Do you have the log file for us to take a look at to see if we can get more from the context? Also, to be sure, such user sees the application launched on the TV and only when it comes to loading a media that error is thrown?
The issue is due to using a Self Signed Certificate. I didn't realize the issue on my old phone because I had changed hosts and bought a normal certificate after switching phones. It would be nice if the SDK would through a useful error though. The one thrown makes you think that it is a problem with connecting to the Play Services SDK, and not a problem with the actual URL being used.

I am working with Twilio android SDK, When i click on hangup button always getting error ?not able to disconnect the call after dialing?

I have successfully integrated Twilio SDK for android but when i am trying to make call with it its not connecting and showing error message in logcat i am getting following errors:
1) Failed to hangup call due to error code: 70015, message: pjsua_call_hangup(): Object already exists (PJ_EEXISTS)
2) Connection disconnected with error code 31000 and message Generic error
this both errors occurs when i am calling disconnect method if i comment this method then my calling is working fine and i make call but if i call this method phone.disconnect(), i am getting error shown as above.
This is my methods which i am using to make calls and to disconnect the calls.
////// To Make Calls
public void connect(String phoneNumber) {
Map parameters = new HashMap();
parameters.put("PhoneNumber", phoneNumber);
connection = device.connect(parameters, null /* ConnectionListener */);
if (connection == null)
Log.w(TAG, "Failed to create new connection");
}
// To Disconnect Phone
public void disconnect() {
if (connection != null) {
connection.disconnect();
connection = null; // will null out in onDisconnected()
if (basicConnectionListener != null)
basicConnectionListener.onConnectionDisconnecting();
}
}
and on my OnClick event:
public void onClick(View view) {
if (view.getId() == R.id.dialButton)
Toast.makeText(getApplicationContext(), "Dialing...", Toast.LENGTH_LONG).show();
phone.connect("PHONE NUMBER");
if (view.getId() == R.id.hangupButton)
Toast.makeText(getApplicationContext(), "Call Disconnected...", Toast.LENGTH_LONG).show();
phone.disconnect();
Please suggest me and help me because i tried all possible thing for hangout but still not able to solve it.Thanks in advance. ![enter image description here][1]
I am sharing my working class for twilio SDK setup.
This the calls which is working perfectly for me.I would like to share my class so any one can take reference of it.
This is the Base class which handle all the events of twillio Calling and Disconnecting the call.
import java.util.HashMap;
import java.util.Map;
import android.content.Context;
import android.media.AudioManager;
import android.util.Log;
import android.view.Gravity;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;
import com.twilio.client.Connection;
import com.twilio.client.Connection.State;
import com.twilio.client.ConnectionListener;
import com.twilio.client.Device;
import com.twilio.client.DeviceListener;
import com.twilio.client.PresenceEvent;
import com.twilio.client.Twilio;
public class MonkeyPhone implements Twilio.InitListener, DeviceListener, ConnectionListener {
private static final String TAG = "MonkeyPhone";
private Device device;
private Connection connection;
private final Context context;
private BasicConnectionListener basicConnectionListener;
private BasicDeviceListener basicDeviceListener;
private Connection pendingIncomingConnection;
InputMethodManager imm;
private boolean speakerEnabled;
private boolean muteEnabled;
public interface BasicConnectionListener {
public void onIncomingConnectionDisconnected();
public void onConnectionConnecting();
public void onConnectionConnected();
public void onConnectionFailedConnecting(Exception error);
public void onConnectionDisconnecting();
public void onConnectionDisconnected();
public void onConnectionFailed(Exception error);
}
public interface BasicDeviceListener {
public void onDeviceStartedListening();
public void onDeviceStoppedListening(Exception error);
}
public MonkeyPhone(Context context) {
this.context = context;
Twilio.initialize(context, this /* Twilio.InitListener */);
}
public void setListeners(BasicConnectionListener basicConnectionListener, BasicDeviceListener basicDeviceListener) {
this.basicConnectionListener = basicConnectionListener;
this.basicDeviceListener = basicDeviceListener;
}
/* Twilio.InitListener method */
#Override
public void onInitialized() {
Log.d(TAG, "Twilio SDK is ready");
try {
// String capabilityToken =
// HttpHelper.httpGet("http://------/mobile/auth.php");
String capabilityToken = HttpHelper.httpGet("http:------/auth.php");
device = Twilio.createDevice(capabilityToken, null /* DeviceListener */);
} catch (Exception e) {
Log.e(TAG, "Failed to obtain capability token: " + e.getLocalizedMessage());
}
}
/* Twilio.InitListener method */
#Override
public void onError(Exception e) {
Log.e(TAG, "Twilio SDK couldn't start: " + e.getLocalizedMessage());
}
#Override
protected void finalize() {
if (device != null)
device.release();
if (connection != null)
connection.disconnect();
}
// To Make Calls
public void connect(String phoneNumber) {
Toast toast = Toast.makeText(context, "Dialing...", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("PhoneNumber", phoneNumber);
String capabilityToken;
try {
// capabilityToken =
// HttpHelper.httpGet("http://------/mobile/auth.php");
capabilityToken = HttpHelper.httpGet("http://------/mobile/auth.php");
device = Twilio.createDevice(capabilityToken, null /* DeviceListener */);
} catch (Exception e1) {
e1.printStackTrace();
}
try {
device.disconnectAll();
} catch (Exception e) {
e.printStackTrace();
}
connection = device.connect(parameters, null /* ConnectionListener */);
if (connection == null) {
Log.w(TAG, "Failed to create new connection");
}
}
// To Disconnect Phone
public void disconnect() {
Toast toast = Toast.makeText(context, "Call Disconnected...", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
if (connection != null) {
connection.disconnect();
connection = null; // will null out in onDisconnected()
if (basicConnectionListener != null)
basicConnectionListener.onConnectionDisconnecting();
}
}
public void setSpeakerEnabled(boolean speakerEnabled) {
if (speakerEnabled != this.speakerEnabled) {
this.speakerEnabled = speakerEnabled;
updateAudioRoute();
}
}
private void updateAudioRoute() {
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
audioManager.setSpeakerphoneOn(speakerEnabled);
}
public void setMuteEnabled(boolean muteEnabled) {
if (muteEnabled != this.muteEnabled) {
this.muteEnabled = muteEnabled;
updateAudioRouteForMute();
}
}
private void updateAudioRouteForMute() {
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
audioManager.setMicrophoneMute(muteEnabled);
}
public State status() {
connection.getState();
State statusHere = connection.getState();
return statusHere;
}
#Override
public void onConnected(Connection arg0) {
updateAudioRoute();
updateAudioRouteForMute();
if (basicConnectionListener != null) {
basicConnectionListener.onConnectionConnected();
}
}
#Override
public void onConnecting(Connection arg0) {
if (basicConnectionListener != null) {
basicConnectionListener.onConnectionConnecting();
}
}
#Override
public void onDisconnected(Connection inConnection) {
if (inConnection == connection) {
connection = null;
if (basicConnectionListener != null)
basicConnectionListener.onConnectionDisconnected();
} else if (inConnection == pendingIncomingConnection) {
pendingIncomingConnection = null;
if (basicConnectionListener != null)
basicConnectionListener.onIncomingConnectionDisconnected();
}
}
#Override
public void onDisconnected(Connection inConnection, int arg1, String inErrorMessage) {
if (inConnection == connection) {
connection = null;
if (basicConnectionListener != null)
basicConnectionListener.onConnectionFailedConnecting(new Exception(inErrorMessage));
}
}
#Override
public void onPresenceChanged(Device arg0, PresenceEvent arg1) {
}
#Override
public void onStartListening(Device arg0) {
if (basicDeviceListener != null) {
basicDeviceListener.onDeviceStartedListening();
}
}
#Override
public void onStopListening(Device arg0) {
if (basicDeviceListener != null) {
basicDeviceListener.onDeviceStoppedListening(null);
}
}
#Override
public void onStopListening(Device arg0, int arg1, String arg2) {
}
#Override
public boolean receivePresenceEvents(Device arg0) {
return false;
}
}
You can use this class like:
private MonkeyPhone phone;
//On create
phone = new MonkeyPhone(getApplicationContext());
//On Call Button Click
#Override
public void onClick(View view) {
if (view.getId() == R.id.btnCallHere) {
phone.connect(newContact);
} else if (view.getId() == R.id.btnDisconnectHere) {
phone.disconnect();
}

SipDemo Outgoing Call

I've totally involved by SipDemo app. I am making Sip call and it is done. I can hear voice but other sip person is unable to hear my voice.
This is my Registration code:-
public void initializeLocalProfile() {
if (manager == null) {
return;
}
if (me != null) {
closeLocalProfile();
}
//sipcallid
// username and password should be same
// sipAddress = "101#217.xx.xxx.xxx";
String domain = sipAddress.substring(sipAddress.indexOf('#')+1);
String username = sipAddress.substring(0,sipAddress.indexOf('#'));
Toast.makeText(outcall.this, "domain = "+domain+" username "+username, Toast.LENGTH_LONG).show();
try {
SipProfile.Builder builder = new SipProfile.Builder(username, domain);
builder.setPassword("123456");
builder.setOutboundProxy(domain);
builder.setDisplayName(username);
builder.setAuthUserName(username);
//builder.setDisplayName(username);
// builder.setAutoRegistration(true);
// builder.setSendKeepAlive(true);
me = builder.build();
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 (SipException se) {
updateStatus("Connection error.");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This is my Initiate call:-
// sipcallid = "rahul22#sip2sip.info";
updateStatus(sipcallid);
try {
SipAudioCall.Listener listener = new SipAudioCall.Listener() {
#Override
public void onCallEstablished(SipAudioCall call) {
call.startAudio();
//call.setSpeakerMode(true);
call.toggleMute();
updateStatus1("on call established");
}
#Override
public void onCallEnded(SipAudioCall call) {
updateStatus1("on call end");
finish();
}
};
call = manager.makeAudioCall(me.getUriString(), sipcallid, listener, 30);
updateStatus1(""+call.getState());
}
catch (Exception e) {
Toast.makeText(outcall.this, "Error when trying to close manager"+ e.getMessage(), Toast.LENGTH_LONG).show();
if (me != null) {
try {
manager.close(me.getUriString());
} catch (Exception ee) {
Toast.makeText(outcall.this, "ee"+ e.getMessage(), Toast.LENGTH_LONG).show();
ee.printStackTrace();
}
}
if (call != null) {
call.close();
}
}
}
Please Except. I can hear the voice of other person but other person can't hear my voice.
please help me!. Thank you for your timing.
It raise when your IP adress is NAT address usually. Android not support NAT by default. For supporting with NAT you will use other external libraries such as CSipSimple.
I see that you call call.toggleMute()
Could it be that you are muting the microphone? The SipDemo app has a button which unmutes the microphone.
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;
}
Maybe you just mute the microphone when you initiate the call but never unmute?

Registration fail error in sipdemo application

I am using SIPDEMO application . when i am login by username , domain, and password . it give me "Registration fail error" ..
I have checked in my iphone and working well . so there is not any problem in my sip accounts.
i have also read the completed code but unable to find any error
please expert help me
this is code:-
public class WalkieTalkieActivity extends Activity implements View.OnTouchListener {
public String sipAddress = null;
public SipManager manager = null;
public SipProfile me = null;
public SipAudioCall call = null;
public IncomingCallReceiver callReceiver;
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);
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();
}
#Override
public void onDestroy() {
super.onDestroy();
if (call != null) {
call.close();
}
closeLocalProfile();
if (callReceiver != null) {
this.unregisterReceiver(callReceiver);
}
}
public void initializeManager() {
if(manager == null) {
manager = SipManager.newInstance(this);
Log.v("sip_test", "manager: " + manager.toString());
Log.v("sip_test", "isApiSupported: " + new Boolean(SipManager.isApiSupported(this)).toString());
Log.v("sip_test", "isSipWifiOnly: " + new Boolean(SipManager.isSipWifiOnly(this)).toString());
Log.v("sip_test", "isVoipSupported: " + new Boolean(SipManager.isVoipSupported(this)).toString());
}
initializeLocalProfile();
}
/**
* Logs you into your SIP provider, registering this device as the location to
* send SIP calls to for your SIP address.
*/
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", "");
System.out.println("username " +username);
System.out.println("domain " +domain);
System.out.println("password " +password);
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.");
System.out.println("local profile uri " + localProfileUri);
System.out.println("error code" + errorCode);
System.out.println("error message " +errorMessage);
}
});
} catch (ParseException pe) {
updateStatus("Connection Error.");
System.out.println("parse exception"+pe.getMessage());
} catch (SipException se) {
updateStatus("Connection error.");
System.out.println("Connection exception"+se.getMessage());
}
}
/**
* Closes out your local profile, freeing associated objects into memory
* and unregistering your device from the server.
*/
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);
}
}
/**
* Make an outgoing call.
*/
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.
#Override
public void onCallEstablished(SipAudioCall call) {
call.startAudio();
call.setSpeakerMode(true);
call.toggleMute();
updateStatus(call);
}
#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();
}
}
}
/**
* Updates the status box at the top of the UI with a messege of your choice.
* #param status The String to display in the status box.
*/
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);
}
});
}
/**
* Updates the status box with the SIP address of the current call.
* #param call The current, active call.
*/
public void updateStatus(SipAudioCall call) {
String useName = call.getPeerProfile().getDisplayName();
if(useName == null) {
useName = call.getPeerProfile().getUserName();
}
updateStatus(useName + "#" + call.getPeerProfile().getSipDomain());
}
/**
* Updates whether or not the user's voice is muted, depending on whether the button is pressed.
* #param v The View where the touch event is being fired.
* #param event The motion to act on.
* #return boolean Returns false to indicate that the parent view should handle the touch event
* as it normally would.
*/
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;
}
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));
// sipAddress = textField.getText().toString();
sipAddress= "sip:kukukkk#ekiga.net";
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);
}
}
Check your android phone is Sip supported or not.
Confirm this code is included in Manifest file:
<uses-sdk android:minSdkVersion="9" />

Categories

Resources