I have my IncomingCallReceiver class from which I want to send my incoming calls to another activity to give user option to Receive or Decline incoming call this is my IncomingReceiver class and clearly out of ideas so If someone might suggest how do I do that.
public class IncomingCallReceiver extends BroadcastReceiver {
#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();
}
}
};
MainActivity wtActivity = (MainActivity) context;
incomingCall = wtActivity.manager.takeAudioCall(intent, listener);
incomingCall.answerCall(30);
incomingCall.startAudio();
incomingCall.setSpeakerMode(true);
wtActivity.call = incomingCall;
wtActivity.updateStatus(incomingCall);
} catch (Exception e) {
if (incomingCall != null) {
incomingCall.close();
}
}
}
}
Hi the question has already been answered in stackoverflow , Anyway change your onRinging method as follows.
SipAudioCall incomingCall = null;
try {
SipAudioCall.Listener listener = new SipAudioCall.Listener() {
#Override
public void onRinging(SipAudioCall call, SipProfile caller) {
super.onRinging(call, caller);
}
};
MainActivity wtActivity = (MainActivity) context;
incomingCall = wtActivity.manager.takeAudioCall(intent, listener);
//Method call which handles incoming call.
showIncomingCall(intent, context);
wtActivity.call = incomingCall;
wtActivity.updateStatus(incomingCall);
} catch (Exception e) {
if (incomingCall != null) {
incomingCall.close();
}
}
private void showIncomingCall(Intent intent, Context context) {
Intent incomingCall = new Intent(context, IncomingCallActivity.class);
context.startActivity(incomingCall);
}
public static void answerIncomingCall() {
try {
incomingCall.answerCall(30);
incomingCall.startAudio();
if (incomingCall.isMuted()) {
incomingCall.toggleMute();
}
}
catch (Exception e) {
System.out.println(e.toString());
}
}
public static void rejectIncomingCall() {
try {
if (incomingCall != null) {
incomingCall.endCall();
incomingCall.close();
}
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
And in your incoming call Activity where you have Answer and Reject call buttons, put the following code.
btnAnswer.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
IncomingCallReceiver.answerIncomingCall();
}
});
btnDecline.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
IncomingCallReceiver.rejectIncomingCall();
finish();
}
});
Related
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);
}
}
I'm developing a sip client based on the SipDemo app. My app receives incoming calls successfully at first, but after some time my app cannot receive calls. BroadcastReceiver doesn't receive anything. What could cause this?
My manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.kasenna.android.kasip">
<uses-permission android:name="android.permission.USE_SIP" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<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" />
<application android:icon="#drawable/icon" android:label="KaSip">
<activity android:name=".MainActivity"
android:launchMode="singleTask"
android:taskAffinity="">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name=".SipSettings" android:label="Настройки"/>
<receiver android:name=".IncomingCallReceiver" android:label="Call Receiver"/>
<service android:name=".MainService" android:exported="false"/>
</application>
</manifest>
Main activity:
package com.kasenna.android.kasip;
public class MainActivity extends FragmentActivity implements
IncallFragmentClass.IncallButtonsEventListener,
IncallCallEndFragmentClass.IncallCallEndButtonsEventListener,
MakeCallFragmentClass.MakeCallButtonsEventListener,
DialpadFragmentClass.DialpadButtonsEventListener
{
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.main);
mswitch=(Switch)findViewById(R.id.regswitch);
mswitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked){
if(isChecked){
SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String username=prefs.getString("namePref","");
String password=prefs.getString("passPref","");
if(username.length()==0||password.length()==0){
showDialog(UPDATE_SETTINGS_DIALOG);
}else {
accRegistered = true;
//registrationWorker("start");
initializeLocalProfile();
}
}else{
SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String username=prefs.getString("namePref","");
String password=prefs.getString("passPref","");
if(username.length()==0||password.length()==0){
}else {
accRegistered = false;
//registrationWorker("stop");
closeLocalProfile();
}
}
}
});
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
AudioManager manager=(AudioManager)getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
manager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
Uri notification=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
ring = RingtoneManager.getRingtone(getApplicationContext(),notification);
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container_dialpad, (new DialpadFragmentClass())).commit();
ImageButton delButton = (ImageButton) findViewById(R.id.buttonDel);
delButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextView labelView=(TextView)findViewById(R.id.sipLabelDialpad);
String currentString = labelView.getText().toString();
String needText = currentString.equals("") ? "" : currentString.substring(0,currentString.length()-1);
updateStatus(needText,true);
if((!currentString.equals(""))&(needText.equals(""))){
getSupportFragmentManager().beginTransaction().remove(mMakeCallClass).commit();
}
}
});
initializeManager();
}
public void initializeManager(){
IntentFilter filter = new IntentFilter();
filter.addAction("android.KaSip.INCOMING_CALL");
callReceiver = new IncomingCallReceiver();
this.registerReceiver(callReceiver,filter);
if(manager == null){
manager = SipManager.newInstance(this);
Log.v("KaSip_logs","manager created: "+manager.toString());
}
}
public void initializeLocalProfile(){
if(manager == null){
return;
}
if(me != null){
closeLocalProfile();
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String username = prefs.getString("namePref","");
String password = prefs.getString("passPref","");
try{
SipProfile.Builder builder = new SipProfile.Builder(username,"cgp.cittel.ru");
builder.setPassword(password);
ConnectivityManager connManager=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi=connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if(mWifi.isConnected()){
builder.setProtocol("TCP");
}else{
builder.setProtocol("UDP");
}
builder.setSendKeepAlive(true);
builder.setAutoRegistration(true);
me=builder.build();
updateStatus("регистрация...");
Intent mServiceIntent = new Intent(this,MainService.class);
String dataUrl = me.getUriString();
mServiceIntent.setData(Uri.parse(dataUrl));
startService(mServiceIntent);
Intent i = new Intent();
i.setAction("android.KaSip.INCOMING_CALL");
PendingIntent pi = PendingIntent.getBroadcast(this,0,i,Intent.FILL_IN_DATA);
Log.v("KaSip_logs","SipProfile="+me.getUriString());
manager.open(me,pi,null);
Log.v("KaSip_logs","after manager open");
SipRegistrationListener mListener = new SipRegistrationListener(){
public void onRegistering(String localProfileUri){
}
public void onRegistrationDone(String localProfileUri,long expiryTime){
updateStatus("зарегистрирован");
}
public void onRegistrationFailed(String localProfileUri,int errorCode,String errorMessage){
Log.v("KaSip_logs","SipRegistrationListener error="+errorMessage);
}
};
manager.setRegistrationListener(me.getUriString(),mListener);
manager.register(me,60,mListener);
Log.v("KaSip_logs","manager register");
}catch(ParseException pe){
pe.printStackTrace();
}catch(SipException se){
Log.v("KaSip_logs","SipException="+se.getMessage());
}
}
public void closeLocalProfile(){
if(manager==null){
return;
}
try{
if(me!=null){
manager.close(me.getUriString());
}
}catch(Exception ee){
ee.printStackTrace();
}
updateStatus("не зарегистрирован");
}
public void updatePreferences(){
Intent settingsActivity=new Intent(getBaseContext(),
SipSettings.class);
startActivity(settingsActivity);
}
public void onReceiveCallBroadcast(Intent intent){
SipAudioCall.Listener listener=new SipAudioCall.Listener(){
#Override
public void onRinging(SipAudioCall call,SipProfile caller){
super.onRinging(call,caller);
remoteCall=call;
Log.v("KaSip_logs","onReceiveCallBroadcast, onRinging, caller="+caller.getUriString());
}
#Override
public void onCallEnded(SipAudioCall call){
super.onCallEnded(call);
callTimer("stop");
updateStatus("", true);
if(ring.isPlaying()){
ring.stop();
}
if (loadedActionFragment.equals("incall")) {
getSupportFragmentManager().beginTransaction().remove(mIncallFragmentClass).commit();
loadedActionFragment = "";
}else if (loadedActionFragment.equals("incallcallstart")){
getSupportFragmentManager().beginTransaction().remove(mIncallCallEndFragmentClass).commit();
loadedActionFragment = "";
}
}
#Override
public void onCallEstablished(SipAudioCall call){
super.onCallEstablished(call);
callTimer("start");
createUI("incallcallstart");
}
#Override
public void onError(SipAudioCall call, int errorCode, String errorMessage){
super.onError(call,errorCode,errorMessage);
callTimer("stop");
updateStatus("",true);
if (loadedActionFragment.equals("incall")) {
getSupportFragmentManager().beginTransaction().remove(mIncallFragmentClass).commit();
loadedActionFragment = "";
}else if (loadedActionFragment.equals("incallcallstart")){
getSupportFragmentManager().beginTransaction().remove(mIncallCallEndFragmentClass).commit();
loadedActionFragment = "";
}
}
};
try{
incomingCall=manager.takeAudioCall(intent,listener);
}catch(SipException se){
Log.v("KaSip_logs","onReceiveCallBroadcast error="+se.getMessage());
if(incomingCall!=null){
incomingCall.close();
}
if(remoteCall!=null){
remoteCall.close();
}
}
Window window=this.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
ring.play();
updateStatus(incomingCall);
}
#Override
public void OnClick_buttonStart() {
updateStatus("",true);
if (ring.isPlaying()) {
ring.stop();
}
try {
if (remoteCall != null) {
remoteCall.answerCall(30);
}
incomingCall.answerCall(30);
incomingCall.startAudio();
if (incomingCall.isMuted()) {
incomingCall.toggleMute();
}
} catch (SipException se) {
Log.v("KaSip_logs", "onReceiveCallBroadcast error=" + se.getMessage());
if (incomingCall != null) {
incomingCall.close();
}
if (remoteCall != null) {
remoteCall.close();
}
}
}
#Override
public void OnClick_buttonStop() {
if (ring.isPlaying()) {
ring.stop();
}
try {
if (remoteCall != null) {
remoteCall.endCall();
}
if (incomingCall != null) {
incomingCall.endCall();
incomingCall.close();
}
if (remoteCall != null) {
remoteCall.close();
}
} catch (SipException se) {
Log.v("KaSip_logs", "onReceiveCallBroadcast error=" + se.getMessage());
}
callTimer("stop");
synchronized (this) {
try {
this.wait(1000);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
updateStatus("", true);
getSupportFragmentManager().beginTransaction().remove(mIncallFragmentClass).commit();
loadedActionFragment = "";
}
#Override
public void OnClick_buttonCallEnd() {
try {
if (remoteCall != null) {
remoteCall.endCall();
}
if (incomingCall != null) {
incomingCall.endCall();
incomingCall.close();
}
if (outgoingCall != null) {
outgoingCall.endCall();
outgoingCall.close();
}
if (remoteCall != null) {
remoteCall.close();
}
} catch (SipException se) {
Log.v("KaSip_logs", "onReceiveCallBroadcast error=" + se.getMessage());
}
callTimer("stop");
generateRingback("stop");
updateStatus("", true);
getSupportFragmentManager().beginTransaction().remove(mIncallCallEndFragmentClass).commit();
loadedActionFragment = "";
}
#Override
public void OnClick_buttonMakeCall(){
if (accRegistered) {
createUI("incallcallstart");
TextView labelView = (TextView) findViewById(R.id.sipLabelDialpad);
sipAddress = labelView.getText().toString();
try {
SipAudioCall.Listener listener = new SipAudioCall.Listener() {
#Override
public void onCallEstablished(SipAudioCall call) {
super.onCallEstablished(call);
generateRingback("stop");
call.startAudio();
callTimer("start");
updateStatus("", true);
}
#Override
public void onCallEnded(SipAudioCall call) {
super.onCallEnded(call);
callTimer("stop");
generateRingback("stop");
updateStatus("", true);
getSupportFragmentManager().beginTransaction().remove(mIncallCallEndFragmentClass).commit();
loadedActionFragment = "";
}
#Override
public void onCallBusy(SipAudioCall call) {
super.onCallBusy(call);
generateRingback("stop");
updateStatus("номер занят", true);
generateBusy("start");
getSupportFragmentManager().beginTransaction().remove(mIncallCallEndFragmentClass).commit();
loadedActionFragment = "";
}
#Override
public void onRingingBack(SipAudioCall call) {
super.onRingingBack(call);
updateStatus("ждём ответа", true);
generateRingback("start");
}
#Override
public void onError(SipAudioCall call, int errorCode, String errorMessage) {
super.onError(call, errorCode, errorMessage);
callTimer("stop");
generateRingback("stop");
updateStatus("", true);
getSupportFragmentManager().beginTransaction().remove(mIncallCallEndFragmentClass).commit();
loadedActionFragment = "";
}
};
outgoingCall = manager.makeAudioCall(me.getUriString(), sipAddress + "#cgp.cittel.ru", listener, 30);
} catch (Exception e) {
e.printStackTrace();
if (me != null) {
try {
manager.close(me.getUriString());
} catch (Exception ee) {
ee.printStackTrace();
}
}
if (outgoingCall != null) {
outgoingCall.close();
}
}
}else{
Toast.makeText(this,"Сначала зарегистрируйтесь",Toast.LENGTH_LONG).show();
}
}
#Override
public void OnClick_buttonDialPad(final String button_description){
this.runOnUiThread(new Runnable(){
public void run(){
TextView labelView=(TextView)findViewById(R.id.sipLabelDialpad);
if ((loadedActionFragment.equals(""))&&(labelView.getText().toString().equals(""))){
mMakeCallClass = new MakeCallFragmentClass();
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container_call_buttons, mMakeCallClass).commit();
}
updateStatus(labelView.getText()+button_description,true);
}
});
try {
if (incomingCall != null) {
if (button_description.equals("0")) {
incomingCall.sendDtmf(0);
} else if (button_description.equals("1")) {
incomingCall.sendDtmf(1);
} else if (button_description.equals("2")) {
incomingCall.sendDtmf(2);
} else if (button_description.equals("3")) {
incomingCall.sendDtmf(3);
} else if (button_description.equals("4")) {
incomingCall.sendDtmf(4);
} else if (button_description.equals("5")) {
incomingCall.sendDtmf(5);
} else if (button_description.equals("6")) {
incomingCall.sendDtmf(6);
} else if (button_description.equals("7")) {
incomingCall.sendDtmf(7);
} else if (button_description.equals("8")) {
incomingCall.sendDtmf(8);
} else if (button_description.equals("9")) {
incomingCall.sendDtmf(9);
} else if (button_description.equals("*")) {
incomingCall.sendDtmf(10);
} else if (button_description.equals("#")) {
incomingCall.sendDtmf(11);
} else if (button_description.equals("A")) {
incomingCall.sendDtmf(12);
} else if (button_description.equals("B")) {
incomingCall.sendDtmf(13);
} else if (button_description.equals("C")) {
incomingCall.sendDtmf(14);
} else if (button_description.equals("D")) {
incomingCall.sendDtmf(15);
}
}
if (outgoingCall != null) {
if (button_description.equals("0")) {
outgoingCall.sendDtmf(0);
} else if (button_description.equals("1")) {
outgoingCall.sendDtmf(1);
} else if (button_description.equals("2")) {
outgoingCall.sendDtmf(2);
} else if (button_description.equals("3")) {
outgoingCall.sendDtmf(3);
} else if (button_description.equals("4")) {
outgoingCall.sendDtmf(4);
} else if (button_description.equals("5")) {
outgoingCall.sendDtmf(5);
} else if (button_description.equals("6")) {
outgoingCall.sendDtmf(6);
} else if (button_description.equals("7")) {
outgoingCall.sendDtmf(7);
} else if (button_description.equals("8")) {
outgoingCall.sendDtmf(8);
} else if (button_description.equals("9")) {
outgoingCall.sendDtmf(9);
} else if (button_description.equals("*")) {
outgoingCall.sendDtmf(10);
} else if (button_description.equals("#")) {
outgoingCall.sendDtmf(11);
} else if (button_description.equals("A")) {
outgoingCall.sendDtmf(12);
} else if (button_description.equals("B")) {
outgoingCall.sendDtmf(13);
} else if (button_description.equals("C")) {
outgoingCall.sendDtmf(14);
} else if (button_description.equals("D")) {
outgoingCall.sendDtmf(15);
}
}
}catch (Exception e){
e.printStackTrace();
}
}
private class generateRingbackTask extends AsyncTask<Void, Void, Void> {
Context mContext;
public generateRingbackTask(Context context) {
super();
mContext = context;
}
#Override
protected Void doInBackground(Void... voids) {
int counter = 0;
ToneGenerator mRingback = new ToneGenerator(0,ToneGenerator.MAX_VOLUME);
synchronized (this) {
while (!this.isCancelled()) {
mRingback.startTone(ToneGenerator.TONE_SUP_DIAL,1000);
try {
this.wait(1000);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
mRingback.stopTone();
try {
this.wait(1500);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
counter = counter + 2;
}
}
return null;
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void generateRingback(String action){
if(action.equals("start")){
synchronized(this){
mringbackTask = new generateRingbackTask(this);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mringbackTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
else {
mringbackTask.execute();
}
}
}else{
if (mringbackTask !=null){
mringbackTask.cancel(true);
}
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void generateBusy(String action){
if(action.equals("start")){
synchronized(this){
mbusyTask = new generateBusyTask(this);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mbusyTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
else {
mbusyTask.execute();
}
}
}else{
if (mbusyTask !=null){
mbusyTask.cancel(true);
}
}
}
private class generateBusyTask extends AsyncTask<Void, Void, Void> {
Context mContext;
public generateBusyTask(Context context) {
super();
mContext = context;
}
#Override
protected void onPostExecute(Void voids) {
updateStatus("", true);
}
#Override
protected Void doInBackground(Void... voids) {
int counter;
ToneGenerator mBusy = new ToneGenerator(0,ToneGenerator.MAX_VOLUME);
synchronized (this) {
for(counter=0;counter<5;counter++){
mBusy.startTone(ToneGenerator.TONE_SUP_DIAL,300);
try {
this.wait(300);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
mBusy.stopTone();
try {
this.wait(100);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
return null;
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void registrationWorker(String action){
if(action.equals("start")){
synchronized(this){
mregistrationTask = new registrationWorkerTask(this);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mregistrationTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
else {
mregistrationTask.execute();
}
}
}else{
if (mregistrationTask !=null){
mregistrationTask.cancel(true);
}
}
}
private class registrationWorkerTask extends AsyncTask<Void, Void, Void> {
Context mContext;
public registrationWorkerTask(Context context) {
super();
mContext = context;
}
#Override
protected void onPreExecute(){
if ((callReceiver == null)&&(manager == null)){
initializeManager();
}
}
#Override
protected void onProgressUpdate(Void... voids){
initializeLocalProfile();
}
#Override
protected Void doInBackground(Void... voids) {
synchronized (this) {
while (!this.isCancelled()) {
publishProgress(null);
try {
this.wait(58000);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
Log.v("KaSip_logs", "registrationWorkerTask stopped");
return null;
}
}
}
and IncomingCallRecever.java:
package com.kasenna.android.kasip;
public class IncomingCallReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context,
MainActivity.class);
context.startActivity(i);
MainActivity mainActivity = (MainActivity) context;
mainActivity.createUI("incall");
mainActivity.onReceiveCallBroadcast(intent);
}
}
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.
In my application I want to call service from Receiver.
This is my NotificationReceiver.java
public class NotificationReceiver extends BroadcastReceiver {
NotificationReceiver _this = this;
private static Context _context;
public static final String ACTION_REFRESH_SCHEDULE_ALARM = "com.example.receiver.ACTION_REFRESH_SCHEDULE_ALARM";
String SERVER_URL = "http://192.168.1.7:8080";
#Override
public void onReceive(final Context context, Intent intent) {
_context = context;
initClient();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(_context);
if (settings.getString("userId",null) != null){
gotNotification(new ClientListener(){
#Override
public void onSuccess(String response) {
try {
JSONObject object = new JSONObject(response);
System.out.println("Service object = "+ object);
} catch (JSONException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
#Override
public void onFail(int error) {
}
#Override
public void onCancel() {
}
},settings.getString("userId",null));
}
}
private void initClient(){
NotifierRestClient.init(SERVER_URL + "/api");
}
private void gotNotification (final ClientListener clientListener, final String uId) {
new Thread() {
#Override
public void run() {
try {
final String responseText = NotifierRestClient.getUserNotifications(uId,null);
if (clientListener != null) {
clientListener.onSuccess(responseText);
}
} catch (final Exception e) {
e.printStackTrace();
if (clientListener != null) {
clientListener.onFail(505);
}
}
}
}.start();
}
}
And this is my NotifiactionService.java
public class NotificationService extends Service {
private AlarmManager alarmManagerPositioning;
private PendingIntent pendingIntent;
#Override
public void onCreate() {
super.onCreate();
alarmManagerPositioning = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
final Intent intentToNotificate = new Intent(NotificationReceiver.ACTION_REFRESH_SCHEDULE_ALARM);
pendingIntent = PendingIntent.getBroadcast(this, 0, intentToNotificate, 0);
}
#Override
public void onStart(Intent intent, int startId) {
try {
long notificationInterval = 5002;
alarmManagerPositioning.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), notificationInterval, pendingIntent);
} catch (NumberFormatException e) {
Toast.makeText(this, "error running services: " + e.getMessage(), Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(this, "error running services: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onDestroy() {
this.alarmManagerPositioning.cancel(pendingIntent);
}
}
My question is how to call NotificationService in NotificationReceiver and change interval? Any help will be useful Thanks
Start Service in your receiver using
Intent in = new Intent(context,NotificationService.class);
in.putExtra("interval",5001);
context.startService(in);
In your service code,
long notificationInterval = intent.getLongExtra("interval", defaultValue)
to get Data from your receiver, Please use onStartCommand(Intent intent, int flags, int startId), onStart has been deprecated.
i want to add an AlertDialog when a call is received(SIP application) and i'm really confused of how to add this in this bloc:
public class IncomingCallReceiver extends BroadcastReceiver {
#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();
}
}
};
SIPCommunicator wtActivity = (SIPCommunicator) context;
incomingCall = wtActivity.manager.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();
}
}
}
}
Thank you very much for your help.
According to the documentation you cant have alertdialog inside onRecieve
http://developer.android.com/reference/android/content/BroadcastReceiver.html#onReceive(android.content.Context,%20android.content.Intent)