Detecting incoming call [duplicate] - android

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);
}
}

Related

Android : AsyncTaks blocks my interface

I got problem with my asyncTask. I have my custom USB Scanner. I want to turn it on and off with ToggleButton. Scanning works fine but asynctask completly blocks user interface. I can't do nothing. Maybe you know what can I do to make it works better ?
Here's toggleButton :
mScanLayout.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked)
task.execute();
if(!isChecked)
task.cancel(true);
}
});
Here is asynctask :
public class scanAsyncTask extends AsyncTask<Void,Void,Void> {
#Override
protected Void doInBackground(Void... params) {
while(!isCancelled()) {
mActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
adapter = new PartAdapter(getContext(), R.layout.part_item, mParts, mActivity,this);
adapter.startScanning();
}
});
}
return null;
}
}
And this is scanning method from adapter :
public void startScanning(){
final PendingIntent mPermissionIntent = PendingIntent.getBroadcast(getContext(), 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
getContext().registerReceiver(usbReceiver, filter);
UsbManager usbManager = (UsbManager) getContext().getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
UsbDevice device = null;
while (deviceIterator.hasNext()) {
device = deviceIterator.next();
if (device.getVendorId() == 1659 && device.getProductId() == 8963) {
this.device = device;
usbManager.requestPermission(device, mPermissionIntent);
break;
}
}
final UsbDevice finalDevice = device;
final UsbDevice finalDevice1 = device;
UsbConnector.CallbackListener listener = new UsbConnector.CallbackListener() {
#Override
public void onStatusChanged(UsbConnector.Status newStatus) {
Toast.makeText(getContext(), "status: " + newStatus, Toast.LENGTH_SHORT).show();
}
#Override
public void onScanCompleted(String result) {
Toast.makeText(getContext(), "result: " + result, Toast.LENGTH_SHORT).show();
}
};
UsbConnector connector = new UsbConnector(getContext(), finalDevice1,listener);
connector.run();
UsbDeviceConnection usbDeviceConnection = usbManager.openDevice(finalDevice);
UsbSerialDevice serial = UsbSerialDevice.createUsbSerialDevice(finalDevice, usbDeviceConnection);
serial.open();
serial.setBaudRate(57600);
if (finalDevice1 != null) {
connector.run();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
connector.send(pal);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] received = connector.receive(36);
if (received == null) {
Toast.makeText(getContext(), "BĹ‚Ä…d inicjalizacji skanera", Toast.LENGTH_SHORT).show();
}
if (received != null) {
String response = null;
long longValue = ByteBuffer.wrap(received).getLong();
response = Long.toHexString(longValue).toUpperCase();
if (response.contains("DAAD0674016F6B26")) {
connector.send(readId);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] receivedTag = connector.receive(36);
if (receivedTag != null) {
String tag = null;
long tagValue = ByteBuffer.wrap(receivedTag).getLong();
tag = Long.toHexString(tagValue).toUpperCase();
if (tag.contentEquals("DAAD046F62ADA900")) {
startScanning();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (!tag.contains("DAAD046F62ADA900")) {
String tag2 = null;
long tagValue2 = ByteBuffer.wrap(receivedTag).getLong();
tag2 = Long.toHexString(tagValue2).toUpperCase();
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getContext(), notification);
r.play();
int i = 0;
for (Part part : mParts) {
if(part.getCode().contains(tag2)) {
part.setScan(true);
part.setScanCounter(part.getScanCounter() + 1);
i++;
notifyDataSetChanged();
}
}
if(i==0){
Intent intent = new Intent(getContext(),AddActivity.class);
intent.putExtra("tag",tag2);
mActivity.startActivityForResult(intent,2);
}
}
}
}
notifyDataSetChanged();
}
} else {
Toast.makeText(getContext(), R.string.plug_scanner, Toast.LENGTH_SHORT).show();
}
}
Please, help.
in your doInBackground you do:
mActivity.runOnUiThread(new Runnable() {
That defeats the purpose and you do not execute on the background anymore - you are on the main-thread and so block the UI
This Line of your code
mActivity.runOnUiThread(new Runnable() {
Runs on UI thread you should return result in doinbackground and then use it in onPostExecute which runs on UI thread. doInBackground is made to run on background not on UI thread but you forcing it to run on UI thread

android SipDemo cannot receive incoming call

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);
}
}

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.

Start activity on BroadcastReceiver while receiving SIP Calls

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();
}
});

java.lang.NullPointerException at android.content.ContextWrapper.getPackageManager

I am getting this error
java.lang.NullPointerException at android.content.ContextWrapper.getPackageManager
when am trying to get list of all installed applications on the device.
I have a server that starts when my application is started, and the client pings the server and asks to get a list of installed applications. The Server then asks the getPackageManager() and gets all the installed applications.
But the getPackageManager throws a NullPointerException.
The Server is written in a java and is started from my android application.
Could someone please tell me what am missing and why I am getting this error?
Please find the code below
public class ApplicationRecognition extends Activity {
// android.os.Debug.waitForDebugger();
Button buttonStart, buttonStop;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonStart = (Button) findViewById(R.id.buttonStart);
buttonStop = (Button) findViewById(R.id.buttonStop);
final SecurityModuleServer server = new SecurityModuleServer(5902);
server.start();
Toast.makeText(this, "Application Server is started", Toast.LENGTH_SHORT).show();
buttonStart.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
startService(new Intent(getBaseContext(), AppReconService.class));
}});
buttonStop.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
stopService(new Intent(getBaseContext(), AppReconService.class));
}});
}
public String[] getInstalledApplications()
{
String[] appname =new String[10];
Intent mainIntent = new Intent(Intent.ACTION_MAIN,null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
PackageManager manager = getPackageManager();
List<ResolveInfo> pkgAppsList = manager.queryIntentActivities(mainIntent, 0);
appname = new String[pkgAppsList.size()];
for(int i=0;i<pkgAppsList.size();i++)
{
appname[i]=pkgAppsList.get(i).activityInfo.packageName;
}
return appname;
}
}
the server side code
public class SecurityModuleServer implements Observer,Runnable
{
private int numberOfConnectedClient;
private Thread serverThread;
private ServerSocket serverSocket;
private volatile boolean isServerRunning;
public SecurityModuleServer(final int port)
{
numberOfConnectedClient = 0;
try
{
serverSocket = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run()
{
System.out.println("SecurityModuleServer>> server thread started."); //$NON-NLS-1$
while(isServerRunning)
{
numberOfConnectedClient++;
try
{
SecurityModuleClientThread client = new SecurityModuleClientThread(serverSocket.accept(), numberOfConnectedClient);
client.addObserver(this);
client.start();
}
catch (IOException e)
{
e.printStackTrace();
}
}
System.out.println("SecurityModuleServer>> server thread stopped."); //$NON-NLS-1$
}
synchronized public void start()
{
serverThread = new Thread(this);
isServerRunning = true;
serverThread.start();
}
synchronized public void stop()
{
isServerRunning = false;
}
public boolean isRunning()
{
return isServerRunning;
}
public static void main(String[] args)
{
SecurityModuleServer server = new SecurityModuleServer(5903);
server.start();
}
public void update(Observable o, Object arg)
{
numberOfConnectedClient--;
}
}
the client side code
public SecurityModuleClientThread(Socket socket, int numberOfClient)
{
clientSocket = socket;
numberOfConnectedClient = numberOfClient;
try
{
printOut = new PrintStream(clientSocket.getOutputStream());
readerIn = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
clientThread = new Thread(this);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void run()
{
Looper.prepare();
String input = ""; //$NON-NLS-1$
System.out.println("SecurityModuleClientThread>> thread started for client."); //$NON-NLS-1$
if (numberOfConnectedClient <= MAX_ALLOWED_CLIENTS)
{
printOut.println(CMD+Answer_Open_Connection+SEPARATOR+M002);
while(isClientRunning)
{
try
{
input = readerIn.readLine();
System.out.println("Message received>> "+input); //$NON-NLS-1$
parseInputMessage(input);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
else
{
printOut.println(CMD+Error+SEPARATOR+M003);
stop();
}
System.out.println("SecurityModuleClientThread>> thread stopped for client."); //$NON-NLS-1$
}
private void parseInputMessage(final String input)
{
if (input.equalsIgnoreCase(CMD+Request_Close_Connection))
{
printOut.println(CMD+Answer_Close_Connection+SEPARATOR+M007);
stop();
}
else
{
String messages[] = input.split(SEPARATOR);
// Parse the command
switch(parseCommand(messages[0]))
{
case Request_Start_Application:
if(parseApplicationName(input) != null)
{
if(startAndroidApplication(parseApplicationName(input)))
{
// TODO
printOut.println(CMD+Answer_Start_Application);
startAndroidApplication(parseApplicationName(input));
}
else
{
printOut.println(CMD+Error+SEPARATOR+M004);
}
}
else
{
printOut.println(CMD+Error+SEPARATOR+M004);
}
break;
case Request_Stop_Application:
if(parseApplicationName(input) != null)
{
if (stopAndroidApplication(parseApplicationName(input)))
{
// TODO
printOut.println(CMD+Answer_Stop_Application);
}
else
{
printOut.println(CMD+Error+SEPARATOR+M004);
}
}
else
{
printOut.println(CMD+Error+SEPARATOR+M004);
}
break;
case Request_Application_Installed:
String[] appnames = new String[provideInstalledApplication().length];
appnames = provideInstalledApplication();
for(int i=0;i<appnames.length;i++)
{
printOut.println(appnames[i]);
}
break;
case Request_Application_Running:
//TODO
break;
default:
printOut.println(CMD+Error+SEPARATOR+M008);
break;
}
}
}
private int parseCommand(String cmd)
{
if (cmd.length() == 6)
{
return Integer.parseInt(cmd.substring(3, 6));
}
else
{
return 0;
}
}
private String parseApplicationName(String message)
{
if (message.length() > 6)
{
// TODO
return message.substring(6, message.length());
}
else
{
return null;
}
}
public synchronized void start()
{
isClientRunning = true;
clientThread = new Thread(this);
clientThread.start();
}
public synchronized void stop()
{
printOut.close();
try
{
readerIn.close();
clientSocket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
isClientRunning = false;
setChanged();
notifyObservers();
}
}
public boolean isRunning()
{
return isClientRunning;
}
public String[] provideInstalledApplication()
{
String[] appnames = null;
ApplicationRecognition apprecon = new ApplicationRecognition();
appnames=new String[apprecon.getInstalledApplications().length];
appnames = apprecon.getInstalledApplications();
return appnames;
}
public String[] provideRunningApplication()
{
// TODO Auto-generated method stub
return null;
}
public boolean startAndroidApplication(String applicationName)
{
// TODO Auto-generated method stub
ApplicationRecognition apprecon = new ApplicationRecognition();
apprecon.startApplication(applicationName);
return false;
}
public boolean stopAndroidApplication(String applicationName)
{
// TODO Auto-generated method stub
return false;
}
}
The main part that is giving me trouble is in ApplicationRecognition class under method getInstalledApplications() in getPackageManager is null.
This method is called from the client side SecurityModuleClientThread class, provideInstalledApplication method.
Can someone please tell me where am I going wrong.

Categories

Resources