diff --git a/src/android/org/linphone/BandwidthManager.java b/src/android/org/linphone/BandwidthManager.java index adf72e950..301fe0b67 100644 --- a/src/android/org/linphone/BandwidthManager.java +++ b/src/android/org/linphone/BandwidthManager.java @@ -24,42 +24,42 @@ import org.linphone.core.Core; public class BandwidthManager { - public static final int HIGH_RESOLUTION = 0; - public static final int LOW_RESOLUTION = 1; - public static final int LOW_BANDWIDTH = 2; + public static final int HIGH_RESOLUTION = 0; + public static final int LOW_RESOLUTION = 1; + public static final int LOW_BANDWIDTH = 2; - private static BandwidthManager instance; + private static BandwidthManager instance; - private int currentProfile = HIGH_RESOLUTION; + private int currentProfile = HIGH_RESOLUTION; - public static final synchronized BandwidthManager getInstance() { - if (instance == null) instance = new BandwidthManager(); - return instance; - } + public static final synchronized BandwidthManager getInstance() { + if (instance == null) instance = new BandwidthManager(); + return instance; + } - private BandwidthManager() { - // FIXME register a listener on NetworkManager to get notified of network state - // FIXME register a listener on Preference to get notified of change in video enable value + private BandwidthManager() { + // FIXME register a listener on NetworkManager to get notified of network state + // FIXME register a listener on Preference to get notified of change in video enable value - // FIXME initially get those values - } + // FIXME initially get those values + } - public void updateWithProfileSettings(Core lc, CallParams callParams) { - if (callParams != null) { // in call - // Update video parm if - if (!isVideoPossible()) { // NO VIDEO - callParams.enableVideo(false); - callParams.setAudioBandwidthLimit(40); - } else { - callParams.enableVideo(true); - callParams.setAudioBandwidthLimit(0); // disable limitation - } - } - } + public void updateWithProfileSettings(Core lc, CallParams callParams) { + if (callParams != null) { // in call + // Update video parm if + if (!isVideoPossible()) { // NO VIDEO + callParams.enableVideo(false); + callParams.setAudioBandwidthLimit(40); + } else { + callParams.enableVideo(true); + callParams.setAudioBandwidthLimit(0); // disable limitation + } + } + } - public boolean isVideoPossible() { - return currentProfile != LOW_BANDWIDTH; - } + public boolean isVideoPossible() { + return currentProfile != LOW_BANDWIDTH; + } } diff --git a/src/android/org/linphone/LinphoneManager.java b/src/android/org/linphone/LinphoneManager.java index 8eed9e79e..20bb27ea4 100644 --- a/src/android/org/linphone/LinphoneManager.java +++ b/src/android/org/linphone/LinphoneManager.java @@ -53,17 +53,18 @@ import android.view.View; import android.widget.Button; import android.widget.Toast; -import org.linphone.call.CallActivity; -import org.linphone.call.CallIncomingActivity; import org.linphone.activities.LinphoneActivity; import org.linphone.assistant.AssistantActivity; +import org.linphone.call.CallActivity; +import org.linphone.call.CallIncomingActivity; import org.linphone.call.CallManager; import org.linphone.contacts.ContactsManager; import org.linphone.contacts.LinphoneContact; -import org.linphone.core.AccountCreatorListener; import org.linphone.core.AccountCreator; +import org.linphone.core.AccountCreatorListener; import org.linphone.core.Address; import org.linphone.core.AuthInfo; +import org.linphone.core.AuthMethod; import org.linphone.core.Call; import org.linphone.core.Call.State; import org.linphone.core.CallLog; @@ -72,39 +73,38 @@ import org.linphone.core.CallStats; import org.linphone.core.ChatMessage; import org.linphone.core.ChatRoom; import org.linphone.core.ChatRoomCapabilities; +import org.linphone.core.ConfiguringState; import org.linphone.core.Content; import org.linphone.core.Core; -import org.linphone.core.AuthMethod; -import org.linphone.core.EcCalibratorStatus; -import org.linphone.core.GlobalState; import org.linphone.core.Core.LogCollectionUploadState; -import org.linphone.core.RegistrationState; -import org.linphone.core.ConfiguringState; import org.linphone.core.CoreException; -import org.linphone.core.Factory; import org.linphone.core.CoreListener; +import org.linphone.core.EcCalibratorStatus; import org.linphone.core.Event; +import org.linphone.core.Factory; import org.linphone.core.Friend; import org.linphone.core.FriendList; +import org.linphone.core.GlobalState; import org.linphone.core.InfoMessage; import org.linphone.core.PresenceActivity; -import org.linphone.core.ProxyConfig; -import org.linphone.core.PublishState; -import org.linphone.core.Tunnel; -import org.linphone.core.tools.OpenH264DownloadHelperListener; import org.linphone.core.PresenceBasicStatus; import org.linphone.core.PresenceModel; +import org.linphone.core.ProxyConfig; +import org.linphone.core.PublishState; import org.linphone.core.Reason; +import org.linphone.core.RegistrationState; import org.linphone.core.SubscriptionState; +import org.linphone.core.Tunnel; import org.linphone.core.TunnelConfig; import org.linphone.core.VersionUpdateCheckResult; +import org.linphone.core.tools.H264Helper; +import org.linphone.core.tools.OpenH264DownloadHelper; +import org.linphone.core.tools.OpenH264DownloadHelperListener; import org.linphone.mediastream.Log; import org.linphone.mediastream.Version; import org.linphone.mediastream.video.capture.hwconf.AndroidCameraConfiguration; import org.linphone.mediastream.video.capture.hwconf.AndroidCameraConfiguration.AndroidCamera; import org.linphone.mediastream.video.capture.hwconf.Hacks; -import org.linphone.core.tools.H264Helper; -import org.linphone.core.tools.OpenH264DownloadHelper; import org.linphone.receivers.BluetoothManager; import org.linphone.receivers.DozeReceiver; import org.linphone.receivers.HookReceiver; @@ -129,7 +129,6 @@ import static android.media.AudioManager.STREAM_RING; import static android.media.AudioManager.STREAM_VOICE_CALL; /** - * * Manager of the low level LibLinphone stuff.
* Including: - * + *

* Add Service Listener to react to Linphone state changes. - * */ public class LinphoneManager implements CoreListener, SensorEventListener, AccountCreatorListener { - private static LinphoneManager instance; - private Context mServiceContext; - private AudioManager mAudioManager; - private PowerManager mPowerManager; - private Resources mR; - private LinphonePreferences mPrefs; - private Core mLc; - private OpenH264DownloadHelper mCodecDownloader; - private OpenH264DownloadHelperListener mCodecListener; - private String basePath; - private static boolean sExited; - private boolean mAudioFocused; - private boolean echoTesterIsRunning; - private boolean dozeModeEnabled; - private boolean callGsmON; - private int mLastNetworkType=-1; - private ConnectivityManager mConnectivityManager; - private BroadcastReceiver mKeepAliveReceiver; - private BroadcastReceiver mDozeReceiver; - private BroadcastReceiver mHookReceiver; - private BroadcastReceiver mCallReceiver; - private BroadcastReceiver mNetworkReceiver; - private IntentFilter mKeepAliveIntentFilter; - private IntentFilter mDozeIntentFilter; - private IntentFilter mHookIntentFilter; - private IntentFilter mCallIntentFilter; - private IntentFilter mNetworkIntentFilter; - private Handler mHandler = new Handler(); - private WakeLock mProximityWakelock; - private AccountCreator accountCreator; - private SensorManager mSensorManager; - private Sensor mProximity; - private boolean mProximitySensingEnabled; - private boolean handsetON = false; - private Address mCurrentChatRoomAddress; + private static LinphoneManager instance; + private Context mServiceContext; + private AudioManager mAudioManager; + private PowerManager mPowerManager; + private Resources mR; + private LinphonePreferences mPrefs; + private Core mLc; + private OpenH264DownloadHelper mCodecDownloader; + private OpenH264DownloadHelperListener mCodecListener; + private String basePath; + private static boolean sExited; + private boolean mAudioFocused; + private boolean echoTesterIsRunning; + private boolean dozeModeEnabled; + private boolean callGsmON; + private int mLastNetworkType = -1; + private ConnectivityManager mConnectivityManager; + private BroadcastReceiver mKeepAliveReceiver; + private BroadcastReceiver mDozeReceiver; + private BroadcastReceiver mHookReceiver; + private BroadcastReceiver mCallReceiver; + private BroadcastReceiver mNetworkReceiver; + private IntentFilter mKeepAliveIntentFilter; + private IntentFilter mDozeIntentFilter; + private IntentFilter mHookIntentFilter; + private IntentFilter mCallIntentFilter; + private IntentFilter mNetworkIntentFilter; + private Handler mHandler = new Handler(); + private WakeLock mProximityWakelock; + private AccountCreator accountCreator; + private SensorManager mSensorManager; + private Sensor mProximity; + private boolean mProximitySensingEnabled; + private boolean handsetON = false; + private Address mCurrentChatRoomAddress; - public String wizardLoginViewDomain = null; + public String wizardLoginViewDomain = null; - protected LinphoneManager(final Context c) { - mUnreadChatsPerRoom = new HashMap(); - sExited = false; - echoTesterIsRunning = false; - mServiceContext = c; - basePath = c.getFilesDir().getAbsolutePath(); - mLPConfigXsd = basePath + "/lpconfig.xsd"; - mLinphoneFactoryConfigFile = basePath + "/linphonerc"; - mConfigFile = basePath + "/.linphonerc"; - mDynamicConfigFile = basePath + "/assistant_create.rc"; - mChatDatabaseFile = basePath + "/linphone-history.db"; - mCallLogDatabaseFile = basePath + "/linphone-log-history.db"; - mFriendsDatabaseFile = basePath + "/linphone-friends.db"; - mRingSoundFile = basePath + "/ringtone.mkv"; + protected LinphoneManager(final Context c) { + mUnreadChatsPerRoom = new HashMap(); + sExited = false; + echoTesterIsRunning = false; + mServiceContext = c; + basePath = c.getFilesDir().getAbsolutePath(); + mLPConfigXsd = basePath + "/lpconfig.xsd"; + mLinphoneFactoryConfigFile = basePath + "/linphonerc"; + mConfigFile = basePath + "/.linphonerc"; + mDynamicConfigFile = basePath + "/assistant_create.rc"; + mChatDatabaseFile = basePath + "/linphone-history.db"; + mCallLogDatabaseFile = basePath + "/linphone-log-history.db"; + mFriendsDatabaseFile = basePath + "/linphone-friends.db"; + mRingSoundFile = basePath + "/ringtone.mkv"; - mPrefs = LinphonePreferences.instance(); - mAudioManager = ((AudioManager) c.getSystemService(Context.AUDIO_SERVICE)); - mVibrator = (Vibrator) c.getSystemService(Context.VIBRATOR_SERVICE); - mPowerManager = (PowerManager) c.getSystemService(Context.POWER_SERVICE); - mConnectivityManager = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE); - mSensorManager = (SensorManager) c.getSystemService(Context.SENSOR_SERVICE); - mProximity = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY); - mR = c.getResources(); - } + mPrefs = LinphonePreferences.instance(); + mAudioManager = ((AudioManager) c.getSystemService(Context.AUDIO_SERVICE)); + mVibrator = (Vibrator) c.getSystemService(Context.VIBRATOR_SERVICE); + mPowerManager = (PowerManager) c.getSystemService(Context.POWER_SERVICE); + mConnectivityManager = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE); + mSensorManager = (SensorManager) c.getSystemService(Context.SENSOR_SERVICE); + mProximity = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY); + mR = c.getResources(); + } - private static final int LINPHONE_VOLUME_STREAM = STREAM_VOICE_CALL; - private static final int dbStep = 4; - /** Called when the activity is first created. */ - private final String mLPConfigXsd; - private final String mLinphoneFactoryConfigFile; - private final String mDynamicConfigFile; - public final String mConfigFile; - private final String mChatDatabaseFile; - private final String mRingSoundFile; - private final String mCallLogDatabaseFile; - private final String mFriendsDatabaseFile; - private Timer mTimer; - private Map mUnreadChatsPerRoom; + private static final int LINPHONE_VOLUME_STREAM = STREAM_VOICE_CALL; + private static final int dbStep = 4; + /** + * Called when the activity is first created. + */ + private final String mLPConfigXsd; + private final String mLinphoneFactoryConfigFile; + private final String mDynamicConfigFile; + public final String mConfigFile; + private final String mChatDatabaseFile; + private final String mRingSoundFile; + private final String mCallLogDatabaseFile; + private final String mFriendsDatabaseFile; + private Timer mTimer; + private Map mUnreadChatsPerRoom; - private void routeAudioToSpeakerHelper(boolean speakerOn) { - Log.w("Routing audio to " + (speakerOn ? "speaker" : "earpiece") + ", disabling bluetooth audio route"); - BluetoothManager.getInstance().disableBluetoothSCO(); + private void routeAudioToSpeakerHelper(boolean speakerOn) { + Log.w("Routing audio to " + (speakerOn ? "speaker" : "earpiece") + ", disabling bluetooth audio route"); + BluetoothManager.getInstance().disableBluetoothSCO(); - enableSpeaker(speakerOn); - } + enableSpeaker(speakerOn); + } - public boolean isSpeakerEnabled() { - return mAudioManager != null && mAudioManager.isSpeakerphoneOn(); - } + public boolean isSpeakerEnabled() { + return mAudioManager != null && mAudioManager.isSpeakerphoneOn(); + } - public void enableSpeaker(boolean enable) { - mAudioManager.setSpeakerphoneOn(enable); - } + public void enableSpeaker(boolean enable) { + mAudioManager.setSpeakerphoneOn(enable); + } - public void initOpenH264DownloadHelper() { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { - Log.i("Android >= 5.1 we disable the download of OpenH264"); - OpenH264DownloadHelper.setOpenH264DownloadEnabled(false); - return; - } + public void initOpenH264DownloadHelper() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { + Log.i("Android >= 5.1 we disable the download of OpenH264"); + OpenH264DownloadHelper.setOpenH264DownloadEnabled(false); + return; + } - mCodecDownloader = Factory.instance().createOpenH264DownloadHelper(getContext()); - mCodecListener = new OpenH264DownloadHelperListener() { - ProgressDialog progress; - int ctxt = 0; - int box = 1; + mCodecDownloader = Factory.instance().createOpenH264DownloadHelper(getContext()); + mCodecListener = new OpenH264DownloadHelperListener() { + ProgressDialog progress; + int ctxt = 0; + int box = 1; - @Override - public void OnProgress(final int current, final int max) { - mHandler.post(new Runnable() { - @Override - public void run() { - OpenH264DownloadHelper ohcodec = LinphoneManager.getInstance().getOpenH264DownloadHelper(); - if (progress == null) { - progress = new ProgressDialog((Context) ohcodec.getUserData(ctxt)); - progress.setCanceledOnTouchOutside(false); - progress.setCancelable(false); - progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); - } else if (current <= max) { - progress.setMessage(getString(R.string.assistant_openh264_downloading)); - progress.setMax(max); - progress.setProgress(current); - progress.show(); - } else { - progress.dismiss(); - progress = null; - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { - LinphoneManager.getLc().reloadMsPlugins(AssistantActivity.instance().getApplicationInfo().nativeLibraryDir); - AssistantActivity.instance().endDownloadCodec(); - } else { - // We need to restart due to bad android linker - AssistantActivity.instance().restartApplication(); - } - } - } - }); - } + @Override + public void OnProgress(final int current, final int max) { + mHandler.post(new Runnable() { + @Override + public void run() { + OpenH264DownloadHelper ohcodec = LinphoneManager.getInstance().getOpenH264DownloadHelper(); + if (progress == null) { + progress = new ProgressDialog((Context) ohcodec.getUserData(ctxt)); + progress.setCanceledOnTouchOutside(false); + progress.setCancelable(false); + progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); + } else if (current <= max) { + progress.setMessage(getString(R.string.assistant_openh264_downloading)); + progress.setMax(max); + progress.setProgress(current); + progress.show(); + } else { + progress.dismiss(); + progress = null; + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { + LinphoneManager.getLc().reloadMsPlugins(AssistantActivity.instance().getApplicationInfo().nativeLibraryDir); + AssistantActivity.instance().endDownloadCodec(); + } else { + // We need to restart due to bad android linker + AssistantActivity.instance().restartApplication(); + } + } + } + }); + } - @Override - public void OnError(final String error) { - mHandler.post(new Runnable() { - @Override - public void run() { - if (progress != null) progress.dismiss(); - AlertDialog.Builder builder = new AlertDialog.Builder((Context) LinphoneManager.getInstance().getOpenH264DownloadHelper().getUserData(ctxt)); - builder.setMessage(getString(R.string.assistant_openh264_error)); - builder.setCancelable(false); - builder.setNeutralButton(getString(R.string.ok), null); - builder.show(); - } - }); - } - }; - mCodecDownloader.setOpenH264HelperListener(mCodecListener); - } + @Override + public void OnError(final String error) { + mHandler.post(new Runnable() { + @Override + public void run() { + if (progress != null) progress.dismiss(); + AlertDialog.Builder builder = new AlertDialog.Builder((Context) LinphoneManager.getInstance().getOpenH264DownloadHelper().getUserData(ctxt)); + builder.setMessage(getString(R.string.assistant_openh264_error)); + builder.setCancelable(false); + builder.setNeutralButton(getString(R.string.ok), null); + builder.show(); + } + }); + } + }; + mCodecDownloader.setOpenH264HelperListener(mCodecListener); + } - public OpenH264DownloadHelperListener getOpenH264HelperListener() { - return mCodecListener; - } + public OpenH264DownloadHelperListener getOpenH264HelperListener() { + return mCodecListener; + } - public OpenH264DownloadHelper getOpenH264DownloadHelper(){ - return mCodecDownloader; - } + public OpenH264DownloadHelper getOpenH264DownloadHelper() { + return mCodecDownloader; + } - public void routeAudioToSpeaker() { - routeAudioToSpeakerHelper(true); - } + public void routeAudioToSpeaker() { + routeAudioToSpeakerHelper(true); + } - public void routeAudioToReceiver() { - routeAudioToSpeakerHelper(false); - } + public void routeAudioToReceiver() { + routeAudioToSpeakerHelper(false); + } - public synchronized static final LinphoneManager createAndStart(Context c) { - if (instance != null) - throw new RuntimeException("Linphone Manager is already initialized"); + public synchronized static final LinphoneManager createAndStart(Context c) { + if (instance != null) + throw new RuntimeException("Linphone Manager is already initialized"); - instance = new LinphoneManager(c); - instance.startLibLinphone(c); - instance.initOpenH264DownloadHelper(); + instance = new LinphoneManager(c); + instance.startLibLinphone(c); + instance.initOpenH264DownloadHelper(); - // H264 codec Management - set to auto mode -> MediaCodec >= android 5.0 >= OpenH264 - H264Helper.setH264Mode(H264Helper.MODE_AUTO, getLc()); + // H264 codec Management - set to auto mode -> MediaCodec >= android 5.0 >= OpenH264 + H264Helper.setH264Mode(H264Helper.MODE_AUTO, getLc()); - return instance; - } + return instance; + } - private boolean isPresenceModelActivitySet() { - Core lc = getLcIfManagerNotDestroyedOrNull(); - if (isInstanciated() && lc != null) { - return lc.getPresenceModel() != null && lc.getPresenceModel().getActivity() != null; - } - return false; - } + private boolean isPresenceModelActivitySet() { + Core lc = getLcIfManagerNotDestroyedOrNull(); + if (isInstanciated() && lc != null) { + return lc.getPresenceModel() != null && lc.getPresenceModel().getActivity() != null; + } + return false; + } - public void changeStatusToOnline() { - Core lc = getLcIfManagerNotDestroyedOrNull(); - if (lc == null) return; - PresenceModel model = lc.createPresenceModel(); - model.setBasicStatus(PresenceBasicStatus.Open); - lc.setPresenceModel(model); + public void changeStatusToOnline() { + Core lc = getLcIfManagerNotDestroyedOrNull(); + if (lc == null) return; + PresenceModel model = lc.createPresenceModel(); + model.setBasicStatus(PresenceBasicStatus.Open); + lc.setPresenceModel(model); /* if (isInstanciated() && lc != null && isPresenceModelActivitySet() && lc.getPresenceModel().getActivity().getType() != PresenceActivity.Type.TV) { lc.getPresenceModel().getActivity().setType(PresenceActivity.Type.TV); @@ -350,939 +350,946 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou lc.setPresenceModel(model); } */ - } + } - public void changeStatusToOnThePhone() { - Core lc = getLcIfManagerNotDestroyedOrNull(); - if (lc == null) return; + public void changeStatusToOnThePhone() { + Core lc = getLcIfManagerNotDestroyedOrNull(); + if (lc == null) return; - if (isInstanciated() && isPresenceModelActivitySet() && lc.getPresenceModel().getActivity().getType() != PresenceActivity.Type.OnThePhone) { - lc.getPresenceModel().getActivity().setType(PresenceActivity.Type.OnThePhone); - } else if (isInstanciated() && !isPresenceModelActivitySet()) { - PresenceModel model = lc.createPresenceModelWithActivity(PresenceActivity.Type.OnThePhone, null); - lc.setPresenceModel(model); - } - } + if (isInstanciated() && isPresenceModelActivitySet() && lc.getPresenceModel().getActivity().getType() != PresenceActivity.Type.OnThePhone) { + lc.getPresenceModel().getActivity().setType(PresenceActivity.Type.OnThePhone); + } else if (isInstanciated() && !isPresenceModelActivitySet()) { + PresenceModel model = lc.createPresenceModelWithActivity(PresenceActivity.Type.OnThePhone, null); + lc.setPresenceModel(model); + } + } - public void changeStatusToOffline() { - Core lc = getLcIfManagerNotDestroyedOrNull(); - if (isInstanciated() && lc != null) { - PresenceModel model = lc.getPresenceModel(); - model.setBasicStatus(PresenceBasicStatus.Closed); - lc.setPresenceModel(model); - } - } + public void changeStatusToOffline() { + Core lc = getLcIfManagerNotDestroyedOrNull(); + if (isInstanciated() && lc != null) { + PresenceModel model = lc.getPresenceModel(); + model.setBasicStatus(PresenceBasicStatus.Closed); + lc.setPresenceModel(model); + } + } - public void subscribeFriendList(boolean enabled){ - Core lc = getLcIfManagerNotDestroyedOrNull(); - if(lc != null && lc.getFriendsLists() != null && lc.getFriendsLists().length > 0) { - FriendList mFriendList = (lc.getFriendsLists())[0]; - Log.i("Presence list subscription is " + (enabled ? "enabled" : "disabled")); - mFriendList.enableSubscriptions(enabled); - } - } + public void subscribeFriendList(boolean enabled) { + Core lc = getLcIfManagerNotDestroyedOrNull(); + if (lc != null && lc.getFriendsLists() != null && lc.getFriendsLists().length > 0) { + FriendList mFriendList = (lc.getFriendsLists())[0]; + Log.i("Presence list subscription is " + (enabled ? "enabled" : "disabled")); + mFriendList.enableSubscriptions(enabled); + } + } - public static synchronized final LinphoneManager getInstance() { - if (instance != null) return instance; + public static synchronized final LinphoneManager getInstance() { + if (instance != null) return instance; - if (sExited) { - throw new RuntimeException("Linphone Manager was already destroyed. " - + "Better use getLcIfManagerNotDestroyedOrNull and check returned value"); - } + if (sExited) { + throw new RuntimeException("Linphone Manager was already destroyed. " + + "Better use getLcIfManagerNotDestroyedOrNull and check returned value"); + } - throw new RuntimeException("Linphone Manager should be created before accessed"); - } + throw new RuntimeException("Linphone Manager should be created before accessed"); + } - public static synchronized final Core getLc() { - return getInstance().mLc; - } + public static synchronized final Core getLc() { + return getInstance().mLc; + } - public String getLPConfigXsdPath() { - return mLPConfigXsd; - } + public String getLPConfigXsdPath() { + return mLPConfigXsd; + } - public void newOutgoingCall(AddressType address) { - String to = address.getText().toString(); - newOutgoingCall(to, address.getDisplayedName()); - } + public void newOutgoingCall(AddressType address) { + String to = address.getText().toString(); + newOutgoingCall(to, address.getDisplayedName()); + } - public void newOutgoingCall(String to, String displayName) { + public void newOutgoingCall(String to, String displayName) { // if (mLc.inCall()) { // listenerDispatcher.tryingNewOutgoingCallButAlreadyInCall(); // return; // } - if (to == null) return; + if (to == null) return; - // If to is only a username, try to find the contact to get an alias if existing - if (!to.startsWith("sip:") || !to.contains("@")) { - LinphoneContact contact = ContactsManager.getInstance().findContactFromPhoneNumber(to); - if (contact != null) { - String alias = contact.getPresenceModelForUriOrTel(to); - if (alias != null) { - to = alias; - } - } - } + // If to is only a username, try to find the contact to get an alias if existing + if (!to.startsWith("sip:") || !to.contains("@")) { + LinphoneContact contact = ContactsManager.getInstance().findContactFromPhoneNumber(to); + if (contact != null) { + String alias = contact.getPresenceModelForUriOrTel(to); + if (alias != null) { + to = alias; + } + } + } - Address lAddress; - lAddress = mLc.interpretUrl(to); // InterpretUrl does normalizePhoneNumber - if (lAddress == null) { - Log.e("Couldn't convert to String to Address : " + to); - return; - } + Address lAddress; + lAddress = mLc.interpretUrl(to); // InterpretUrl does normalizePhoneNumber + if (lAddress == null) { + Log.e("Couldn't convert to String to Address : " + to); + return; + } - ProxyConfig lpc = mLc.getDefaultProxyConfig(); - if (mR.getBoolean(R.bool.forbid_self_call) && lpc != null && lAddress.asStringUriOnly().equals(lpc.getIdentityAddress())) { - return; - } - lAddress.setDisplayName(displayName); + ProxyConfig lpc = mLc.getDefaultProxyConfig(); + if (mR.getBoolean(R.bool.forbid_self_call) && lpc != null && lAddress.asStringUriOnly().equals(lpc.getIdentityAddress())) { + return; + } + lAddress.setDisplayName(displayName); - boolean isLowBandwidthConnection = !LinphoneUtils.isHighBandwidthConnection(LinphoneService.instance().getApplicationContext()); + boolean isLowBandwidthConnection = !LinphoneUtils.isHighBandwidthConnection(LinphoneService.instance().getApplicationContext()); - if (mLc.isNetworkReachable()) { - try { - if (Version.isVideoCapable()) { - boolean prefVideoEnable = mPrefs.isVideoEnabled(); - boolean prefInitiateWithVideo = mPrefs.shouldInitiateVideoCall(); - CallManager.getInstance().inviteAddress(lAddress, prefVideoEnable && prefInitiateWithVideo, isLowBandwidthConnection); - } else { - CallManager.getInstance().inviteAddress(lAddress, false, isLowBandwidthConnection); - } + if (mLc.isNetworkReachable()) { + try { + if (Version.isVideoCapable()) { + boolean prefVideoEnable = mPrefs.isVideoEnabled(); + boolean prefInitiateWithVideo = mPrefs.shouldInitiateVideoCall(); + CallManager.getInstance().inviteAddress(lAddress, prefVideoEnable && prefInitiateWithVideo, isLowBandwidthConnection); + } else { + CallManager.getInstance().inviteAddress(lAddress, false, isLowBandwidthConnection); + } - } catch (CoreException e) { - return; - } - } else if (LinphoneActivity.isInstanciated()) { - LinphoneActivity.instance().displayCustomToast(getString(R.string.error_network_unreachable), Toast.LENGTH_LONG); - } else { - Log.e("Error: " + getString(R.string.error_network_unreachable)); - } - } + } catch (CoreException e) { + return; + } + } else if (LinphoneActivity.isInstanciated()) { + LinphoneActivity.instance().displayCustomToast(getString(R.string.error_network_unreachable), Toast.LENGTH_LONG); + } else { + Log.e("Error: " + getString(R.string.error_network_unreachable)); + } + } - private void resetCameraFromPreferences() { - boolean useFrontCam = mPrefs.useFrontCam(); - int camId = 0; - AndroidCamera[] cameras = AndroidCameraConfiguration.retrieveCameras(); - for (AndroidCamera androidCamera : cameras) { - if (androidCamera.frontFacing == useFrontCam) - camId = androidCamera.id; - } - String[] devices = getLc().getVideoDevicesList(); - String newDevice = devices[camId]; - LinphoneManager.getLc().setVideoDevice(newDevice); - } + private void resetCameraFromPreferences() { + boolean useFrontCam = mPrefs.useFrontCam(); + int camId = 0; + AndroidCamera[] cameras = AndroidCameraConfiguration.retrieveCameras(); + for (AndroidCamera androidCamera : cameras) { + if (androidCamera.frontFacing == useFrontCam) + camId = androidCamera.id; + } + String[] devices = getLc().getVideoDevicesList(); + String newDevice = devices[camId]; + LinphoneManager.getLc().setVideoDevice(newDevice); + } - public interface AddressType { - void setText(CharSequence s); - CharSequence getText(); - void setDisplayedName(String s); - String getDisplayedName(); - } + public interface AddressType { + void setText(CharSequence s); - public void enableCamera(Call call, boolean enable) { - if (call != null) { - call.enableCamera(enable); - if (mServiceContext.getResources().getBoolean(R.bool.enable_call_notification)) - LinphoneService.instance().refreshIncallIcon(mLc.getCurrentCall()); - } - } + CharSequence getText(); - public void playDtmf(ContentResolver r, char dtmf) { - try { - if (Settings.System.getInt(r, Settings.System.DTMF_TONE_WHEN_DIALING) == 0) { - // audible touch disabled: don't play on speaker, only send in outgoing stream - return; - } - } catch (SettingNotFoundException e) {} + void setDisplayedName(String s); - getLc().playDtmf(dtmf, -1); - } + String getDisplayedName(); + } - public void terminateCall() { - if (mLc.inCall()) { - mLc.terminateCall(mLc.getCurrentCall()); - } - } + public void enableCamera(Call call, boolean enable) { + if (call != null) { + call.enableCamera(enable); + if (mServiceContext.getResources().getBoolean(R.bool.enable_call_notification)) + LinphoneService.instance().refreshIncallIcon(mLc.getCurrentCall()); + } + } - public void initTunnelFromConf() { - if (!mLc.tunnelAvailable()) - return; + public void playDtmf(ContentResolver r, char dtmf) { + try { + if (Settings.System.getInt(r, Settings.System.DTMF_TONE_WHEN_DIALING) == 0) { + // audible touch disabled: don't play on speaker, only send in outgoing stream + return; + } + } catch (SettingNotFoundException e) { + } - NetworkInfo info = mConnectivityManager.getActiveNetworkInfo(); - Tunnel tunnel = mLc.getTunnel(); - tunnel.cleanServers(); - TunnelConfig config = mPrefs.getTunnelConfig(); - if (config.getHost() != null) { - tunnel.addServer(config); - manageTunnelServer(info); - } - } + getLc().playDtmf(dtmf, -1); + } - private boolean isTunnelNeeded(NetworkInfo info) { - if (info == null) { - Log.i("No connectivity: tunnel should be disabled"); - return false; - } + public void terminateCall() { + if (mLc.inCall()) { + mLc.terminateCall(mLc.getCurrentCall()); + } + } - String pref = mPrefs.getTunnelMode(); + public void initTunnelFromConf() { + if (!mLc.tunnelAvailable()) + return; - if (getString(R.string.tunnel_mode_entry_value_always).equals(pref)) { - return true; - } + NetworkInfo info = mConnectivityManager.getActiveNetworkInfo(); + Tunnel tunnel = mLc.getTunnel(); + tunnel.cleanServers(); + TunnelConfig config = mPrefs.getTunnelConfig(); + if (config.getHost() != null) { + tunnel.addServer(config); + manageTunnelServer(info); + } + } - if (info.getType() != ConnectivityManager.TYPE_WIFI - && getString(R.string.tunnel_mode_entry_value_3G_only).equals(pref)) { - Log.i("need tunnel: 'no wifi' connection"); - return true; - } + private boolean isTunnelNeeded(NetworkInfo info) { + if (info == null) { + Log.i("No connectivity: tunnel should be disabled"); + return false; + } - return false; - } + String pref = mPrefs.getTunnelMode(); - private void manageTunnelServer(NetworkInfo info) { - if (mLc == null) return; - if (!mLc.tunnelAvailable()) return; - Tunnel tunnel = mLc.getTunnel(); + if (getString(R.string.tunnel_mode_entry_value_always).equals(pref)) { + return true; + } - Log.i("Managing tunnel"); - if (isTunnelNeeded(info)) { - Log.i("Tunnel need to be activated"); - tunnel.setMode(Tunnel.Mode.Enable); - } else { - Log.i("Tunnel should not be used"); - String pref = mPrefs.getTunnelMode(); - tunnel.setMode(Tunnel.Mode.Disable); - if (getString(R.string.tunnel_mode_entry_value_auto).equals(pref)) { - tunnel.setMode(Tunnel.Mode.Auto); - } - } - } + if (info.getType() != ConnectivityManager.TYPE_WIFI + && getString(R.string.tunnel_mode_entry_value_3G_only).equals(pref)) { + Log.i("need tunnel: 'no wifi' connection"); + return true; + } - public synchronized final void destroyCore() { - sExited = true; - ContactsManagerDestroy(); - BluetoothManagerDestroy(); - try { - mTimer.cancel(); - destroyLinphoneCore(); - } - catch (RuntimeException e) { - Log.e(e); - } - finally { - try { - if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) { - mServiceContext.unregisterReceiver(mNetworkReceiver); - } - } catch (Exception e) { - Log.e(e); - } - try { - mServiceContext.unregisterReceiver(mHookReceiver); - } catch (Exception e) { - Log.e(e); - } - try { - mServiceContext.unregisterReceiver(mCallReceiver); - } catch (Exception e) { - Log.e(e); - } - try { - mServiceContext.unregisterReceiver(mKeepAliveReceiver); - } catch (Exception e) { - Log.e(e); - } - try { - dozeManager(false); - } catch (IllegalArgumentException iae) { - Log.e(iae); - }catch (Exception e) { - Log.e(e); - } - mLc = null; - } - } + return false; + } + + private void manageTunnelServer(NetworkInfo info) { + if (mLc == null) return; + if (!mLc.tunnelAvailable()) return; + Tunnel tunnel = mLc.getTunnel(); + + Log.i("Managing tunnel"); + if (isTunnelNeeded(info)) { + Log.i("Tunnel need to be activated"); + tunnel.setMode(Tunnel.Mode.Enable); + } else { + Log.i("Tunnel should not be used"); + String pref = mPrefs.getTunnelMode(); + tunnel.setMode(Tunnel.Mode.Disable); + if (getString(R.string.tunnel_mode_entry_value_auto).equals(pref)) { + tunnel.setMode(Tunnel.Mode.Auto); + } + } + } + + public synchronized final void destroyCore() { + sExited = true; + ContactsManagerDestroy(); + BluetoothManagerDestroy(); + try { + mTimer.cancel(); + destroyLinphoneCore(); + } catch (RuntimeException e) { + Log.e(e); + } finally { + try { + if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) { + mServiceContext.unregisterReceiver(mNetworkReceiver); + } + } catch (Exception e) { + Log.e(e); + } + try { + mServiceContext.unregisterReceiver(mHookReceiver); + } catch (Exception e) { + Log.e(e); + } + try { + mServiceContext.unregisterReceiver(mCallReceiver); + } catch (Exception e) { + Log.e(e); + } + try { + mServiceContext.unregisterReceiver(mKeepAliveReceiver); + } catch (Exception e) { + Log.e(e); + } + try { + dozeManager(false); + } catch (IllegalArgumentException iae) { + Log.e(iae); + } catch (Exception e) { + Log.e(e); + } + mLc = null; + } + } - public void restartCore() { - destroyCore(); - startLibLinphone(mServiceContext); - sExited = false; - } + public void restartCore() { + destroyCore(); + startLibLinphone(mServiceContext); + sExited = false; + } - private synchronized void startLibLinphone(Context c) { - try { - copyAssetsFromPackage(); - //traces alway start with traces enable to not missed first initialization - mLc = Factory.instance().createCore(mConfigFile, mLinphoneFactoryConfigFile, c); - mLc.addListener(this); - mLc.start(); - TimerTask lTask = new TimerTask() { - @Override - public void run() { - LinphoneUtils.dispatchOnUIThread(new Runnable() { - @Override - public void run() { - if (mLc != null) { - mLc.iterate(); - } - } - }); - } - }; - /*use schedule instead of scheduleAtFixedRate to avoid iterate from being call in burst after cpu wake up*/ - mTimer = new Timer("Linphone scheduler"); - mTimer.schedule(lTask, 0, 20); - } catch (Exception e) { - Log.e(e, "Cannot start linphone"); - } - } + private synchronized void startLibLinphone(Context c) { + try { + copyAssetsFromPackage(); + //traces alway start with traces enable to not missed first initialization + mLc = Factory.instance().createCore(mConfigFile, mLinphoneFactoryConfigFile, c); + mLc.addListener(this); + mLc.start(); + TimerTask lTask = new TimerTask() { + @Override + public void run() { + LinphoneUtils.dispatchOnUIThread(new Runnable() { + @Override + public void run() { + if (mLc != null) { + mLc.iterate(); + } + } + }); + } + }; + /*use schedule instead of scheduleAtFixedRate to avoid iterate from being call in burst after cpu wake up*/ + mTimer = new Timer("Linphone scheduler"); + mTimer.schedule(lTask, 0, 20); + } catch (Exception e) { + Log.e(e, "Cannot start linphone"); + } + } - private void initPushNotificationsService() { - if (getString(R.string.push_type).equals("google")) { - try { - Class GCMRegistrar = Class.forName("com.google.android.gcm.GCMRegistrar"); - GCMRegistrar.getMethod("checkDevice", Context.class).invoke(null, mServiceContext); - try { - GCMRegistrar.getMethod("checkManifest", Context.class).invoke(null, mServiceContext); - } catch (IllegalStateException e) { - Log.e("[Push Notification] No receiver found", e); - } - final String regId = (String) GCMRegistrar.getMethod("getRegistrationId", Context.class).invoke(null, mServiceContext); - String newPushSenderID = mServiceContext.getString(R.string.push_sender_id); - String currentPushSenderID = LinphonePreferences.instance().getPushNotificationRegistrationID(); - if (regId.equals("") || currentPushSenderID == null || !currentPushSenderID.equals(newPushSenderID)) { - GCMRegistrar.getMethod("register", Context.class, String[].class).invoke(null, mServiceContext, new String[]{newPushSenderID}); - Log.i("[Push Notification] Storing current sender id = " + newPushSenderID); - } else { - Log.i("[Push Notification] Already registered with id = " + regId); - LinphonePreferences.instance().setPushNotificationRegistrationID(regId); - } - } catch (java.lang.UnsupportedOperationException e) { - Log.i("[Push Notification] Not activated"); - } catch (Exception e1) { - Log.i("[Push Notification] Assuming GCM jar is not provided."); - } - }else if (getString(R.string.push_type).equals("firebase")){ - try{ - Class firebaseClass = Class.forName("com.google.firebase.iid.FirebaseInstanceId"); - Object firebaseInstance = firebaseClass.getMethod("getInstance").invoke(null); - final String refreshedToken = (String)firebaseClass.getMethod("getToken").invoke(firebaseInstance); + private void initPushNotificationsService() { + if (getString(R.string.push_type).equals("google")) { + try { + Class GCMRegistrar = Class.forName("com.google.android.gcm.GCMRegistrar"); + GCMRegistrar.getMethod("checkDevice", Context.class).invoke(null, mServiceContext); + try { + GCMRegistrar.getMethod("checkManifest", Context.class).invoke(null, mServiceContext); + } catch (IllegalStateException e) { + Log.e("[Push Notification] No receiver found", e); + } + final String regId = (String) GCMRegistrar.getMethod("getRegistrationId", Context.class).invoke(null, mServiceContext); + String newPushSenderID = mServiceContext.getString(R.string.push_sender_id); + String currentPushSenderID = LinphonePreferences.instance().getPushNotificationRegistrationID(); + if (regId.equals("") || currentPushSenderID == null || !currentPushSenderID.equals(newPushSenderID)) { + GCMRegistrar.getMethod("register", Context.class, String[].class).invoke(null, mServiceContext, new String[]{newPushSenderID}); + Log.i("[Push Notification] Storing current sender id = " + newPushSenderID); + } else { + Log.i("[Push Notification] Already registered with id = " + regId); + LinphonePreferences.instance().setPushNotificationRegistrationID(regId); + } + } catch (java.lang.UnsupportedOperationException e) { + Log.i("[Push Notification] Not activated"); + } catch (Exception e1) { + Log.i("[Push Notification] Assuming GCM jar is not provided."); + } + } else if (getString(R.string.push_type).equals("firebase")) { + try { + Class firebaseClass = Class.forName("com.google.firebase.iid.FirebaseInstanceId"); + Object firebaseInstance = firebaseClass.getMethod("getInstance").invoke(null); + final String refreshedToken = (String) firebaseClass.getMethod("getToken").invoke(firebaseInstance); - //final String refreshedToken = com.google.firebase.iid.FirebaseInstanceId.getInstance().getToken(); - if (refreshedToken != null) { - Log.i("[Push Notification] current token is: " + refreshedToken); - LinphonePreferences.instance().setPushNotificationRegistrationID(refreshedToken); - } - }catch(Exception e){ - Log.i("[Push Notification] firebase not available."); - } - } - } + //final String refreshedToken = com.google.firebase.iid.FirebaseInstanceId.getInstance().getToken(); + if (refreshedToken != null) { + Log.i("[Push Notification] current token is: " + refreshedToken); + LinphonePreferences.instance().setPushNotificationRegistrationID(refreshedToken); + } + } catch (Exception e) { + Log.i("[Push Notification] firebase not available."); + } + } + } - private synchronized void initLiblinphone(Core lc) throws CoreException { - mLc = lc; + private synchronized void initLiblinphone(Core lc) throws CoreException { + mLc = lc; - mLc.setZrtpSecretsFile(basePath + "/zrtp_secrets"); + mLc.setZrtpSecretsFile(basePath + "/zrtp_secrets"); - try { - String versionName = mServiceContext.getPackageManager().getPackageInfo(mServiceContext.getPackageName(), 0).versionName; - if (versionName == null) { - versionName = String.valueOf(mServiceContext.getPackageManager().getPackageInfo(mServiceContext.getPackageName(), 0).versionCode); - } else { - //Api to check version can't use version code - mLc.checkForUpdate(versionName); - } - mLc.setUserAgent("LinphoneAndroid", versionName); - } catch (NameNotFoundException e) { - Log.e(e, "cannot get version name"); - } + try { + String versionName = mServiceContext.getPackageManager().getPackageInfo(mServiceContext.getPackageName(), 0).versionName; + if (versionName == null) { + versionName = String.valueOf(mServiceContext.getPackageManager().getPackageInfo(mServiceContext.getPackageName(), 0).versionCode); + } else { + //Api to check version can't use version code + mLc.checkForUpdate(versionName); + } + mLc.setUserAgent("LinphoneAndroid", versionName); + } catch (NameNotFoundException e) { + Log.e(e, "cannot get version name"); + } - mLc.setChatDatabasePath(mChatDatabaseFile); - mLc.setCallLogsDatabasePath(mCallLogDatabaseFile); - mLc.setFriendsDatabasePath(mFriendsDatabaseFile); - //mLc.setCallErrorTone(Reason.NotFound, mErrorToneFile); - enableDeviceRingtone(mPrefs.isDeviceRingtoneEnabled()); + mLc.setChatDatabasePath(mChatDatabaseFile); + mLc.setCallLogsDatabasePath(mCallLogDatabaseFile); + mLc.setFriendsDatabasePath(mFriendsDatabaseFile); + //mLc.setCallErrorTone(Reason.NotFound, mErrorToneFile); + enableDeviceRingtone(mPrefs.isDeviceRingtoneEnabled()); - int availableCores = Runtime.getRuntime().availableProcessors(); - Log.w("MediaStreamer : " + availableCores + " cores detected and configured"); - //mLc.setCpuCount(availableCores); + int availableCores = Runtime.getRuntime().availableProcessors(); + Log.w("MediaStreamer : " + availableCores + " cores detected and configured"); + //mLc.setCpuCount(availableCores); - mLc.migrateLogsFromRcToDb(); + mLc.migrateLogsFromRcToDb(); - // Migrate existing linphone accounts to have conference factory uri set - for (ProxyConfig lpc : mLc.getProxyConfigList()) { - if (lpc.getConferenceFactoryUri() == null && lpc.getIdentityAddress().getDomain().equals(getString(R.string.default_domain))) { - lpc.edit(); - lpc.setConferenceFactoryUri(getString(R.string.default_conference_factory_uri)); - lpc.done(); - } - } + // Migrate existing linphone accounts to have conference factory uri set + for (ProxyConfig lpc : mLc.getProxyConfigList()) { + if (lpc.getConferenceFactoryUri() == null && lpc.getIdentityAddress().getDomain().equals(getString(R.string.default_domain))) { + lpc.edit(); + lpc.setConferenceFactoryUri(getString(R.string.default_conference_factory_uri)); + lpc.done(); + } + } - if (mServiceContext.getResources().getBoolean(R.bool.enable_push_id)) { - initPushNotificationsService(); - } + if (mServiceContext.getResources().getBoolean(R.bool.enable_push_id)) { + initPushNotificationsService(); + } /* You cannot receive this through components declared in manifests, only by explicitly registering for it with Context.registerReceiver(). This is a protected intent that can only be sent by the system. */ - mKeepAliveIntentFilter = new IntentFilter(Intent.ACTION_SCREEN_ON); - mKeepAliveIntentFilter.addAction(Intent.ACTION_SCREEN_OFF); - - mKeepAliveReceiver = new KeepAliveReceiver(); - mServiceContext.registerReceiver(mKeepAliveReceiver, mKeepAliveIntentFilter); - - mCallIntentFilter = new IntentFilter("android.intent.action.ACTION_NEW_OUTGOING_CALL"); - mCallIntentFilter.setPriority(99999999); - mCallReceiver = new OutgoingCallReceiver(); - try { - mServiceContext.registerReceiver(mCallReceiver, mCallIntentFilter); - }catch(IllegalArgumentException e){e.printStackTrace();} - mProximityWakelock = mPowerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, "manager_proximity_sensor"); - - - - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - mDozeIntentFilter = new IntentFilter(); - mDozeIntentFilter.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED); - mDozeReceiver = new DozeReceiver(); - dozeModeEnabled = ((PowerManager) mServiceContext.getSystemService(Context.POWER_SERVICE)).isDeviceIdleMode(); - mServiceContext.registerReceiver(mDozeReceiver, mDozeIntentFilter); - } - - mHookIntentFilter = new IntentFilter("com.base.module.phone.HOOKEVENT"); - mHookIntentFilter.setPriority(999); - mHookReceiver = new HookReceiver(); - mServiceContext.registerReceiver(mHookReceiver, mHookIntentFilter); - - // Since Android N we need to register the network manager - if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) { - mNetworkReceiver = new NetworkManager(); - mNetworkIntentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); - mServiceContext.registerReceiver(mNetworkReceiver, mNetworkIntentFilter); - } - - updateNetworkReachability(); - - resetCameraFromPreferences(); - - accountCreator = LinphoneManager.getLc().createAccountCreator(LinphonePreferences.instance().getXmlrpcUrl()); - accountCreator.setListener(this); - callGsmON = false; - - updateMissedChatCount(); - } - - public void setHandsetMode(Boolean on){ - if (mLc.isIncomingInvitePending() && on) { - handsetON = true; - mLc.acceptCall(mLc.getCurrentCall()); - LinphoneActivity.instance().startIncallActivity(mLc.getCurrentCall()); - } else if(on && CallActivity.isInstanciated()) { - handsetON = true; - CallActivity.instance().setSpeakerEnabled(true); - CallActivity.instance().refreshInCallActions(); - } else if (!on) { - handsetON = false; - LinphoneManager.getInstance().terminateCall(); - } - } - - public boolean isHansetModeOn(){ - return handsetON; - } - - private void copyAssetsFromPackage() throws IOException { - copyIfNotExist(R.raw.linphonerc_default, mConfigFile); - copyFromPackage(R.raw.linphonerc_factory, new File(mLinphoneFactoryConfigFile).getName()); - copyIfNotExist(R.raw.lpconfig, mLPConfigXsd); - copyFromPackage(R.raw.assistant_create, new File(mDynamicConfigFile).getName()); - } - - public void copyIfNotExist(int ressourceId, String target) throws IOException { - File lFileToCopy = new File(target); - if (!lFileToCopy.exists()) { - copyFromPackage(ressourceId,lFileToCopy.getName()); - } - } - - public void copyFromPackage(int ressourceId, String target) throws IOException{ - FileOutputStream lOutputStream = mServiceContext.openFileOutput (target, 0); - InputStream lInputStream = mR.openRawResource(ressourceId); - int readByte; - byte[] buff = new byte[8048]; - while (( readByte = lInputStream.read(buff)) != -1) { - lOutputStream.write(buff,0, readByte); - } - lOutputStream.flush(); - lOutputStream.close(); - lInputStream.close(); - } - - //public void loadConfig(){ - // try { - // copyIfNotExist(R.raw.configrc, mConfigFile); - // } catch (Exception e){ - // Log.w(e); - // } - // LinphonePreferences.instance().setRemoteProvisioningUrl("file://" + mConfigFile); - // getLc().getConfig().setInt("misc","transient_provisioning",1); - //} - - public void updateNetworkReachability() { - if (mConnectivityManager == null) return; - - boolean connected = false; - NetworkInfo networkInfo = mConnectivityManager.getActiveNetworkInfo(); - connected = networkInfo != null && networkInfo.isConnected(); - - if (networkInfo == null && Version.sdkAboveOrEqual(Version.API21_LOLLIPOP_50)) { - for (Network network : mConnectivityManager.getAllNetworks()) { - if (network != null) { - networkInfo = mConnectivityManager.getNetworkInfo(network); - if (networkInfo != null && networkInfo.isConnected()) { - connected = true; - break; - } - } - } - } - - if (networkInfo == null || !connected) { - Log.i("No connectivity: setting network unreachable"); - mLc.setNetworkReachable(false); - } else if (dozeModeEnabled) { - Log.i("Doze Mode enabled: shutting down network"); - mLc.setNetworkReachable(false); - } else if (connected){ - manageTunnelServer(networkInfo); - - boolean wifiOnly = LinphonePreferences.instance().isWifiOnlyEnabled(); - if (wifiOnly){ - if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) { - mLc.setNetworkReachable(true); - } - else { - Log.i("Wifi-only mode, setting network not reachable"); - mLc.setNetworkReachable(false); - } - } else { - int curtype=networkInfo.getType(); - - if (curtype != mLastNetworkType) { - //if kind of network has changed, we need to notify network_reachable(false) to make sure all current connections are destroyed. - //they will be re-created during setNetworkReachable(true). - Log.i("Connectivity has changed."); - mLc.setNetworkReachable(false); - } - mLc.setNetworkReachable(true); - mLastNetworkType = curtype; - } - } - - if (mLc.isNetworkReachable()) { - // When network isn't available, push informations might not be set. This should fix the issue. - LinphonePreferences prefs = LinphonePreferences.instance(); - prefs.setPushNotificationEnabled(prefs.isPushNotificationEnabled()); - } - } - - private void destroyLinphoneCore() { - if (LinphonePreferences.instance() != null) { - // We set network reachable at false before destroy LC to not send register with expires at 0 - if (LinphonePreferences.instance().isPushNotificationEnabled() - || LinphonePreferences.instance().isBackgroundModeEnabled()) { - mLc.setNetworkReachable(false); - } - } - mLc = null; - } - - public void dozeManager(boolean enable) { - if (enable) { - Log.i("[Doze Mode]: register"); - mServiceContext.registerReceiver(mDozeReceiver, mDozeIntentFilter); - dozeModeEnabled = true; - } else { - Log.i("[Doze Mode]: unregister"); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - try { - mServiceContext.unregisterReceiver(mDozeReceiver); - } catch (IllegalArgumentException e) { - e.printStackTrace(); - } - } - dozeModeEnabled = false; - } - } - - public void enableProximitySensing(boolean enable){ - if (enable){ - if (!mProximitySensingEnabled){ - mSensorManager.registerListener(this, mProximity, SensorManager.SENSOR_DELAY_NORMAL); - mProximitySensingEnabled = true; - } - } else { - if (mProximitySensingEnabled){ - mSensorManager.unregisterListener(this); - mProximitySensingEnabled = false; - // Don't forgeting to release wakelock if held - if(mProximityWakelock.isHeld()) { - mProximityWakelock.release(); - } - } - } - } - - public static Boolean isProximitySensorNearby(final SensorEvent event) { - float threshold = 4.001f; // <= 4 cm is near - - final float distanceInCm = event.values[0]; - final float maxDistance = event.sensor.getMaximumRange(); - Log.d("Proximity sensor report ["+distanceInCm+"] , for max range ["+maxDistance+"]"); - - if (maxDistance <= threshold) { - // Case binary 0/1 and short sensors - threshold = maxDistance; - } - return distanceInCm < threshold; - } - - @Override - public void onSensorChanged(SensorEvent event) { - if (event.timestamp == 0) return; - if(isProximitySensorNearby(event)){ - if(!mProximityWakelock.isHeld()) { - mProximityWakelock.acquire(); - } - } else { - if(mProximityWakelock.isHeld()) { - mProximityWakelock.release(); - } - } - } - - @Override - public void onAccuracyChanged(Sensor sensor, int accuracy) { - - } - - public static void ContactsManagerDestroy() { - if (LinphoneManager.instance != null && LinphoneManager.instance.mServiceContext != null) - LinphoneManager.instance.mServiceContext.getContentResolver().unregisterContentObserver(ContactsManager.getInstance()); - ContactsManager.getInstance().destroy(); - } - - public static void BluetoothManagerDestroy() { - BluetoothManager.getInstance().destroy(); - } - - public static synchronized void destroy() { - if (instance == null) return; - getInstance().changeStatusToOffline(); - sExited = true; - instance.destroyCore(); - } - - private String getString(int key) { - return mR.getString(key); - } - - /* Simple implementation as Android way seems very complicate: - For example: with wifi and mobile actives; when pulling mobile down: - I/Linphone( 8397): WIFI connected: setting network reachable - I/Linphone( 8397): new state [RegistrationProgress] - I/Linphone( 8397): mobile disconnected: setting network unreachable - I/Linphone( 8397): Managing tunnel - I/Linphone( 8397): WIFI connected: setting network reachable - */ - public void connectivityChanged(ConnectivityManager cm, boolean noConnectivity) { - updateNetworkReachability(); - } - - private Call ringingCall; - - private MediaPlayer mRingerPlayer; - private Vibrator mVibrator; - - public void onNewSubscriptionRequested(Core lc, Friend lf, String url) {} - public void onNotifyPresenceReceived(Core lc, Friend lf) {} - - @Override - public void onEcCalibrationAudioInit(Core lc) { - - } - - @Override - public void onDtmfReceived(Core lc, Call call, int dtmf) { - Log.d("DTMF received: " + dtmf); - } - - @Override - public void onMessageReceived(Core lc, ChatRoom cr, ChatMessage message) { - if (mServiceContext.getResources().getBoolean(R.bool.disable_chat)) { - return; - } - - if (mCurrentChatRoomAddress != null && cr.getPeerAddress().asStringUriOnly().equals(mCurrentChatRoomAddress.asStringUriOnly())) { - Log.i("Message received for currently displayed chat room, do not make a notification"); - return; - } - - if (message.getErrorInfo() != null && message.getErrorInfo().getReason() == Reason.UnsupportedContent) { - Log.w("Message received but content is unsupported, do not notify it"); - return; - } - - if (!message.hasTextContent() && message.getFileTransferInformation() == null) { - Log.w("Message has no text or file transfer information to display, ignoring it..."); - return; - } - - increaseUnreadCountForChatRoom(cr); - - Address from = message.getFromAddress(); - LinphoneContact contact = ContactsManager.getInstance().findContactFromAddress(from); - String textMessage = (message.getFileTransferInformation() != null) ? getString(R.string.content_description_incoming_file) : message.getTextContent(); - - if (!mServiceContext.getResources().getBoolean(R.bool.disable_chat_message_notification) && !message.isOutgoing()) { - if (cr.hasCapability(ChatRoomCapabilities.OneToOne.toInt())) { - if (contact != null) { - LinphoneService.instance().displayMessageNotification(cr.getPeerAddress().asStringUriOnly(), contact.getFullName(), contact.getThumbnailUri(), textMessage); - } else { - LinphoneService.instance().displayMessageNotification(cr.getPeerAddress().asStringUriOnly(), from.getUsername(), null, textMessage); - } - } else { - String subject = cr.getSubject(); - if (contact != null) { - LinphoneService.instance().displayGroupChatMessageNotification(subject, cr.getPeerAddress().asStringUriOnly(), contact.getFullName(), contact.getThumbnailUri(), textMessage); - } else { - LinphoneService.instance().displayGroupChatMessageNotification(subject, cr.getPeerAddress().asStringUriOnly(), from.getUsername(), null, textMessage); - } - } - } - } - - public void setCurrentChatRoomAddress(Address address) { - mCurrentChatRoomAddress = address; - LinphoneService.instance().setCurrentlyDisplayedChatRoom(address != null ? address.asStringUriOnly() : null); - } - - @Override - public void onEcCalibrationResult(Core lc, EcCalibratorStatus status, int delay_ms) { - ((AudioManager)getContext().getSystemService(Context.AUDIO_SERVICE)).setMode(AudioManager.MODE_NORMAL); - mAudioManager.abandonAudioFocus(null); - Log.i("Set audio mode on 'Normal'"); - } - - public void onGlobalStateChanged(final Core lc, final GlobalState state, final String message) { - Log.i("New global state [",state,"]"); - if (state == GlobalState.On){ - try { - Log.e("LinphoneManager"," onGlobalStateChanged ON"); - initLiblinphone(lc); - - }catch(IllegalArgumentException iae){ - Log.e(iae); - } catch (CoreException e) { - Log.e(e); - } - } - } - - public void onRegistrationStateChanged(final Core lc, final ProxyConfig proxy,final RegistrationState state,final String message) { - Log.i("New registration state ["+state+"]"); - if(LinphoneManager.getLc().getDefaultProxyConfig() == null){ - subscribeFriendList(false); - } - } - - public Context getContext() { - try { - if (LinphoneActivity.isInstanciated()) - return LinphoneActivity.instance(); - else if (CallActivity.isInstanciated()) - return CallActivity.instance(); - else if (CallIncomingActivity.isInstanciated()) - return CallIncomingActivity.instance(); - else if (mServiceContext != null) - return mServiceContext; - else if (LinphoneService.isReady()) - return LinphoneService.instance().getApplicationContext(); - } catch (Exception e) { - Log.e(e); - } - return null; - } - - public void setAudioManagerInCallMode() { - if (mAudioManager.getMode() == AudioManager.MODE_IN_COMMUNICATION) { - Log.w("[AudioManager] already in MODE_IN_COMMUNICATION, skipping..."); - return; - } - Log.d("[AudioManager] Mode: MODE_IN_COMMUNICATION"); - - mAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION); - } - - @SuppressLint("Wakelock") - public void onCallStateChanged(final Core lc,final Call call, final State state, final String message) { - Log.i("New call state [",state,"]"); - if (state == State.IncomingReceived && !call.equals(lc.getCurrentCall())) { - if (call.getReplacedCall()!=null){ - // attended transfer - // it will be accepted automatically. - return; - } - } - - if (state == State.IncomingReceived && getCallGsmON()) { - if (mLc != null) { - mLc.declineCall(call, Reason.Busy); - } - } else if (state == State.IncomingReceived && (LinphonePreferences.instance().isAutoAnswerEnabled()) && !getCallGsmON()) { - TimerTask lTask = new TimerTask() { - @Override - public void run() { - if (mLc != null) { - if (mLc.getCallsNb() > 0) { - mLc.acceptCall(call); - if (LinphoneManager.getInstance() != null) { - LinphoneManager.getInstance().routeAudioToReceiver(); - if (LinphoneActivity.instance() != null) - LinphoneActivity.instance().startIncallActivity(call); - } - } - } - } - }; - mTimer = new Timer("Auto answer"); - mTimer.schedule(lTask, mPrefs.getAutoAnswerTime()); - } else if (state == State.IncomingReceived || (state == State.IncomingEarlyMedia && mR.getBoolean(R.bool.allow_ringing_while_early_media))) { - // Brighten screen for at least 10 seconds - if (mLc.getCallsNb() == 1) { - requestAudioFocus(STREAM_RING); - - ringingCall = call; - startRinging(); - // otherwise there is the beep - } - } else if (call == ringingCall && isRinging) { - //previous state was ringing, so stop ringing - stopRinging(); - } - - if (state == State.Connected) { - if (mLc.getCallsNb() == 1) { - //It is for incoming calls, because outgoing calls enter MODE_IN_COMMUNICATION immediately when they start. - //However, incoming call first use the MODE_RINGING to play the local ring. - if(call.getDir() == Call.Dir.Incoming) { - setAudioManagerInCallMode(); - //mAudioManager.abandonAudioFocus(null); - requestAudioFocus(STREAM_VOICE_CALL); - } - } - - if (Hacks.needSoftvolume()) { - Log.w("Using soft volume audio hack"); - adjustVolume(0); // Synchronize - } - } - - if (state == State.End || state == State.Error) { - if (mLc.getCallsNb() == 0) { - //Disabling proximity sensor - enableProximitySensing(false); - Context activity = getContext(); - if (mAudioFocused) { - int res = mAudioManager.abandonAudioFocus(null); - Log.d("Audio focus released a bit later: " + (res == AudioManager.AUDIOFOCUS_REQUEST_GRANTED ? "Granted" : "Denied")); - mAudioFocused = false; - } - if (activity != null) { - TelephonyManager tm = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE); - if (tm.getCallState() == TelephonyManager.CALL_STATE_IDLE) { - Log.d("---AudioManager: back to MODE_NORMAL"); - mAudioManager.setMode(AudioManager.MODE_NORMAL); - Log.d("All call terminated, routing back to earpiece"); - routeAudioToReceiver(); - } - } - } - } - if (state == State.UpdatedByRemote) { - // If the correspondent proposes video while audio call - boolean remoteVideo = call.getRemoteParams().videoEnabled(); - boolean localVideo = call.getCurrentParams().videoEnabled(); - boolean autoAcceptCameraPolicy = LinphonePreferences.instance().shouldAutomaticallyAcceptVideoRequests(); - if (remoteVideo && !localVideo && !autoAcceptCameraPolicy && !(LinphoneManager.getLc().getConference() != null)) { - LinphoneManager.getLc().deferCallUpdate(call); - } - } - if (state == State.OutgoingInit) { - //Enter the MODE_IN_COMMUNICATION mode as soon as possible, so that ringback - //is heard normally in earpiece or bluetooth receiver. - setAudioManagerInCallMode(); - requestAudioFocus(STREAM_VOICE_CALL); - startBluetooth(); - } - - if (state == State.StreamsRunning) { - startBluetooth(); - setAudioManagerInCallMode(); - } - } - - public void startBluetooth() { - if (BluetoothManager.getInstance().isBluetoothHeadsetAvailable()) { - BluetoothManager.getInstance().routeAudioToBluetooth(); - } - } - - public void onCallStatsUpdated(final Core lc, final Call call, final CallStats stats) {} - - @Override - public void onChatRoomStateChanged(Core lc, ChatRoom cr, ChatRoom.State state) { - - } - - public void onCallEncryptionChanged(Core lc, Call call, - boolean encrypted, String authenticationToken) { - } - - public void startEcCalibration() throws CoreException { - routeAudioToSpeaker(); - setAudioManagerInCallMode(); - Log.i("Set audio mode on 'Voice Communication'"); - requestAudioFocus(STREAM_VOICE_CALL); - int oldVolume = mAudioManager.getStreamVolume(STREAM_VOICE_CALL); - int maxVolume = mAudioManager.getStreamMaxVolume(STREAM_VOICE_CALL); - mAudioManager.setStreamVolume(STREAM_VOICE_CALL, maxVolume, 0); - mLc.startEchoCancellerCalibration(); - mAudioManager.setStreamVolume(STREAM_VOICE_CALL, oldVolume, 0); - } - - public int startEchoTester() throws CoreException { - routeAudioToSpeaker(); - setAudioManagerInCallMode(); - Log.i("Set audio mode on 'Voice Communication'"); - requestAudioFocus(STREAM_VOICE_CALL); - int oldVolume = mAudioManager.getStreamVolume(STREAM_VOICE_CALL); - int maxVolume = mAudioManager.getStreamMaxVolume(STREAM_VOICE_CALL); - int sampleRate = 44100; - mAudioManager.setStreamVolume(STREAM_VOICE_CALL, maxVolume, 0); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { - String sampleRateProperty = mAudioManager.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE); - sampleRate = Integer.parseInt(sampleRateProperty); - } - /*int status = */mLc.startEchoTester(sampleRate); - /*if (status > 0)*/ - echoTesterIsRunning = true; + mKeepAliveIntentFilter = new IntentFilter(Intent.ACTION_SCREEN_ON); + mKeepAliveIntentFilter.addAction(Intent.ACTION_SCREEN_OFF); + + mKeepAliveReceiver = new KeepAliveReceiver(); + mServiceContext.registerReceiver(mKeepAliveReceiver, mKeepAliveIntentFilter); + + mCallIntentFilter = new IntentFilter("android.intent.action.ACTION_NEW_OUTGOING_CALL"); + mCallIntentFilter.setPriority(99999999); + mCallReceiver = new OutgoingCallReceiver(); + try { + mServiceContext.registerReceiver(mCallReceiver, mCallIntentFilter); + } catch (IllegalArgumentException e) { + e.printStackTrace(); + } + mProximityWakelock = mPowerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, "manager_proximity_sensor"); + + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + mDozeIntentFilter = new IntentFilter(); + mDozeIntentFilter.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED); + mDozeReceiver = new DozeReceiver(); + dozeModeEnabled = ((PowerManager) mServiceContext.getSystemService(Context.POWER_SERVICE)).isDeviceIdleMode(); + mServiceContext.registerReceiver(mDozeReceiver, mDozeIntentFilter); + } + + mHookIntentFilter = new IntentFilter("com.base.module.phone.HOOKEVENT"); + mHookIntentFilter.setPriority(999); + mHookReceiver = new HookReceiver(); + mServiceContext.registerReceiver(mHookReceiver, mHookIntentFilter); + + // Since Android N we need to register the network manager + if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) { + mNetworkReceiver = new NetworkManager(); + mNetworkIntentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); + mServiceContext.registerReceiver(mNetworkReceiver, mNetworkIntentFilter); + } + + updateNetworkReachability(); + + resetCameraFromPreferences(); + + accountCreator = LinphoneManager.getLc().createAccountCreator(LinphonePreferences.instance().getXmlrpcUrl()); + accountCreator.setListener(this); + callGsmON = false; + + updateMissedChatCount(); + } + + public void setHandsetMode(Boolean on) { + if (mLc.isIncomingInvitePending() && on) { + handsetON = true; + mLc.acceptCall(mLc.getCurrentCall()); + LinphoneActivity.instance().startIncallActivity(mLc.getCurrentCall()); + } else if (on && CallActivity.isInstanciated()) { + handsetON = true; + CallActivity.instance().setSpeakerEnabled(true); + CallActivity.instance().refreshInCallActions(); + } else if (!on) { + handsetON = false; + LinphoneManager.getInstance().terminateCall(); + } + } + + public boolean isHansetModeOn() { + return handsetON; + } + + private void copyAssetsFromPackage() throws IOException { + copyIfNotExist(R.raw.linphonerc_default, mConfigFile); + copyFromPackage(R.raw.linphonerc_factory, new File(mLinphoneFactoryConfigFile).getName()); + copyIfNotExist(R.raw.lpconfig, mLPConfigXsd); + copyFromPackage(R.raw.assistant_create, new File(mDynamicConfigFile).getName()); + } + + public void copyIfNotExist(int ressourceId, String target) throws IOException { + File lFileToCopy = new File(target); + if (!lFileToCopy.exists()) { + copyFromPackage(ressourceId, lFileToCopy.getName()); + } + } + + public void copyFromPackage(int ressourceId, String target) throws IOException { + FileOutputStream lOutputStream = mServiceContext.openFileOutput(target, 0); + InputStream lInputStream = mR.openRawResource(ressourceId); + int readByte; + byte[] buff = new byte[8048]; + while ((readByte = lInputStream.read(buff)) != -1) { + lOutputStream.write(buff, 0, readByte); + } + lOutputStream.flush(); + lOutputStream.close(); + lInputStream.close(); + } + + //public void loadConfig(){ + // try { + // copyIfNotExist(R.raw.configrc, mConfigFile); + // } catch (Exception e){ + // Log.w(e); + // } + // LinphonePreferences.instance().setRemoteProvisioningUrl("file://" + mConfigFile); + // getLc().getConfig().setInt("misc","transient_provisioning",1); + //} + + public void updateNetworkReachability() { + if (mConnectivityManager == null) return; + + boolean connected = false; + NetworkInfo networkInfo = mConnectivityManager.getActiveNetworkInfo(); + connected = networkInfo != null && networkInfo.isConnected(); + + if (networkInfo == null && Version.sdkAboveOrEqual(Version.API21_LOLLIPOP_50)) { + for (Network network : mConnectivityManager.getAllNetworks()) { + if (network != null) { + networkInfo = mConnectivityManager.getNetworkInfo(network); + if (networkInfo != null && networkInfo.isConnected()) { + connected = true; + break; + } + } + } + } + + if (networkInfo == null || !connected) { + Log.i("No connectivity: setting network unreachable"); + mLc.setNetworkReachable(false); + } else if (dozeModeEnabled) { + Log.i("Doze Mode enabled: shutting down network"); + mLc.setNetworkReachable(false); + } else if (connected) { + manageTunnelServer(networkInfo); + + boolean wifiOnly = LinphonePreferences.instance().isWifiOnlyEnabled(); + if (wifiOnly) { + if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) { + mLc.setNetworkReachable(true); + } else { + Log.i("Wifi-only mode, setting network not reachable"); + mLc.setNetworkReachable(false); + } + } else { + int curtype = networkInfo.getType(); + + if (curtype != mLastNetworkType) { + //if kind of network has changed, we need to notify network_reachable(false) to make sure all current connections are destroyed. + //they will be re-created during setNetworkReachable(true). + Log.i("Connectivity has changed."); + mLc.setNetworkReachable(false); + } + mLc.setNetworkReachable(true); + mLastNetworkType = curtype; + } + } + + if (mLc.isNetworkReachable()) { + // When network isn't available, push informations might not be set. This should fix the issue. + LinphonePreferences prefs = LinphonePreferences.instance(); + prefs.setPushNotificationEnabled(prefs.isPushNotificationEnabled()); + } + } + + private void destroyLinphoneCore() { + if (LinphonePreferences.instance() != null) { + // We set network reachable at false before destroy LC to not send register with expires at 0 + if (LinphonePreferences.instance().isPushNotificationEnabled() + || LinphonePreferences.instance().isBackgroundModeEnabled()) { + mLc.setNetworkReachable(false); + } + } + mLc = null; + } + + public void dozeManager(boolean enable) { + if (enable) { + Log.i("[Doze Mode]: register"); + mServiceContext.registerReceiver(mDozeReceiver, mDozeIntentFilter); + dozeModeEnabled = true; + } else { + Log.i("[Doze Mode]: unregister"); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + try { + mServiceContext.unregisterReceiver(mDozeReceiver); + } catch (IllegalArgumentException e) { + e.printStackTrace(); + } + } + dozeModeEnabled = false; + } + } + + public void enableProximitySensing(boolean enable) { + if (enable) { + if (!mProximitySensingEnabled) { + mSensorManager.registerListener(this, mProximity, SensorManager.SENSOR_DELAY_NORMAL); + mProximitySensingEnabled = true; + } + } else { + if (mProximitySensingEnabled) { + mSensorManager.unregisterListener(this); + mProximitySensingEnabled = false; + // Don't forgeting to release wakelock if held + if (mProximityWakelock.isHeld()) { + mProximityWakelock.release(); + } + } + } + } + + public static Boolean isProximitySensorNearby(final SensorEvent event) { + float threshold = 4.001f; // <= 4 cm is near + + final float distanceInCm = event.values[0]; + final float maxDistance = event.sensor.getMaximumRange(); + Log.d("Proximity sensor report [" + distanceInCm + "] , for max range [" + maxDistance + "]"); + + if (maxDistance <= threshold) { + // Case binary 0/1 and short sensors + threshold = maxDistance; + } + return distanceInCm < threshold; + } + + @Override + public void onSensorChanged(SensorEvent event) { + if (event.timestamp == 0) return; + if (isProximitySensorNearby(event)) { + if (!mProximityWakelock.isHeld()) { + mProximityWakelock.acquire(); + } + } else { + if (mProximityWakelock.isHeld()) { + mProximityWakelock.release(); + } + } + } + + @Override + public void onAccuracyChanged(Sensor sensor, int accuracy) { + + } + + public static void ContactsManagerDestroy() { + if (LinphoneManager.instance != null && LinphoneManager.instance.mServiceContext != null) + LinphoneManager.instance.mServiceContext.getContentResolver().unregisterContentObserver(ContactsManager.getInstance()); + ContactsManager.getInstance().destroy(); + } + + public static void BluetoothManagerDestroy() { + BluetoothManager.getInstance().destroy(); + } + + public static synchronized void destroy() { + if (instance == null) return; + getInstance().changeStatusToOffline(); + sExited = true; + instance.destroyCore(); + } + + private String getString(int key) { + return mR.getString(key); + } + + /* Simple implementation as Android way seems very complicate: + For example: with wifi and mobile actives; when pulling mobile down: + I/Linphone( 8397): WIFI connected: setting network reachable + I/Linphone( 8397): new state [RegistrationProgress] + I/Linphone( 8397): mobile disconnected: setting network unreachable + I/Linphone( 8397): Managing tunnel + I/Linphone( 8397): WIFI connected: setting network reachable + */ + public void connectivityChanged(ConnectivityManager cm, boolean noConnectivity) { + updateNetworkReachability(); + } + + private Call ringingCall; + + private MediaPlayer mRingerPlayer; + private Vibrator mVibrator; + + public void onNewSubscriptionRequested(Core lc, Friend lf, String url) { + } + + public void onNotifyPresenceReceived(Core lc, Friend lf) { + } + + @Override + public void onEcCalibrationAudioInit(Core lc) { + + } + + @Override + public void onDtmfReceived(Core lc, Call call, int dtmf) { + Log.d("DTMF received: " + dtmf); + } + + @Override + public void onMessageReceived(Core lc, ChatRoom cr, ChatMessage message) { + if (mServiceContext.getResources().getBoolean(R.bool.disable_chat)) { + return; + } + + if (mCurrentChatRoomAddress != null && cr.getPeerAddress().asStringUriOnly().equals(mCurrentChatRoomAddress.asStringUriOnly())) { + Log.i("Message received for currently displayed chat room, do not make a notification"); + return; + } + + if (message.getErrorInfo() != null && message.getErrorInfo().getReason() == Reason.UnsupportedContent) { + Log.w("Message received but content is unsupported, do not notify it"); + return; + } + + if (!message.hasTextContent() && message.getFileTransferInformation() == null) { + Log.w("Message has no text or file transfer information to display, ignoring it..."); + return; + } + + increaseUnreadCountForChatRoom(cr); + + Address from = message.getFromAddress(); + LinphoneContact contact = ContactsManager.getInstance().findContactFromAddress(from); + String textMessage = (message.getFileTransferInformation() != null) ? getString(R.string.content_description_incoming_file) : message.getTextContent(); + + if (!mServiceContext.getResources().getBoolean(R.bool.disable_chat_message_notification) && !message.isOutgoing()) { + if (cr.hasCapability(ChatRoomCapabilities.OneToOne.toInt())) { + if (contact != null) { + LinphoneService.instance().displayMessageNotification(cr.getPeerAddress().asStringUriOnly(), contact.getFullName(), contact.getThumbnailUri(), textMessage); + } else { + LinphoneService.instance().displayMessageNotification(cr.getPeerAddress().asStringUriOnly(), from.getUsername(), null, textMessage); + } + } else { + String subject = cr.getSubject(); + if (contact != null) { + LinphoneService.instance().displayGroupChatMessageNotification(subject, cr.getPeerAddress().asStringUriOnly(), contact.getFullName(), contact.getThumbnailUri(), textMessage); + } else { + LinphoneService.instance().displayGroupChatMessageNotification(subject, cr.getPeerAddress().asStringUriOnly(), from.getUsername(), null, textMessage); + } + } + } + } + + public void setCurrentChatRoomAddress(Address address) { + mCurrentChatRoomAddress = address; + LinphoneService.instance().setCurrentlyDisplayedChatRoom(address != null ? address.asStringUriOnly() : null); + } + + @Override + public void onEcCalibrationResult(Core lc, EcCalibratorStatus status, int delay_ms) { + ((AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE)).setMode(AudioManager.MODE_NORMAL); + mAudioManager.abandonAudioFocus(null); + Log.i("Set audio mode on 'Normal'"); + } + + public void onGlobalStateChanged(final Core lc, final GlobalState state, final String message) { + Log.i("New global state [", state, "]"); + if (state == GlobalState.On) { + try { + Log.e("LinphoneManager", " onGlobalStateChanged ON"); + initLiblinphone(lc); + + } catch (IllegalArgumentException iae) { + Log.e(iae); + } catch (CoreException e) { + Log.e(e); + } + } + } + + public void onRegistrationStateChanged(final Core lc, final ProxyConfig proxy, final RegistrationState state, final String message) { + Log.i("New registration state [" + state + "]"); + if (LinphoneManager.getLc().getDefaultProxyConfig() == null) { + subscribeFriendList(false); + } + } + + public Context getContext() { + try { + if (LinphoneActivity.isInstanciated()) + return LinphoneActivity.instance(); + else if (CallActivity.isInstanciated()) + return CallActivity.instance(); + else if (CallIncomingActivity.isInstanciated()) + return CallIncomingActivity.instance(); + else if (mServiceContext != null) + return mServiceContext; + else if (LinphoneService.isReady()) + return LinphoneService.instance().getApplicationContext(); + } catch (Exception e) { + Log.e(e); + } + return null; + } + + public void setAudioManagerInCallMode() { + if (mAudioManager.getMode() == AudioManager.MODE_IN_COMMUNICATION) { + Log.w("[AudioManager] already in MODE_IN_COMMUNICATION, skipping..."); + return; + } + Log.d("[AudioManager] Mode: MODE_IN_COMMUNICATION"); + + mAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION); + } + + @SuppressLint("Wakelock") + public void onCallStateChanged(final Core lc, final Call call, final State state, final String message) { + Log.i("New call state [", state, "]"); + if (state == State.IncomingReceived && !call.equals(lc.getCurrentCall())) { + if (call.getReplacedCall() != null) { + // attended transfer + // it will be accepted automatically. + return; + } + } + + if (state == State.IncomingReceived && getCallGsmON()) { + if (mLc != null) { + mLc.declineCall(call, Reason.Busy); + } + } else if (state == State.IncomingReceived && (LinphonePreferences.instance().isAutoAnswerEnabled()) && !getCallGsmON()) { + TimerTask lTask = new TimerTask() { + @Override + public void run() { + if (mLc != null) { + if (mLc.getCallsNb() > 0) { + mLc.acceptCall(call); + if (LinphoneManager.getInstance() != null) { + LinphoneManager.getInstance().routeAudioToReceiver(); + if (LinphoneActivity.instance() != null) + LinphoneActivity.instance().startIncallActivity(call); + } + } + } + } + }; + mTimer = new Timer("Auto answer"); + mTimer.schedule(lTask, mPrefs.getAutoAnswerTime()); + } else if (state == State.IncomingReceived || (state == State.IncomingEarlyMedia && mR.getBoolean(R.bool.allow_ringing_while_early_media))) { + // Brighten screen for at least 10 seconds + if (mLc.getCallsNb() == 1) { + requestAudioFocus(STREAM_RING); + + ringingCall = call; + startRinging(); + // otherwise there is the beep + } + } else if (call == ringingCall && isRinging) { + //previous state was ringing, so stop ringing + stopRinging(); + } + + if (state == State.Connected) { + if (mLc.getCallsNb() == 1) { + //It is for incoming calls, because outgoing calls enter MODE_IN_COMMUNICATION immediately when they start. + //However, incoming call first use the MODE_RINGING to play the local ring. + if (call.getDir() == Call.Dir.Incoming) { + setAudioManagerInCallMode(); + //mAudioManager.abandonAudioFocus(null); + requestAudioFocus(STREAM_VOICE_CALL); + } + } + + if (Hacks.needSoftvolume()) { + Log.w("Using soft volume audio hack"); + adjustVolume(0); // Synchronize + } + } + + if (state == State.End || state == State.Error) { + if (mLc.getCallsNb() == 0) { + //Disabling proximity sensor + enableProximitySensing(false); + Context activity = getContext(); + if (mAudioFocused) { + int res = mAudioManager.abandonAudioFocus(null); + Log.d("Audio focus released a bit later: " + (res == AudioManager.AUDIOFOCUS_REQUEST_GRANTED ? "Granted" : "Denied")); + mAudioFocused = false; + } + if (activity != null) { + TelephonyManager tm = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE); + if (tm.getCallState() == TelephonyManager.CALL_STATE_IDLE) { + Log.d("---AudioManager: back to MODE_NORMAL"); + mAudioManager.setMode(AudioManager.MODE_NORMAL); + Log.d("All call terminated, routing back to earpiece"); + routeAudioToReceiver(); + } + } + } + } + if (state == State.UpdatedByRemote) { + // If the correspondent proposes video while audio call + boolean remoteVideo = call.getRemoteParams().videoEnabled(); + boolean localVideo = call.getCurrentParams().videoEnabled(); + boolean autoAcceptCameraPolicy = LinphonePreferences.instance().shouldAutomaticallyAcceptVideoRequests(); + if (remoteVideo && !localVideo && !autoAcceptCameraPolicy && !(LinphoneManager.getLc().getConference() != null)) { + LinphoneManager.getLc().deferCallUpdate(call); + } + } + if (state == State.OutgoingInit) { + //Enter the MODE_IN_COMMUNICATION mode as soon as possible, so that ringback + //is heard normally in earpiece or bluetooth receiver. + setAudioManagerInCallMode(); + requestAudioFocus(STREAM_VOICE_CALL); + startBluetooth(); + } + + if (state == State.StreamsRunning) { + startBluetooth(); + setAudioManagerInCallMode(); + } + } + + public void startBluetooth() { + if (BluetoothManager.getInstance().isBluetoothHeadsetAvailable()) { + BluetoothManager.getInstance().routeAudioToBluetooth(); + } + } + + public void onCallStatsUpdated(final Core lc, final Call call, final CallStats stats) { + } + + @Override + public void onChatRoomStateChanged(Core lc, ChatRoom cr, ChatRoom.State state) { + + } + + public void onCallEncryptionChanged(Core lc, Call call, + boolean encrypted, String authenticationToken) { + } + + public void startEcCalibration() throws CoreException { + routeAudioToSpeaker(); + setAudioManagerInCallMode(); + Log.i("Set audio mode on 'Voice Communication'"); + requestAudioFocus(STREAM_VOICE_CALL); + int oldVolume = mAudioManager.getStreamVolume(STREAM_VOICE_CALL); + int maxVolume = mAudioManager.getStreamMaxVolume(STREAM_VOICE_CALL); + mAudioManager.setStreamVolume(STREAM_VOICE_CALL, maxVolume, 0); + mLc.startEchoCancellerCalibration(); + mAudioManager.setStreamVolume(STREAM_VOICE_CALL, oldVolume, 0); + } + + public int startEchoTester() throws CoreException { + routeAudioToSpeaker(); + setAudioManagerInCallMode(); + Log.i("Set audio mode on 'Voice Communication'"); + requestAudioFocus(STREAM_VOICE_CALL); + int oldVolume = mAudioManager.getStreamVolume(STREAM_VOICE_CALL); + int maxVolume = mAudioManager.getStreamMaxVolume(STREAM_VOICE_CALL); + int sampleRate = 44100; + mAudioManager.setStreamVolume(STREAM_VOICE_CALL, maxVolume, 0); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { + String sampleRateProperty = mAudioManager.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE); + sampleRate = Integer.parseInt(sampleRateProperty); + } + /*int status = */ + mLc.startEchoTester(sampleRate); + /*if (status > 0)*/ + echoTesterIsRunning = true; /*else { echoTesterIsRunning = false; routeAudioToReceiver(); @@ -1290,492 +1297,500 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou ((AudioManager)getContext().getSystemService(Context.AUDIO_SERVICE)).setMode(AudioManager.MODE_NORMAL); Log.i("Set audio mode on 'Normal'"); }*/ - return 1; - //return status; - } - - public int stopEchoTester() throws CoreException { - echoTesterIsRunning = false; - /*int status = */mLc.stopEchoTester(); - routeAudioToReceiver(); - ((AudioManager)getContext().getSystemService(Context.AUDIO_SERVICE)).setMode(AudioManager.MODE_NORMAL); - Log.i("Set audio mode on 'Normal'"); - return 1;//status; - } - - public boolean getEchoTesterStatus() { - return echoTesterIsRunning; - } - - private boolean isRinging; - - private void requestAudioFocus(int stream){ - if (!mAudioFocused){ - int res = mAudioManager.requestAudioFocus(null, stream, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE ); - Log.d("Audio focus requested: " + (res == AudioManager.AUDIOFOCUS_REQUEST_GRANTED ? "Granted" : "Denied")); - if (res == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) mAudioFocused=true; - } - } - - public void enableDeviceRingtone(boolean use) { - if (use) { - mLc.setRing(null); - } else { - mLc.setRing(mRingSoundFile); - } - } - - private synchronized void startRinging() { - if (!LinphonePreferences.instance().isDeviceRingtoneEnabled()) { - // Enable speaker audio route, linphone library will do the ringing itself automatically - routeAudioToSpeaker(); - return; - } - - if (mR.getBoolean(R.bool.allow_ringing_while_early_media)) { - routeAudioToSpeaker(); // Need to be able to ear the ringtone during the early media - } - - //if (Hacks.needGalaxySAudioHack()) - mAudioManager.setMode(MODE_RINGTONE); - - try { - if ((mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE || mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL) && mVibrator != null) { - long[] patern = {0,1000,1000}; - mVibrator.vibrate(patern, 1); - } - if (mRingerPlayer == null) { - requestAudioFocus(STREAM_RING); - mRingerPlayer = new MediaPlayer(); - mRingerPlayer.setAudioStreamType(STREAM_RING); - - String ringtone = LinphonePreferences.instance().getRingtone(Settings.System.DEFAULT_RINGTONE_URI.toString()); - try { - if (ringtone.startsWith("content://")) { - mRingerPlayer.setDataSource(mServiceContext, Uri.parse(ringtone)); - } else { - FileInputStream fis = new FileInputStream(ringtone); - mRingerPlayer.setDataSource(fis.getFD()); - fis.close(); - } - } catch (IOException e) { - Log.e(e, "Cannot set ringtone"); - } - - mRingerPlayer.prepare(); - mRingerPlayer.setLooping(true); - mRingerPlayer.start(); - } else { - Log.w("already ringing"); - } - } catch (Exception e) { - Log.e(e,"cannot handle incoming call"); - } - isRinging = true; - } - - private synchronized void stopRinging() { - if (mRingerPlayer != null) { - mRingerPlayer.stop(); - mRingerPlayer.release(); - mRingerPlayer = null; - } - if (mVibrator != null) { - mVibrator.cancel(); - } - - if (Hacks.needGalaxySAudioHack()) - mAudioManager.setMode(AudioManager.MODE_NORMAL); - - isRinging = false; - // You may need to call galaxys audio hack after this method - if (!BluetoothManager.getInstance().isBluetoothHeadsetAvailable()) { - if (mServiceContext.getResources().getBoolean(R.bool.isTablet)) { - Log.d("Stopped ringing, routing back to speaker"); - routeAudioToSpeaker(); - } else { - Log.d("Stopped ringing, routing back to earpiece"); - routeAudioToReceiver(); - } - } - } - - - public static String extractADisplayName(Resources r, Address address) { - if (address == null) return r.getString(R.string.unknown_incoming_call_name); - - final String displayName = address.getDisplayName(); - if (displayName!=null) { - return displayName; - } else if (address.getUsername() != null){ - return address.getUsername(); - } else { - String rms = address.toString(); - if (rms != null && rms.length() > 1) - return rms; - - return r.getString(R.string.unknown_incoming_call_name); - } - } - - public static boolean reinviteWithVideo() { - return CallManager.getInstance().reinviteWithVideo(); - } - - /** - * - * @return false if already in video call. - */ - public boolean addVideo() { - Call call = mLc.getCurrentCall(); - enableCamera(call, true); - return reinviteWithVideo(); - } - - public boolean acceptCallIfIncomingPending() throws CoreException { - if (mLc.isIncomingInvitePending()) { - mLc.acceptCall(mLc.getCurrentCall()); - return true; - } - return false; - } - - public boolean acceptCallWithParams(Call call, CallParams params) { - mLc.acceptCallWithParams(call, params); - return true; - } - - public void adjustVolume(int i) { - if (Build.VERSION.SDK_INT < 15) { - int oldVolume = mAudioManager.getStreamVolume(LINPHONE_VOLUME_STREAM); - int maxVolume = mAudioManager.getStreamMaxVolume(LINPHONE_VOLUME_STREAM); - - int nextVolume = oldVolume +i; - if (nextVolume > maxVolume) nextVolume = maxVolume; - if (nextVolume < 0) nextVolume = 0; - - mLc.setPlaybackGainDb((nextVolume - maxVolume)* dbStep); - } else - // starting from ICS, volume must be adjusted by the application, at least for STREAM_VOICE_CALL volume stream - mAudioManager.adjustStreamVolume(LINPHONE_VOLUME_STREAM, i < 0 ? AudioManager.ADJUST_LOWER : AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI); - } - - public static synchronized Core getLcIfManagerNotDestroyedOrNull() { - if (sExited || instance == null) { - // Can occur if the UI thread play a posted event but in the meantime the LinphoneManager was destroyed - // Ex: stop call and quickly terminate application. - return null; - } - return getLc(); - } - - public static final boolean isInstanciated() { - return instance != null; - } - - public void isAccountWithAlias(){ - if(LinphoneManager.getLc().getDefaultProxyConfig() != null) { - long now = new Timestamp(new Date().getTime()).getTime(); - if (accountCreator != null && LinphonePreferences.instance().getLinkPopupTime() == null - || Long.parseLong(LinphonePreferences.instance().getLinkPopupTime()) < now) { - accountCreator.setUsername(LinphonePreferences.instance().getAccountUsername(LinphonePreferences.instance().getDefaultAccountIndex())); - accountCreator.isAccountExist(); - } - } else { - LinphonePreferences.instance().setLinkPopupTime(null); - } - } - - private void askLinkWithPhoneNumber(){ - long now = new Timestamp(new Date().getTime()).getTime(); - long future = new Timestamp(LinphoneActivity.instance().getResources().getInteger(R.integer.popup_time_interval)).getTime(); - long newDate = now + future; - - LinphonePreferences.instance().setLinkPopupTime(String.valueOf(newDate)); - - final Dialog dialog = LinphoneActivity.instance().displayDialog(String.format(getString(R.string.link_account_popup), LinphoneManager.getLc().getDefaultProxyConfig().getIdentityAddress().asStringUriOnly())); - Button delete = (Button) dialog.findViewById(R.id.delete_button); - delete.setText(getString(R.string.link)); - Button cancel = (Button) dialog.findViewById(R.id.cancel); - cancel.setText(getString(R.string.maybe_later)); - - delete.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - Intent assistant = new Intent(); - assistant.setClass(LinphoneActivity.instance(), AssistantActivity.class); - assistant.putExtra("LinkPhoneNumber", true); - assistant.putExtra("LinkPhoneNumberAsk", true); - mServiceContext.startActivity(assistant); - dialog.dismiss(); - } - }); - - LinphonePreferences.instance().setLinkPopupTime(String.valueOf(newDate)); - - cancel.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - dialog.dismiss(); - } - }); - dialog.show(); - } - - public void setDozeModeEnabled(boolean b) { - dozeModeEnabled = b; - } - - public String getmDynamicConfigFile() { - return mDynamicConfigFile; - } - - public boolean getCallGsmON() { - return callGsmON; - } - - public void setCallGsmON(boolean on) { - callGsmON = on; - } - - @Override - public void onTransferStateChanged(Core lc, Call call, - State new_call_state) { - - } - - @Override - public void onInfoReceived(Core lc, Call call, InfoMessage info) { - Log.d("Info message received from "+call.getRemoteAddress().asString()); - Content ct=info.getContent(); - if (ct!=null){ - Log.d("Info received with body with mime type "+ct.getType()+"/"+ct.getSubtype()+" and data ["+ct.getStringBuffer()+"]"); - } - } - @Override - public void onSubscriptionStateChanged(Core lc, Event ev, - SubscriptionState state) { - Log.d("Subscription state changed to "+state+" event name is "+ev.getName()); - } - - @Override - public void onCallLogUpdated(Core lc, CallLog newcl) { - - } - - @Override - public void onNotifyReceived(Core lc, Event ev, - String eventName, Content content) { - Log.d("Notify received for event "+eventName); - if (content!=null) Log.d("with content "+content.getType()+"/"+content.getSubtype()+" data:"+content.getStringBuffer()); - } - - @Override - public void onSubscribeReceived(Core lc, Event lev, String subscribeEvent, Content body) { - - } - - @Override - public void onPublishStateChanged(Core lc, Event ev, PublishState state) { - Log.d("Publish state changed to " + state + " for event name " + ev.getName()); - } - - @Override - public void onIsComposingReceived(Core lc, ChatRoom cr) { - Log.d("Composing received for chatroom " + cr.getPeerAddress().asStringUriOnly()); - } - - @Override - public void onMessageReceivedUnableDecrypt(Core lc, ChatRoom room, ChatMessage message) { - - } - - @Override - public void onConfiguringStatus(Core lc, - ConfiguringState state, String message) { - Log.d("Remote provisioning status = " + state.toString() + " (" + message + ")"); - - LinphonePreferences prefs = LinphonePreferences.instance(); - if (state == ConfiguringState.Successful) { - if (prefs.isProvisioningLoginViewEnabled()) { - ProxyConfig proxyConfig = lc.createProxyConfig(); - Address addr = proxyConfig.getIdentityAddress(); - wizardLoginViewDomain = addr.getDomain(); - } - prefs.setPushNotificationEnabled(prefs.isPushNotificationEnabled()); - } - } - - @Override - public void onCallCreated(Core lc, Call call) { - - } - - @Override - public void onLogCollectionUploadProgressIndication(Core linphoneCore, int offset, int total) { - if(total > 0) - Log.d("Log upload progress: currently uploaded = " + offset + " , total = " + total + ", % = " + String.valueOf((offset * 100) / total)); - } - - @Override - public void onVersionUpdateCheckResultReceived(Core lc, VersionUpdateCheckResult result, String version, String url) { - if (result == VersionUpdateCheckResult.NewVersionAvailable) { - final String urlToUse = url; - final String versionAv = version; - mHandler.postDelayed(new Runnable() { - @Override - public void run() { - AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); - builder.setMessage(getString(R.string.update_available) + ": " + versionAv); - builder.setCancelable(false); - builder.setNeutralButton(getString(R.string.ok), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - if (urlToUse != null) { - Intent urlIntent = new Intent(Intent.ACTION_VIEW); - urlIntent.setData(Uri.parse(urlToUse)); - getContext().startActivity(urlIntent); - } - } - }); - builder.show(); - } - }, 1000); - } - } - - @Override - public void onEcCalibrationAudioUninit(Core lc) { - - } - - @Override - public void onLogCollectionUploadStateChanged(Core linphoneCore, LogCollectionUploadState state, String info) { - Log.d("Log upload state: " + state.toString() + ", info = " + info); - } - - @Override - public void onFriendListCreated(Core lc, FriendList list) { - list.setListener(ContactsManager.getInstance()); - } - - @Override - public void onFriendListRemoved(Core lc, FriendList list) { - list.setListener(null); - } - - @Override - public void onReferReceived(Core lc, String refer_to) { - - } - - @Override - public void onNetworkReachable(Core lc, boolean enable) { - - } - - @Override - public void onAuthenticationRequested(Core lc, - AuthInfo authInfo, AuthMethod method) { - // TODO Auto-generated method stub - - } - - @Override - public void onNotifyPresenceReceivedForUriOrTel(Core lc, Friend lf, String uri_or_tel, PresenceModel presence_model) { - - } - - @Override - public void onBuddyInfoUpdated(Core lc, Friend lf) { - - } - - @Override - public void onIsAccountExist(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - if (status.equals(AccountCreator.Status.AccountExist)) { - accountCreator.isAccountLinked(); - } - } - - @Override - public void onCreateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) {} - - @Override - public void onActivateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) {} - - @Override - public void onLinkAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - if (status.equals(AccountCreator.Status.AccountNotLinked)) { - askLinkWithPhoneNumber(); - } - } - - @Override - public void onActivateAlias(AccountCreator accountCreator, AccountCreator.Status status, String resp) {} - - @Override - public void onIsAccountActivated(AccountCreator accountCreator, AccountCreator.Status status, String resp) {} - - @Override - public void onRecoverAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) {} - - @Override - public void onIsAccountLinked(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - if (status.equals(AccountCreator.Status.AccountNotLinked)) { - askLinkWithPhoneNumber(); - } - } - - @Override - public void onIsAliasUsed(AccountCreator accountCreator, AccountCreator.Status status, String resp) {} - - @Override - public void onUpdateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - - } - - private void updateMissedChatCount() { - for (ChatRoom cr : LinphoneManager.getLc().getChatRooms()) { - updateUnreadCountForChatRoom(cr, cr.getUnreadMessagesCount()); - } - } - - public int getUnreadMessageCount() { - int count = 0; - for (Integer unread : mUnreadChatsPerRoom.values()) { - count += unread; - } - return count; - } - - public void updateUnreadCountForChatRoom(String key, Integer value) { - mUnreadChatsPerRoom.put(key, value); - } - - - public void updateUnreadCountForChatRoom(ChatRoom cr, Integer value) { - String key = cr.getPeerAddress().asStringUriOnly(); - updateUnreadCountForChatRoom(key, value); - } - - public int getUnreadCountForChatRoom(ChatRoom cr) { - String key = cr.getPeerAddress().asStringUriOnly(); - if (mUnreadChatsPerRoom.containsKey(key)) { - return mUnreadChatsPerRoom.get(key); - } - return 0; - } - - private void increaseUnreadCountForChatRoom(ChatRoom cr) { - String key = cr.getPeerAddress().asStringUriOnly(); - if (mUnreadChatsPerRoom.containsKey(key)) { - mUnreadChatsPerRoom.put(key, mUnreadChatsPerRoom.get(key) + 1); - } else { - mUnreadChatsPerRoom.put(key, 1); - } - } - - public void onQrcodeFound(Core lc, String something){ - } + return 1; + //return status; + } + + public int stopEchoTester() throws CoreException { + echoTesterIsRunning = false; + /*int status = */ + mLc.stopEchoTester(); + routeAudioToReceiver(); + ((AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE)).setMode(AudioManager.MODE_NORMAL); + Log.i("Set audio mode on 'Normal'"); + return 1;//status; + } + + public boolean getEchoTesterStatus() { + return echoTesterIsRunning; + } + + private boolean isRinging; + + private void requestAudioFocus(int stream) { + if (!mAudioFocused) { + int res = mAudioManager.requestAudioFocus(null, stream, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE); + Log.d("Audio focus requested: " + (res == AudioManager.AUDIOFOCUS_REQUEST_GRANTED ? "Granted" : "Denied")); + if (res == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) mAudioFocused = true; + } + } + + public void enableDeviceRingtone(boolean use) { + if (use) { + mLc.setRing(null); + } else { + mLc.setRing(mRingSoundFile); + } + } + + private synchronized void startRinging() { + if (!LinphonePreferences.instance().isDeviceRingtoneEnabled()) { + // Enable speaker audio route, linphone library will do the ringing itself automatically + routeAudioToSpeaker(); + return; + } + + if (mR.getBoolean(R.bool.allow_ringing_while_early_media)) { + routeAudioToSpeaker(); // Need to be able to ear the ringtone during the early media + } + + //if (Hacks.needGalaxySAudioHack()) + mAudioManager.setMode(MODE_RINGTONE); + + try { + if ((mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE || mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL) && mVibrator != null) { + long[] patern = {0, 1000, 1000}; + mVibrator.vibrate(patern, 1); + } + if (mRingerPlayer == null) { + requestAudioFocus(STREAM_RING); + mRingerPlayer = new MediaPlayer(); + mRingerPlayer.setAudioStreamType(STREAM_RING); + + String ringtone = LinphonePreferences.instance().getRingtone(Settings.System.DEFAULT_RINGTONE_URI.toString()); + try { + if (ringtone.startsWith("content://")) { + mRingerPlayer.setDataSource(mServiceContext, Uri.parse(ringtone)); + } else { + FileInputStream fis = new FileInputStream(ringtone); + mRingerPlayer.setDataSource(fis.getFD()); + fis.close(); + } + } catch (IOException e) { + Log.e(e, "Cannot set ringtone"); + } + + mRingerPlayer.prepare(); + mRingerPlayer.setLooping(true); + mRingerPlayer.start(); + } else { + Log.w("already ringing"); + } + } catch (Exception e) { + Log.e(e, "cannot handle incoming call"); + } + isRinging = true; + } + + private synchronized void stopRinging() { + if (mRingerPlayer != null) { + mRingerPlayer.stop(); + mRingerPlayer.release(); + mRingerPlayer = null; + } + if (mVibrator != null) { + mVibrator.cancel(); + } + + if (Hacks.needGalaxySAudioHack()) + mAudioManager.setMode(AudioManager.MODE_NORMAL); + + isRinging = false; + // You may need to call galaxys audio hack after this method + if (!BluetoothManager.getInstance().isBluetoothHeadsetAvailable()) { + if (mServiceContext.getResources().getBoolean(R.bool.isTablet)) { + Log.d("Stopped ringing, routing back to speaker"); + routeAudioToSpeaker(); + } else { + Log.d("Stopped ringing, routing back to earpiece"); + routeAudioToReceiver(); + } + } + } + + + public static String extractADisplayName(Resources r, Address address) { + if (address == null) return r.getString(R.string.unknown_incoming_call_name); + + final String displayName = address.getDisplayName(); + if (displayName != null) { + return displayName; + } else if (address.getUsername() != null) { + return address.getUsername(); + } else { + String rms = address.toString(); + if (rms != null && rms.length() > 1) + return rms; + + return r.getString(R.string.unknown_incoming_call_name); + } + } + + public static boolean reinviteWithVideo() { + return CallManager.getInstance().reinviteWithVideo(); + } + + /** + * @return false if already in video call. + */ + public boolean addVideo() { + Call call = mLc.getCurrentCall(); + enableCamera(call, true); + return reinviteWithVideo(); + } + + public boolean acceptCallIfIncomingPending() throws CoreException { + if (mLc.isIncomingInvitePending()) { + mLc.acceptCall(mLc.getCurrentCall()); + return true; + } + return false; + } + + public boolean acceptCallWithParams(Call call, CallParams params) { + mLc.acceptCallWithParams(call, params); + return true; + } + + public void adjustVolume(int i) { + if (Build.VERSION.SDK_INT < 15) { + int oldVolume = mAudioManager.getStreamVolume(LINPHONE_VOLUME_STREAM); + int maxVolume = mAudioManager.getStreamMaxVolume(LINPHONE_VOLUME_STREAM); + + int nextVolume = oldVolume + i; + if (nextVolume > maxVolume) nextVolume = maxVolume; + if (nextVolume < 0) nextVolume = 0; + + mLc.setPlaybackGainDb((nextVolume - maxVolume) * dbStep); + } else + // starting from ICS, volume must be adjusted by the application, at least for STREAM_VOICE_CALL volume stream + mAudioManager.adjustStreamVolume(LINPHONE_VOLUME_STREAM, i < 0 ? AudioManager.ADJUST_LOWER : AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI); + } + + public static synchronized Core getLcIfManagerNotDestroyedOrNull() { + if (sExited || instance == null) { + // Can occur if the UI thread play a posted event but in the meantime the LinphoneManager was destroyed + // Ex: stop call and quickly terminate application. + return null; + } + return getLc(); + } + + public static final boolean isInstanciated() { + return instance != null; + } + + public void isAccountWithAlias() { + if (LinphoneManager.getLc().getDefaultProxyConfig() != null) { + long now = new Timestamp(new Date().getTime()).getTime(); + if (accountCreator != null && LinphonePreferences.instance().getLinkPopupTime() == null + || Long.parseLong(LinphonePreferences.instance().getLinkPopupTime()) < now) { + accountCreator.setUsername(LinphonePreferences.instance().getAccountUsername(LinphonePreferences.instance().getDefaultAccountIndex())); + accountCreator.isAccountExist(); + } + } else { + LinphonePreferences.instance().setLinkPopupTime(null); + } + } + + private void askLinkWithPhoneNumber() { + long now = new Timestamp(new Date().getTime()).getTime(); + long future = new Timestamp(LinphoneActivity.instance().getResources().getInteger(R.integer.popup_time_interval)).getTime(); + long newDate = now + future; + + LinphonePreferences.instance().setLinkPopupTime(String.valueOf(newDate)); + + final Dialog dialog = LinphoneActivity.instance().displayDialog(String.format(getString(R.string.link_account_popup), LinphoneManager.getLc().getDefaultProxyConfig().getIdentityAddress().asStringUriOnly())); + Button delete = (Button) dialog.findViewById(R.id.delete_button); + delete.setText(getString(R.string.link)); + Button cancel = (Button) dialog.findViewById(R.id.cancel); + cancel.setText(getString(R.string.maybe_later)); + + delete.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + Intent assistant = new Intent(); + assistant.setClass(LinphoneActivity.instance(), AssistantActivity.class); + assistant.putExtra("LinkPhoneNumber", true); + assistant.putExtra("LinkPhoneNumberAsk", true); + mServiceContext.startActivity(assistant); + dialog.dismiss(); + } + }); + + LinphonePreferences.instance().setLinkPopupTime(String.valueOf(newDate)); + + cancel.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + dialog.dismiss(); + } + }); + dialog.show(); + } + + public void setDozeModeEnabled(boolean b) { + dozeModeEnabled = b; + } + + public String getmDynamicConfigFile() { + return mDynamicConfigFile; + } + + public boolean getCallGsmON() { + return callGsmON; + } + + public void setCallGsmON(boolean on) { + callGsmON = on; + } + + @Override + public void onTransferStateChanged(Core lc, Call call, + State new_call_state) { + + } + + @Override + public void onInfoReceived(Core lc, Call call, InfoMessage info) { + Log.d("Info message received from " + call.getRemoteAddress().asString()); + Content ct = info.getContent(); + if (ct != null) { + Log.d("Info received with body with mime type " + ct.getType() + "/" + ct.getSubtype() + " and data [" + ct.getStringBuffer() + "]"); + } + } + + @Override + public void onSubscriptionStateChanged(Core lc, Event ev, + SubscriptionState state) { + Log.d("Subscription state changed to " + state + " event name is " + ev.getName()); + } + + @Override + public void onCallLogUpdated(Core lc, CallLog newcl) { + + } + + @Override + public void onNotifyReceived(Core lc, Event ev, + String eventName, Content content) { + Log.d("Notify received for event " + eventName); + if (content != null) + Log.d("with content " + content.getType() + "/" + content.getSubtype() + " data:" + content.getStringBuffer()); + } + + @Override + public void onSubscribeReceived(Core lc, Event lev, String subscribeEvent, Content body) { + + } + + @Override + public void onPublishStateChanged(Core lc, Event ev, PublishState state) { + Log.d("Publish state changed to " + state + " for event name " + ev.getName()); + } + + @Override + public void onIsComposingReceived(Core lc, ChatRoom cr) { + Log.d("Composing received for chatroom " + cr.getPeerAddress().asStringUriOnly()); + } + + @Override + public void onMessageReceivedUnableDecrypt(Core lc, ChatRoom room, ChatMessage message) { + + } + + @Override + public void onConfiguringStatus(Core lc, + ConfiguringState state, String message) { + Log.d("Remote provisioning status = " + state.toString() + " (" + message + ")"); + + LinphonePreferences prefs = LinphonePreferences.instance(); + if (state == ConfiguringState.Successful) { + if (prefs.isProvisioningLoginViewEnabled()) { + ProxyConfig proxyConfig = lc.createProxyConfig(); + Address addr = proxyConfig.getIdentityAddress(); + wizardLoginViewDomain = addr.getDomain(); + } + prefs.setPushNotificationEnabled(prefs.isPushNotificationEnabled()); + } + } + + @Override + public void onCallCreated(Core lc, Call call) { + + } + + @Override + public void onLogCollectionUploadProgressIndication(Core linphoneCore, int offset, int total) { + if (total > 0) + Log.d("Log upload progress: currently uploaded = " + offset + " , total = " + total + ", % = " + String.valueOf((offset * 100) / total)); + } + + @Override + public void onVersionUpdateCheckResultReceived(Core lc, VersionUpdateCheckResult result, String version, String url) { + if (result == VersionUpdateCheckResult.NewVersionAvailable) { + final String urlToUse = url; + final String versionAv = version; + mHandler.postDelayed(new Runnable() { + @Override + public void run() { + AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); + builder.setMessage(getString(R.string.update_available) + ": " + versionAv); + builder.setCancelable(false); + builder.setNeutralButton(getString(R.string.ok), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + if (urlToUse != null) { + Intent urlIntent = new Intent(Intent.ACTION_VIEW); + urlIntent.setData(Uri.parse(urlToUse)); + getContext().startActivity(urlIntent); + } + } + }); + builder.show(); + } + }, 1000); + } + } + + @Override + public void onEcCalibrationAudioUninit(Core lc) { + + } + + @Override + public void onLogCollectionUploadStateChanged(Core linphoneCore, LogCollectionUploadState state, String info) { + Log.d("Log upload state: " + state.toString() + ", info = " + info); + } + + @Override + public void onFriendListCreated(Core lc, FriendList list) { + list.setListener(ContactsManager.getInstance()); + } + + @Override + public void onFriendListRemoved(Core lc, FriendList list) { + list.setListener(null); + } + + @Override + public void onReferReceived(Core lc, String refer_to) { + + } + + @Override + public void onNetworkReachable(Core lc, boolean enable) { + + } + + @Override + public void onAuthenticationRequested(Core lc, + AuthInfo authInfo, AuthMethod method) { + // TODO Auto-generated method stub + + } + + @Override + public void onNotifyPresenceReceivedForUriOrTel(Core lc, Friend lf, String uri_or_tel, PresenceModel presence_model) { + + } + + @Override + public void onBuddyInfoUpdated(Core lc, Friend lf) { + + } + + @Override + public void onIsAccountExist(AccountCreator accountCreator, AccountCreator.Status status, String resp) { + if (status.equals(AccountCreator.Status.AccountExist)) { + accountCreator.isAccountLinked(); + } + } + + @Override + public void onCreateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { + } + + @Override + public void onActivateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { + } + + @Override + public void onLinkAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { + if (status.equals(AccountCreator.Status.AccountNotLinked)) { + askLinkWithPhoneNumber(); + } + } + + @Override + public void onActivateAlias(AccountCreator accountCreator, AccountCreator.Status status, String resp) { + } + + @Override + public void onIsAccountActivated(AccountCreator accountCreator, AccountCreator.Status status, String resp) { + } + + @Override + public void onRecoverAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { + } + + @Override + public void onIsAccountLinked(AccountCreator accountCreator, AccountCreator.Status status, String resp) { + if (status.equals(AccountCreator.Status.AccountNotLinked)) { + askLinkWithPhoneNumber(); + } + } + + @Override + public void onIsAliasUsed(AccountCreator accountCreator, AccountCreator.Status status, String resp) { + } + + @Override + public void onUpdateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { + + } + + private void updateMissedChatCount() { + for (ChatRoom cr : LinphoneManager.getLc().getChatRooms()) { + updateUnreadCountForChatRoom(cr, cr.getUnreadMessagesCount()); + } + } + + public int getUnreadMessageCount() { + int count = 0; + for (Integer unread : mUnreadChatsPerRoom.values()) { + count += unread; + } + return count; + } + + public void updateUnreadCountForChatRoom(String key, Integer value) { + mUnreadChatsPerRoom.put(key, value); + } + + + public void updateUnreadCountForChatRoom(ChatRoom cr, Integer value) { + String key = cr.getPeerAddress().asStringUriOnly(); + updateUnreadCountForChatRoom(key, value); + } + + public int getUnreadCountForChatRoom(ChatRoom cr) { + String key = cr.getPeerAddress().asStringUriOnly(); + if (mUnreadChatsPerRoom.containsKey(key)) { + return mUnreadChatsPerRoom.get(key); + } + return 0; + } + + private void increaseUnreadCountForChatRoom(ChatRoom cr) { + String key = cr.getPeerAddress().asStringUriOnly(); + if (mUnreadChatsPerRoom.containsKey(key)) { + mUnreadChatsPerRoom.put(key, mUnreadChatsPerRoom.get(key) + 1); + } else { + mUnreadChatsPerRoom.put(key, 1); + } + } + + public void onQrcodeFound(Core lc, String something) { + } } diff --git a/src/android/org/linphone/LinphonePreferences.java b/src/android/org/linphone/LinphonePreferences.java index c42679e09..d96aa1bd1 100644 --- a/src/android/org/linphone/LinphonePreferences.java +++ b/src/android/org/linphone/LinphonePreferences.java @@ -25,17 +25,17 @@ import android.content.pm.PackageManager; import org.linphone.core.AVPFMode; import org.linphone.core.Address; -import org.linphone.core.TransportType; import org.linphone.core.AuthInfo; +import org.linphone.core.Config; import org.linphone.core.Core; -import org.linphone.core.LimeState; -import org.linphone.core.MediaEncryption; -import org.linphone.core.Transports; import org.linphone.core.CoreException; import org.linphone.core.Factory; +import org.linphone.core.LimeState; +import org.linphone.core.MediaEncryption; import org.linphone.core.NatPolicy; import org.linphone.core.ProxyConfig; -import org.linphone.core.Config; +import org.linphone.core.TransportType; +import org.linphone.core.Transports; import org.linphone.core.Tunnel; import org.linphone.core.TunnelConfig; import org.linphone.core.VideoActivationPolicy; @@ -50,1592 +50,1596 @@ import java.io.InputStreamReader; import java.util.ArrayList; public class LinphonePreferences { - private static final int LINPHONE_CORE_RANDOM_PORT = -1; - private static LinphonePreferences instance; - private Context mContext; - private String basePath; - - public static final synchronized LinphonePreferences instance() { - if (instance == null) { - instance = new LinphonePreferences(); - } - return instance; - } - - private LinphonePreferences() { - - } - - public void setContext(Context c) { - mContext = c; - basePath = mContext.getFilesDir().getAbsolutePath(); - } - - private String getString(int key) { - if (mContext == null && LinphoneManager.isInstanciated()) { - mContext = LinphoneManager.getInstance().getContext(); - } - - return mContext.getString(key); - } - - private Core getLc() { - if (!LinphoneManager.isInstanciated()) - return null; - - return LinphoneManager.getLcIfManagerNotDestroyedOrNull(); - } - - public Config getConfig() { - Core lc = getLc(); - if (lc != null) { - return lc.getConfig(); - } - - if (!LinphoneManager.isInstanciated()) { - File linphonerc = new File(basePath + "/.linphonerc"); - if (linphonerc.exists()) { - return Factory.instance().createConfig(linphonerc.getAbsolutePath()); - } else if (mContext != null) { - InputStream inputStream = mContext.getResources().openRawResource(R.raw.linphonerc_default); - InputStreamReader inputreader = new InputStreamReader(inputStream); - BufferedReader buffreader = new BufferedReader(inputreader); - StringBuilder text = new StringBuilder(); - String line; - try { - while ((line = buffreader.readLine()) != null) { - text.append(line); - text.append('\n'); - } - } catch (IOException ioe) { - Log.e(ioe); - } - return Factory.instance().createConfigFromString(text.toString()); - } - } else { - return Factory.instance().createConfig(LinphoneManager.getInstance().mConfigFile); - } - return null; - } - - public void removePreviousVersionAuthInfoRemoval() { - getConfig().setBool("sip", "store_auth_info", true); - } - - // App settings - public boolean isFirstLaunch() { - return getConfig().getBool("app", "first_launch", true); - } - - public void firstLaunchSuccessful() { - getConfig().setBool("app", "first_launch", false); - } - - public String getRingtone(String defaultRingtone) { - String ringtone = getConfig().getString("app", "ringtone", defaultRingtone); - if (ringtone == null || ringtone.length() == 0) - ringtone = defaultRingtone; - return ringtone; - } - - public void setRingtone(String ringtonePath) { - getConfig().setString("app", "ringtone", ringtonePath); - - } - - public boolean shouldAutomaticallyAcceptFriendsRequests() { - return false; //TODO - } - // End of app settings - - // Accounts settings - private ProxyConfig getProxyConfig(int n) { - if (getLc() == null) return null; - ProxyConfig[] prxCfgs = getLc().getProxyConfigList(); - if (n < 0 || n >= prxCfgs.length) - return null; - return prxCfgs[n]; - } - - private AuthInfo getAuthInfo(int n) { - ProxyConfig prxCfg = getProxyConfig(n); - if (prxCfg == null) return null; - Address addr = prxCfg.getIdentityAddress(); - AuthInfo authInfo = getLc().findAuthInfo(null, addr.getUsername(), addr.getDomain()); - return authInfo; - } - - /** - * Removes a authInfo from the core and returns a copy of it. - * Useful to edit a authInfo (you should call saveAuthInfo after the modifications to save them). - */ - private AuthInfo getClonedAuthInfo(int n) { - if (getLc() == null) return null; - AuthInfo authInfo = getAuthInfo(n); - if (authInfo == null) - return null; - - AuthInfo cloneAuthInfo = authInfo.clone(); - getLc().removeAuthInfo(authInfo); - return cloneAuthInfo; - } - - /** - * Saves a authInfo into the core. - * Useful to save the changes made to a cloned authInfo. - */ - private void saveAuthInfo(AuthInfo authInfo) { - if (getLc() == null) return; - getLc().addAuthInfo(authInfo); - } - - public static class AccountBuilder { - private Core lc; - private String tempUsername; - private String tempDisplayName; - private String tempUserId; - private String tempPassword; - private String tempHa1; - private String tempDomain; - private String tempProxy; - private String tempRealm; - private String tempPrefix; - private boolean tempOutboundProxy; - private String tempContactsParams; - private String tempExpire; - private TransportType tempTransport; - private boolean tempAvpfEnabled = false; - private int tempAvpfRRInterval = 0; - private String tempQualityReportingCollector; - private boolean tempQualityReportingEnabled = false; - private int tempQualityReportingInterval = 0; - private boolean tempEnabled = true; - private boolean tempNoDefault = false; - - - public AccountBuilder(Core lc) { - this.lc = lc; - } - - public AccountBuilder setTransport(TransportType transport) { - tempTransport = transport; - return this; - } - - public AccountBuilder setUsername(String username) { - tempUsername = username; - return this; - } - - public AccountBuilder setDisplayName(String displayName) { - tempDisplayName = displayName; - return this; - } - - public AccountBuilder setPassword(String password) { - tempPassword = password; - return this; - } - - public AccountBuilder setHa1(String ha1) { - tempHa1 = ha1; - return this; - } - - public AccountBuilder setDomain(String domain) { - tempDomain = domain; - return this; - } - - public AccountBuilder setServerAddr(String proxy) { - tempProxy = proxy; - return this; - } - - public AccountBuilder setOutboundProxyEnabled(boolean enabled) { - tempOutboundProxy = enabled; - return this; - } - - public AccountBuilder setContactParameters(String contactParams) { - tempContactsParams = contactParams; - return this; - } - - public AccountBuilder setExpires(String expire) { - tempExpire = expire; - return this; - } - - public AccountBuilder setUserid(String userId) { - tempUserId = userId; - return this; - } - - public AccountBuilder setAvpfEnabled(boolean enable) { - tempAvpfEnabled = enable; - return this; - } - - public AccountBuilder setAvpfRrInterval(int interval) { - tempAvpfRRInterval = interval; - return this; - } - - public AccountBuilder setRealm(String realm) { - tempRealm = realm; - return this; - } - - public AccountBuilder setQualityReportingCollector(String collector) { - tempQualityReportingCollector = collector; - return this; - } - - public AccountBuilder setPrefix(String prefix) { - tempPrefix = prefix; - return this; - } - - public AccountBuilder setQualityReportingEnabled(boolean enable) { - tempQualityReportingEnabled = enable; - return this; - } - - public AccountBuilder setQualityReportingInterval(int interval) { - tempQualityReportingInterval = interval; - return this; - } - - public AccountBuilder setEnabled(boolean enable) { - tempEnabled = enable; - return this; - } - - public AccountBuilder setNoDefault(boolean yesno) { - tempNoDefault = yesno; - return this; - } - - /** - * Creates a new account - * @throws CoreException - */ - public void saveNewAccount() throws CoreException { - - if (tempUsername == null || tempUsername.length() < 1 || tempDomain == null || tempDomain.length() < 1) { - Log.w("Skipping account save: username or domain not provided"); - return; - } - - String identity = "sip:" + tempUsername + "@" + tempDomain; - String proxy = "sip:"; - if (tempProxy == null) { - proxy += tempDomain; - } else { - if (!tempProxy.startsWith("sip:") && !tempProxy.startsWith(" n && LinphoneManager.getLc().getAuthInfoList()[n] != null) { - userid = getAccountUserId(n); - realm = getAccountRealm(n); - LinphoneManager.getLc().removeAuthInfo(LinphoneManager.getLc().getAuthInfoList()[n]); - } - AuthInfo authInfo = Factory.instance().createAuthInfo( - user, userid, password, ha1, realm, domain); - LinphoneManager.getLc().addAuthInfo(authInfo); - } - } - - public String getAccountPassword(int n) { - AuthInfo authInfo = getAuthInfo(n); - return authInfo == null ? null : authInfo.getPassword(); - } - - public String getAccountHa1(int n) { - AuthInfo authInfo = getAuthInfo(n); - return authInfo == null ? null : authInfo.getHa1(); - } - - public void setAccountIce(int n, boolean ice) { - try { - ProxyConfig prxCfg = getProxyConfig(n); - prxCfg.edit(); - prxCfg.getNatPolicy().enableIce(ice); - prxCfg.getNatPolicy().enableStun(ice); - prxCfg.done(); - } catch (Exception e) { - Log.e(e); - } - } - - public boolean getAccountIce(int n) { - if (getProxyConfig(n) == null || getProxyConfig(n).getNatPolicy() == null) return false; - return getProxyConfig(n).getNatPolicy().iceEnabled(); - } - - public void setAccountStunServer(int n, String stun) { - try { - ProxyConfig prxCfg = getProxyConfig(n); - prxCfg.edit(); - NatPolicy np = prxCfg.getNatPolicy(); - np.setStunServer(stun); - prxCfg.done(); - } catch (Exception e) { - Log.e(e); - } - } - - public String getAccountStunServer(int n) { - if (getProxyConfig(n) == null || getProxyConfig(n).getNatPolicy() == null) return ""; - return getProxyConfig(n).getNatPolicy().getStunServer(); - } - - public void setAccountDomain(int n, String domain) { - String identity = "sip:" + getAccountUsername(n) + "@" + domain; - AuthInfo old_info = getAuthInfo(n); - ProxyConfig prxCfg = getProxyConfig(n); - prxCfg.edit(); - prxCfg.setIdentityAddress(Factory.instance().createAddress(identity)); - prxCfg.enableRegister(true); - prxCfg.done(); - - if (old_info != null) { - // We have to remove the previous auth info after otherwise we can't unregister the previous proxy config - AuthInfo new_info = old_info.clone(); - getLc().removeAuthInfo(old_info); - new_info.setDomain(domain); - saveAuthInfo(new_info); - } - } - - public String getAccountDomain(int n) { - ProxyConfig proxyConf = getProxyConfig(n); - return (proxyConf != null) ? proxyConf.getDomain() : ""; - } - - public void setAccountProxy(int n, String proxy) { - if (proxy == null || proxy.length() <= 0) { - proxy = getAccountDomain(n); - } - - if (!proxy.contains("sip:")) { - proxy = "sip:" + proxy; - } - - Address proxyAddr = Factory.instance().createAddress(proxy); - if (proxyAddr == null) return; - - if (!proxy.contains("transport=")) { - proxyAddr.setTransport(getAccountTransport(n)); - } - - ProxyConfig prxCfg = getProxyConfig(n); - prxCfg.edit(); - prxCfg.setServerAddr(proxyAddr.asStringUriOnly()); - prxCfg.done(); - - if (isAccountOutboundProxySet(n)) { - setAccountOutboundProxyEnabled(n, true); - } - } - - public String getAccountProxy(int n) { - String proxy = getProxyConfig(n).getServerAddr(); - return proxy; - } - - - public void setAccountOutboundProxyEnabled(int n, boolean enabled) { - ProxyConfig prxCfg = getProxyConfig(n); - prxCfg.edit(); - if (enabled) { - String route = prxCfg.getServerAddr(); - prxCfg.setRoute(route); - } else { - prxCfg.setRoute(null); - } - prxCfg.done(); - } - - public boolean isAccountOutboundProxySet(int n) { - return getProxyConfig(n).getRoute() != null; - } - - public void setAccountContactParameters(int n, String contactParams) { - ProxyConfig prxCfg = getProxyConfig(n); - prxCfg.edit(); - prxCfg.setContactUriParameters(contactParams); - prxCfg.done(); - } - - public String getExpires(int n) { - return String.valueOf(getProxyConfig(n).getExpires()); - } - - public void setExpires(int n, String expire) { - try { - ProxyConfig prxCfg = getProxyConfig(n); - prxCfg.edit(); - prxCfg.setExpires(Integer.parseInt(expire)); - prxCfg.done(); - } catch (NumberFormatException nfe) { } - } - - public String getPrefix(int n) { - return getProxyConfig(n).getDialPrefix(); - } - - public void setPrefix(int n, String prefix) { - ProxyConfig prxCfg = getProxyConfig(n); - prxCfg.edit(); - prxCfg.setDialPrefix(prefix); - prxCfg.done(); - } - - public boolean avpfEnabled(int n) { - return getProxyConfig(n).avpfEnabled(); - } - - public void setAvpfMode(int n, boolean enable) { - ProxyConfig prxCfg = getProxyConfig(n); - prxCfg.edit(); - prxCfg.setAvpfMode(enable ? AVPFMode.Enabled : AVPFMode.Disabled); - prxCfg.done(); - } - - public String getAvpfRrInterval(int n) { - return String.valueOf(getProxyConfig(n).getAvpfRrInterval()); - } - - public void setAvpfRrInterval(int n, String interval) { - try { - ProxyConfig prxCfg = getProxyConfig(n); - prxCfg.edit(); - prxCfg.setAvpfRrInterval(Integer.parseInt(interval)); - prxCfg.done(); - } catch (NumberFormatException nfe) { } - } - - public boolean getReplacePlusByZeroZero(int n) { - return getProxyConfig(n).getDialEscapePlus(); - } - - public void setReplacePlusByZeroZero(int n, boolean replace) { - ProxyConfig prxCfg = getProxyConfig(n); - prxCfg.edit(); - prxCfg.setDialEscapePlus(replace); - prxCfg.done(); - } - - public void enablePushNotifForProxy(int n, boolean enable) { - ProxyConfig prxCfg = getProxyConfig(n); - prxCfg.edit(); - prxCfg.setPushNotificationAllowed(enable); - prxCfg.done(); - - setPushNotificationEnabled(isPushNotificationEnabled()); - } - - public boolean isPushNotifEnabledForProxy(int n) { - ProxyConfig prxCfg = getProxyConfig(n); - return prxCfg.isPushNotificationAllowed(); - } - - public boolean isFriendlistsubscriptionEnabled() { - return getConfig().getBool("app", "friendlist_subscription_enabled", false); - } - - public void enabledFriendlistSubscription(boolean enabled) { - getConfig().setBool("app", "friendlist_subscription_enabled", enabled); - - } - - public void setDefaultAccount(int accountIndex) { - if (getLc() == null) return; - ProxyConfig[] prxCfgs = getLc().getProxyConfigList(); - if (accountIndex >= 0 && accountIndex < prxCfgs.length) - getLc().setDefaultProxyConfig(prxCfgs[accountIndex]); - } - - public int getDefaultAccountIndex() { - if (getLc() == null) - return -1; - ProxyConfig defaultPrxCfg = getLc().getDefaultProxyConfig(); - if (defaultPrxCfg == null) - return -1; - - ProxyConfig[] prxCfgs = getLc().getProxyConfigList(); - for (int i = 0; i < prxCfgs.length; i++) { - if (defaultPrxCfg.getIdentityAddress().equals(prxCfgs[i].getIdentityAddress())) { - return i; - } - } - return -1; - } - - public int getAccountCount() { - if (getLc() == null || getLc().getProxyConfigList() == null) - return 0; - - return getLc().getProxyConfigList().length; - } - - public void setAccountEnabled(int n, boolean enabled) { - if (getLc() == null) return; - ProxyConfig prxCfg = getProxyConfig(n); - if (prxCfg == null) { - LinphoneUtils.displayErrorAlert(getString(R.string.error), mContext); - return; - } - prxCfg.edit(); - prxCfg.enableRegister(enabled); - prxCfg.done(); - - // If default proxy config is disabled, try to set another one as default proxy - if (!enabled && getLc().getDefaultProxyConfig().getIdentityAddress().equals(prxCfg.getIdentityAddress())) { - int count = getLc().getProxyConfigList().length; - if (count > 1) { - for (int i = 0; i < count; i++) { - if (isAccountEnabled(i)) { - getLc().setDefaultProxyConfig(getProxyConfig(i)); - break; - } - } - } - } - } - - public boolean isAccountEnabled(int n) { - return getProxyConfig(n).registerEnabled(); - } - - public void resetDefaultProxyConfig(){ - if (getLc() == null) return; - int count = getLc().getProxyConfigList().length; - for (int i = 0; i < count; i++) { - if (isAccountEnabled(i)) { - getLc().setDefaultProxyConfig(getProxyConfig(i)); - break; - } - } - - if(getLc().getDefaultProxyConfig() == null){ - getLc().setDefaultProxyConfig(getProxyConfig(0)); - } - } - - public void deleteAccount(int n) { - if (getLc() == null) return; - ProxyConfig proxyCfg = getProxyConfig(n); - if (proxyCfg != null) - getLc().removeProxyConfig(proxyCfg); - if (getLc().getProxyConfigList().length != 0) { - resetDefaultProxyConfig(); - } else { - getLc().setDefaultProxyConfig(null); - } - - AuthInfo authInfo = getAuthInfo(n); - if (authInfo != null) { - getLc().removeAuthInfo(authInfo); - } - - getLc().refreshRegisters(); - } - // End of accounts settings - - // Audio settings - public void setEchoCancellation(boolean enable) { - if (getLc() == null) return; - getLc().enableEchoCancellation(enable); - } - - public boolean echoCancellationEnabled() { - if (getLc() == null) return false; - return getLc().echoCancellationEnabled(); - } - - public int getEchoCalibration() { - return getConfig().getInt("sound", "ec_delay", -1); - } - - public boolean isEchoConfigurationUpdated() { - return getConfig().getBool("app", "ec_updated", false); - } - - public void echoConfigurationUpdated() { - getConfig().setBool("app", "ec_updated", true); - } - // End of audio settings - - // Video settings - public boolean useFrontCam() { - return getConfig().getBool("app", "front_camera_default", true); - } - - public void setFrontCamAsDefault(boolean frontcam) { - getConfig().setBool("app", "front_camera_default", frontcam); - } - - public boolean isVideoEnabled() { - if (getLc() == null) return false; - return getLc().videoSupported() && getLc().videoEnabled(); - } - - public void enableVideo(boolean enable) { - if (getLc() == null) return; - getLc().enableVideoCapture(enable); - getLc().enableVideoDisplay(enable); - } - - public boolean shouldInitiateVideoCall() { - if (getLc() == null) return false; - return getLc().getVideoActivationPolicy().getAutomaticallyInitiate(); - } - - public void setInitiateVideoCall(boolean initiate) { - if (getLc() == null) return; - VideoActivationPolicy vap = getLc().getVideoActivationPolicy(); - vap.setAutomaticallyInitiate(initiate); - getLc().setVideoActivationPolicy(vap); - } - - public boolean shouldAutomaticallyAcceptVideoRequests() { - if (getLc() == null) return false; - VideoActivationPolicy vap = getLc().getVideoActivationPolicy(); - return vap.getAutomaticallyAccept(); - } - - public void setAutomaticallyAcceptVideoRequests(boolean accept) { - if (getLc() == null) return; - VideoActivationPolicy vap = getLc().getVideoActivationPolicy(); - vap.setAutomaticallyAccept(accept); - getLc().setVideoActivationPolicy(vap); - } - - public String getVideoPreset() { - if (getLc() == null) return null; - String preset = getLc().getVideoPreset(); - if (preset == null) preset = "default"; - return preset; - } - - public void setVideoPreset(String preset) { - if (getLc() == null) return; - if (preset.equals("default")) preset = null; - getLc().setVideoPreset(preset); - preset = getVideoPreset(); - if (!preset.equals("custom")) { - getLc().setPreferredFramerate(0); - } - setPreferredVideoSize(getPreferredVideoSize()); // Apply the bandwidth limit - } - - public String getPreferredVideoSize() { - //Core can only return video size (width and height), not the name - return getConfig().getString("video", "size", "qvga"); - } - - public void setPreferredVideoSize(String preferredVideoSize) { - if (getLc() == null) return; - getLc().setPreferredVideoSizeByName(preferredVideoSize); - } - - public int getPreferredVideoFps() { - if (getLc() == null) return 0; - return (int)getLc().getPreferredFramerate(); - } - - public void setPreferredVideoFps(int fps) { - if (getLc() == null) return; - getLc().setPreferredFramerate(fps); - } - - public int getBandwidthLimit() { - if (getLc() == null) return 0; - return getLc().getDownloadBandwidth(); - } - - public void setBandwidthLimit(int bandwidth) { - if (getLc() == null) return; - getLc().setUploadBandwidth(bandwidth); - getLc().setDownloadBandwidth(bandwidth); - } - // End of video settings - - // Call settings - public boolean useRfc2833Dtmfs() { - if (getLc() == null) return false; - return getLc().getUseRfc2833ForDtmf(); - } - - public void sendDtmfsAsRfc2833(boolean use) { - if (getLc() == null) return; - getLc().setUseRfc2833ForDtmf(use); - } - - public boolean useSipInfoDtmfs() { - if (getLc() == null) return false; - return getLc().getUseInfoForDtmf(); - } - - public void sendDTMFsAsSipInfo(boolean use) { - if (getLc() == null) return; - getLc().setUseInfoForDtmf(use); - } - - public int getIncTimeout() { - if (getLc() == null) return 0; - return getLc().getIncTimeout(); - } - - public void setIncTimeout(int timeout) { - if (getLc() == null) return; - getLc().setIncTimeout(timeout); - } - - public int getInCallTimeout() { - if (getLc() == null) return 0; - return getLc().getInCallTimeout(); - } - - public void setInCallTimeout(int timeout) { - if (getLc() == null) return; - getLc().setInCallTimeout(timeout); - } - - public String getVoiceMailUri() { - return getConfig().getString("app", "voice_mail", null); - } - - public void setVoiceMailUri(String uri) { - getConfig().setString("app", "voice_mail", uri); - } - - public boolean getNativeDialerCall() { - return getConfig().getBool("app", "native_dialer_call", false); - } - - public void setNativeDialerCall(boolean use) { - getConfig().setBool("app", "native_dialer_call", use); - } + private static final int LINPHONE_CORE_RANDOM_PORT = -1; + private static LinphonePreferences instance; + private Context mContext; + private String basePath; + + public static final synchronized LinphonePreferences instance() { + if (instance == null) { + instance = new LinphonePreferences(); + } + return instance; + } + + private LinphonePreferences() { + + } + + public void setContext(Context c) { + mContext = c; + basePath = mContext.getFilesDir().getAbsolutePath(); + } + + private String getString(int key) { + if (mContext == null && LinphoneManager.isInstanciated()) { + mContext = LinphoneManager.getInstance().getContext(); + } + + return mContext.getString(key); + } + + private Core getLc() { + if (!LinphoneManager.isInstanciated()) + return null; + + return LinphoneManager.getLcIfManagerNotDestroyedOrNull(); + } + + public Config getConfig() { + Core lc = getLc(); + if (lc != null) { + return lc.getConfig(); + } + + if (!LinphoneManager.isInstanciated()) { + File linphonerc = new File(basePath + "/.linphonerc"); + if (linphonerc.exists()) { + return Factory.instance().createConfig(linphonerc.getAbsolutePath()); + } else if (mContext != null) { + InputStream inputStream = mContext.getResources().openRawResource(R.raw.linphonerc_default); + InputStreamReader inputreader = new InputStreamReader(inputStream); + BufferedReader buffreader = new BufferedReader(inputreader); + StringBuilder text = new StringBuilder(); + String line; + try { + while ((line = buffreader.readLine()) != null) { + text.append(line); + text.append('\n'); + } + } catch (IOException ioe) { + Log.e(ioe); + } + return Factory.instance().createConfigFromString(text.toString()); + } + } else { + return Factory.instance().createConfig(LinphoneManager.getInstance().mConfigFile); + } + return null; + } + + public void removePreviousVersionAuthInfoRemoval() { + getConfig().setBool("sip", "store_auth_info", true); + } + + // App settings + public boolean isFirstLaunch() { + return getConfig().getBool("app", "first_launch", true); + } + + public void firstLaunchSuccessful() { + getConfig().setBool("app", "first_launch", false); + } + + public String getRingtone(String defaultRingtone) { + String ringtone = getConfig().getString("app", "ringtone", defaultRingtone); + if (ringtone == null || ringtone.length() == 0) + ringtone = defaultRingtone; + return ringtone; + } + + public void setRingtone(String ringtonePath) { + getConfig().setString("app", "ringtone", ringtonePath); + + } + + public boolean shouldAutomaticallyAcceptFriendsRequests() { + return false; //TODO + } + // End of app settings + + // Accounts settings + private ProxyConfig getProxyConfig(int n) { + if (getLc() == null) return null; + ProxyConfig[] prxCfgs = getLc().getProxyConfigList(); + if (n < 0 || n >= prxCfgs.length) + return null; + return prxCfgs[n]; + } + + private AuthInfo getAuthInfo(int n) { + ProxyConfig prxCfg = getProxyConfig(n); + if (prxCfg == null) return null; + Address addr = prxCfg.getIdentityAddress(); + AuthInfo authInfo = getLc().findAuthInfo(null, addr.getUsername(), addr.getDomain()); + return authInfo; + } + + /** + * Removes a authInfo from the core and returns a copy of it. + * Useful to edit a authInfo (you should call saveAuthInfo after the modifications to save them). + */ + private AuthInfo getClonedAuthInfo(int n) { + if (getLc() == null) return null; + AuthInfo authInfo = getAuthInfo(n); + if (authInfo == null) + return null; + + AuthInfo cloneAuthInfo = authInfo.clone(); + getLc().removeAuthInfo(authInfo); + return cloneAuthInfo; + } + + /** + * Saves a authInfo into the core. + * Useful to save the changes made to a cloned authInfo. + */ + private void saveAuthInfo(AuthInfo authInfo) { + if (getLc() == null) return; + getLc().addAuthInfo(authInfo); + } + + public static class AccountBuilder { + private Core lc; + private String tempUsername; + private String tempDisplayName; + private String tempUserId; + private String tempPassword; + private String tempHa1; + private String tempDomain; + private String tempProxy; + private String tempRealm; + private String tempPrefix; + private boolean tempOutboundProxy; + private String tempContactsParams; + private String tempExpire; + private TransportType tempTransport; + private boolean tempAvpfEnabled = false; + private int tempAvpfRRInterval = 0; + private String tempQualityReportingCollector; + private boolean tempQualityReportingEnabled = false; + private int tempQualityReportingInterval = 0; + private boolean tempEnabled = true; + private boolean tempNoDefault = false; + + + public AccountBuilder(Core lc) { + this.lc = lc; + } + + public AccountBuilder setTransport(TransportType transport) { + tempTransport = transport; + return this; + } + + public AccountBuilder setUsername(String username) { + tempUsername = username; + return this; + } + + public AccountBuilder setDisplayName(String displayName) { + tempDisplayName = displayName; + return this; + } + + public AccountBuilder setPassword(String password) { + tempPassword = password; + return this; + } + + public AccountBuilder setHa1(String ha1) { + tempHa1 = ha1; + return this; + } + + public AccountBuilder setDomain(String domain) { + tempDomain = domain; + return this; + } + + public AccountBuilder setServerAddr(String proxy) { + tempProxy = proxy; + return this; + } + + public AccountBuilder setOutboundProxyEnabled(boolean enabled) { + tempOutboundProxy = enabled; + return this; + } + + public AccountBuilder setContactParameters(String contactParams) { + tempContactsParams = contactParams; + return this; + } + + public AccountBuilder setExpires(String expire) { + tempExpire = expire; + return this; + } + + public AccountBuilder setUserid(String userId) { + tempUserId = userId; + return this; + } + + public AccountBuilder setAvpfEnabled(boolean enable) { + tempAvpfEnabled = enable; + return this; + } + + public AccountBuilder setAvpfRrInterval(int interval) { + tempAvpfRRInterval = interval; + return this; + } + + public AccountBuilder setRealm(String realm) { + tempRealm = realm; + return this; + } + + public AccountBuilder setQualityReportingCollector(String collector) { + tempQualityReportingCollector = collector; + return this; + } + + public AccountBuilder setPrefix(String prefix) { + tempPrefix = prefix; + return this; + } + + public AccountBuilder setQualityReportingEnabled(boolean enable) { + tempQualityReportingEnabled = enable; + return this; + } + + public AccountBuilder setQualityReportingInterval(int interval) { + tempQualityReportingInterval = interval; + return this; + } + + public AccountBuilder setEnabled(boolean enable) { + tempEnabled = enable; + return this; + } + + public AccountBuilder setNoDefault(boolean yesno) { + tempNoDefault = yesno; + return this; + } + + /** + * Creates a new account + * + * @throws CoreException + */ + public void saveNewAccount() throws CoreException { + + if (tempUsername == null || tempUsername.length() < 1 || tempDomain == null || tempDomain.length() < 1) { + Log.w("Skipping account save: username or domain not provided"); + return; + } + + String identity = "sip:" + tempUsername + "@" + tempDomain; + String proxy = "sip:"; + if (tempProxy == null) { + proxy += tempDomain; + } else { + if (!tempProxy.startsWith("sip:") && !tempProxy.startsWith(" n && LinphoneManager.getLc().getAuthInfoList()[n] != null) { + userid = getAccountUserId(n); + realm = getAccountRealm(n); + LinphoneManager.getLc().removeAuthInfo(LinphoneManager.getLc().getAuthInfoList()[n]); + } + AuthInfo authInfo = Factory.instance().createAuthInfo( + user, userid, password, ha1, realm, domain); + LinphoneManager.getLc().addAuthInfo(authInfo); + } + } + + public String getAccountPassword(int n) { + AuthInfo authInfo = getAuthInfo(n); + return authInfo == null ? null : authInfo.getPassword(); + } + + public String getAccountHa1(int n) { + AuthInfo authInfo = getAuthInfo(n); + return authInfo == null ? null : authInfo.getHa1(); + } + + public void setAccountIce(int n, boolean ice) { + try { + ProxyConfig prxCfg = getProxyConfig(n); + prxCfg.edit(); + prxCfg.getNatPolicy().enableIce(ice); + prxCfg.getNatPolicy().enableStun(ice); + prxCfg.done(); + } catch (Exception e) { + Log.e(e); + } + } + + public boolean getAccountIce(int n) { + if (getProxyConfig(n) == null || getProxyConfig(n).getNatPolicy() == null) return false; + return getProxyConfig(n).getNatPolicy().iceEnabled(); + } + + public void setAccountStunServer(int n, String stun) { + try { + ProxyConfig prxCfg = getProxyConfig(n); + prxCfg.edit(); + NatPolicy np = prxCfg.getNatPolicy(); + np.setStunServer(stun); + prxCfg.done(); + } catch (Exception e) { + Log.e(e); + } + } + + public String getAccountStunServer(int n) { + if (getProxyConfig(n) == null || getProxyConfig(n).getNatPolicy() == null) return ""; + return getProxyConfig(n).getNatPolicy().getStunServer(); + } + + public void setAccountDomain(int n, String domain) { + String identity = "sip:" + getAccountUsername(n) + "@" + domain; + AuthInfo old_info = getAuthInfo(n); + ProxyConfig prxCfg = getProxyConfig(n); + prxCfg.edit(); + prxCfg.setIdentityAddress(Factory.instance().createAddress(identity)); + prxCfg.enableRegister(true); + prxCfg.done(); + + if (old_info != null) { + // We have to remove the previous auth info after otherwise we can't unregister the previous proxy config + AuthInfo new_info = old_info.clone(); + getLc().removeAuthInfo(old_info); + new_info.setDomain(domain); + saveAuthInfo(new_info); + } + } + + public String getAccountDomain(int n) { + ProxyConfig proxyConf = getProxyConfig(n); + return (proxyConf != null) ? proxyConf.getDomain() : ""; + } + + public void setAccountProxy(int n, String proxy) { + if (proxy == null || proxy.length() <= 0) { + proxy = getAccountDomain(n); + } + + if (!proxy.contains("sip:")) { + proxy = "sip:" + proxy; + } + + Address proxyAddr = Factory.instance().createAddress(proxy); + if (proxyAddr == null) return; + + if (!proxy.contains("transport=")) { + proxyAddr.setTransport(getAccountTransport(n)); + } + + ProxyConfig prxCfg = getProxyConfig(n); + prxCfg.edit(); + prxCfg.setServerAddr(proxyAddr.asStringUriOnly()); + prxCfg.done(); + + if (isAccountOutboundProxySet(n)) { + setAccountOutboundProxyEnabled(n, true); + } + } + + public String getAccountProxy(int n) { + String proxy = getProxyConfig(n).getServerAddr(); + return proxy; + } + + + public void setAccountOutboundProxyEnabled(int n, boolean enabled) { + ProxyConfig prxCfg = getProxyConfig(n); + prxCfg.edit(); + if (enabled) { + String route = prxCfg.getServerAddr(); + prxCfg.setRoute(route); + } else { + prxCfg.setRoute(null); + } + prxCfg.done(); + } + + public boolean isAccountOutboundProxySet(int n) { + return getProxyConfig(n).getRoute() != null; + } + + public void setAccountContactParameters(int n, String contactParams) { + ProxyConfig prxCfg = getProxyConfig(n); + prxCfg.edit(); + prxCfg.setContactUriParameters(contactParams); + prxCfg.done(); + } + + public String getExpires(int n) { + return String.valueOf(getProxyConfig(n).getExpires()); + } + + public void setExpires(int n, String expire) { + try { + ProxyConfig prxCfg = getProxyConfig(n); + prxCfg.edit(); + prxCfg.setExpires(Integer.parseInt(expire)); + prxCfg.done(); + } catch (NumberFormatException nfe) { + } + } + + public String getPrefix(int n) { + return getProxyConfig(n).getDialPrefix(); + } + + public void setPrefix(int n, String prefix) { + ProxyConfig prxCfg = getProxyConfig(n); + prxCfg.edit(); + prxCfg.setDialPrefix(prefix); + prxCfg.done(); + } + + public boolean avpfEnabled(int n) { + return getProxyConfig(n).avpfEnabled(); + } + + public void setAvpfMode(int n, boolean enable) { + ProxyConfig prxCfg = getProxyConfig(n); + prxCfg.edit(); + prxCfg.setAvpfMode(enable ? AVPFMode.Enabled : AVPFMode.Disabled); + prxCfg.done(); + } + + public String getAvpfRrInterval(int n) { + return String.valueOf(getProxyConfig(n).getAvpfRrInterval()); + } + + public void setAvpfRrInterval(int n, String interval) { + try { + ProxyConfig prxCfg = getProxyConfig(n); + prxCfg.edit(); + prxCfg.setAvpfRrInterval(Integer.parseInt(interval)); + prxCfg.done(); + } catch (NumberFormatException nfe) { + } + } + + public boolean getReplacePlusByZeroZero(int n) { + return getProxyConfig(n).getDialEscapePlus(); + } + + public void setReplacePlusByZeroZero(int n, boolean replace) { + ProxyConfig prxCfg = getProxyConfig(n); + prxCfg.edit(); + prxCfg.setDialEscapePlus(replace); + prxCfg.done(); + } + + public void enablePushNotifForProxy(int n, boolean enable) { + ProxyConfig prxCfg = getProxyConfig(n); + prxCfg.edit(); + prxCfg.setPushNotificationAllowed(enable); + prxCfg.done(); + + setPushNotificationEnabled(isPushNotificationEnabled()); + } + + public boolean isPushNotifEnabledForProxy(int n) { + ProxyConfig prxCfg = getProxyConfig(n); + return prxCfg.isPushNotificationAllowed(); + } + + public boolean isFriendlistsubscriptionEnabled() { + return getConfig().getBool("app", "friendlist_subscription_enabled", false); + } + + public void enabledFriendlistSubscription(boolean enabled) { + getConfig().setBool("app", "friendlist_subscription_enabled", enabled); + + } + + public void setDefaultAccount(int accountIndex) { + if (getLc() == null) return; + ProxyConfig[] prxCfgs = getLc().getProxyConfigList(); + if (accountIndex >= 0 && accountIndex < prxCfgs.length) + getLc().setDefaultProxyConfig(prxCfgs[accountIndex]); + } + + public int getDefaultAccountIndex() { + if (getLc() == null) + return -1; + ProxyConfig defaultPrxCfg = getLc().getDefaultProxyConfig(); + if (defaultPrxCfg == null) + return -1; + + ProxyConfig[] prxCfgs = getLc().getProxyConfigList(); + for (int i = 0; i < prxCfgs.length; i++) { + if (defaultPrxCfg.getIdentityAddress().equals(prxCfgs[i].getIdentityAddress())) { + return i; + } + } + return -1; + } + + public int getAccountCount() { + if (getLc() == null || getLc().getProxyConfigList() == null) + return 0; + + return getLc().getProxyConfigList().length; + } + + public void setAccountEnabled(int n, boolean enabled) { + if (getLc() == null) return; + ProxyConfig prxCfg = getProxyConfig(n); + if (prxCfg == null) { + LinphoneUtils.displayErrorAlert(getString(R.string.error), mContext); + return; + } + prxCfg.edit(); + prxCfg.enableRegister(enabled); + prxCfg.done(); + + // If default proxy config is disabled, try to set another one as default proxy + if (!enabled && getLc().getDefaultProxyConfig().getIdentityAddress().equals(prxCfg.getIdentityAddress())) { + int count = getLc().getProxyConfigList().length; + if (count > 1) { + for (int i = 0; i < count; i++) { + if (isAccountEnabled(i)) { + getLc().setDefaultProxyConfig(getProxyConfig(i)); + break; + } + } + } + } + } + + public boolean isAccountEnabled(int n) { + return getProxyConfig(n).registerEnabled(); + } + + public void resetDefaultProxyConfig() { + if (getLc() == null) return; + int count = getLc().getProxyConfigList().length; + for (int i = 0; i < count; i++) { + if (isAccountEnabled(i)) { + getLc().setDefaultProxyConfig(getProxyConfig(i)); + break; + } + } + + if (getLc().getDefaultProxyConfig() == null) { + getLc().setDefaultProxyConfig(getProxyConfig(0)); + } + } + + public void deleteAccount(int n) { + if (getLc() == null) return; + ProxyConfig proxyCfg = getProxyConfig(n); + if (proxyCfg != null) + getLc().removeProxyConfig(proxyCfg); + if (getLc().getProxyConfigList().length != 0) { + resetDefaultProxyConfig(); + } else { + getLc().setDefaultProxyConfig(null); + } + + AuthInfo authInfo = getAuthInfo(n); + if (authInfo != null) { + getLc().removeAuthInfo(authInfo); + } + + getLc().refreshRegisters(); + } + // End of accounts settings + + // Audio settings + public void setEchoCancellation(boolean enable) { + if (getLc() == null) return; + getLc().enableEchoCancellation(enable); + } + + public boolean echoCancellationEnabled() { + if (getLc() == null) return false; + return getLc().echoCancellationEnabled(); + } + + public int getEchoCalibration() { + return getConfig().getInt("sound", "ec_delay", -1); + } + + public boolean isEchoConfigurationUpdated() { + return getConfig().getBool("app", "ec_updated", false); + } + + public void echoConfigurationUpdated() { + getConfig().setBool("app", "ec_updated", true); + } + // End of audio settings + + // Video settings + public boolean useFrontCam() { + return getConfig().getBool("app", "front_camera_default", true); + } + + public void setFrontCamAsDefault(boolean frontcam) { + getConfig().setBool("app", "front_camera_default", frontcam); + } + + public boolean isVideoEnabled() { + if (getLc() == null) return false; + return getLc().videoSupported() && getLc().videoEnabled(); + } + + public void enableVideo(boolean enable) { + if (getLc() == null) return; + getLc().enableVideoCapture(enable); + getLc().enableVideoDisplay(enable); + } + + public boolean shouldInitiateVideoCall() { + if (getLc() == null) return false; + return getLc().getVideoActivationPolicy().getAutomaticallyInitiate(); + } + + public void setInitiateVideoCall(boolean initiate) { + if (getLc() == null) return; + VideoActivationPolicy vap = getLc().getVideoActivationPolicy(); + vap.setAutomaticallyInitiate(initiate); + getLc().setVideoActivationPolicy(vap); + } + + public boolean shouldAutomaticallyAcceptVideoRequests() { + if (getLc() == null) return false; + VideoActivationPolicy vap = getLc().getVideoActivationPolicy(); + return vap.getAutomaticallyAccept(); + } + + public void setAutomaticallyAcceptVideoRequests(boolean accept) { + if (getLc() == null) return; + VideoActivationPolicy vap = getLc().getVideoActivationPolicy(); + vap.setAutomaticallyAccept(accept); + getLc().setVideoActivationPolicy(vap); + } + + public String getVideoPreset() { + if (getLc() == null) return null; + String preset = getLc().getVideoPreset(); + if (preset == null) preset = "default"; + return preset; + } + + public void setVideoPreset(String preset) { + if (getLc() == null) return; + if (preset.equals("default")) preset = null; + getLc().setVideoPreset(preset); + preset = getVideoPreset(); + if (!preset.equals("custom")) { + getLc().setPreferredFramerate(0); + } + setPreferredVideoSize(getPreferredVideoSize()); // Apply the bandwidth limit + } + + public String getPreferredVideoSize() { + //Core can only return video size (width and height), not the name + return getConfig().getString("video", "size", "qvga"); + } + + public void setPreferredVideoSize(String preferredVideoSize) { + if (getLc() == null) return; + getLc().setPreferredVideoSizeByName(preferredVideoSize); + } + + public int getPreferredVideoFps() { + if (getLc() == null) return 0; + return (int) getLc().getPreferredFramerate(); + } + + public void setPreferredVideoFps(int fps) { + if (getLc() == null) return; + getLc().setPreferredFramerate(fps); + } + + public int getBandwidthLimit() { + if (getLc() == null) return 0; + return getLc().getDownloadBandwidth(); + } + + public void setBandwidthLimit(int bandwidth) { + if (getLc() == null) return; + getLc().setUploadBandwidth(bandwidth); + getLc().setDownloadBandwidth(bandwidth); + } + // End of video settings + + // Call settings + public boolean useRfc2833Dtmfs() { + if (getLc() == null) return false; + return getLc().getUseRfc2833ForDtmf(); + } + + public void sendDtmfsAsRfc2833(boolean use) { + if (getLc() == null) return; + getLc().setUseRfc2833ForDtmf(use); + } + + public boolean useSipInfoDtmfs() { + if (getLc() == null) return false; + return getLc().getUseInfoForDtmf(); + } + + public void sendDTMFsAsSipInfo(boolean use) { + if (getLc() == null) return; + getLc().setUseInfoForDtmf(use); + } + + public int getIncTimeout() { + if (getLc() == null) return 0; + return getLc().getIncTimeout(); + } + + public void setIncTimeout(int timeout) { + if (getLc() == null) return; + getLc().setIncTimeout(timeout); + } + + public int getInCallTimeout() { + if (getLc() == null) return 0; + return getLc().getInCallTimeout(); + } + + public void setInCallTimeout(int timeout) { + if (getLc() == null) return; + getLc().setInCallTimeout(timeout); + } + + public String getVoiceMailUri() { + return getConfig().getString("app", "voice_mail", null); + } + + public void setVoiceMailUri(String uri) { + getConfig().setString("app", "voice_mail", uri); + } + + public boolean getNativeDialerCall() { + return getConfig().getBool("app", "native_dialer_call", false); + } + + public void setNativeDialerCall(boolean use) { + getConfig().setBool("app", "native_dialer_call", use); + } // End of call settings - // Network settings - public void setWifiOnlyEnabled(Boolean enable) { - getConfig().setBool("app", "wifi_only", enable); - } - - public boolean isWifiOnlyEnabled() { - return getConfig().getBool("app", "wifi_only", false); - } - - public void useRandomPort(boolean enabled) { - useRandomPort(enabled, true); - } - - public void useRandomPort(boolean enabled, boolean apply) { - getConfig().setBool("app", "random_port", enabled); - if (apply) { - if (enabled) { - setSipPort(LINPHONE_CORE_RANDOM_PORT); - } else { - setSipPort(5060); - } - } - } - - public boolean isUsingRandomPort() { - return getConfig().getBool("app", "random_port", true); - } - - public String getSipPort() { - if (getLc() == null) return null; - Transports transports = getLc().getTransports(); - int port; - if (transports.getUdpPort() > 0) - port = transports.getUdpPort(); - else - port = transports.getTcpPort(); - return String.valueOf(port); - } - - public void setSipPort(int port) { - if (getLc() == null) return; - Transports transports = getLc().getTransports(); - transports.setUdpPort(port); - transports.setTcpPort(port); - transports.setTlsPort(LINPHONE_CORE_RANDOM_PORT); - getLc().setTransports(transports); - } - - private NatPolicy getOrCreateNatPolicy() { - if (getLc() == null) return null; - NatPolicy nat = getLc().getNatPolicy(); - if (nat == null) { - nat = getLc().createNatPolicy(); - } - return nat; - } - - public String getStunServer() { - NatPolicy nat = getOrCreateNatPolicy(); - return nat.getStunServer(); - } - - public void setStunServer(String stun) { - if (getLc() == null) return; - NatPolicy nat = getOrCreateNatPolicy(); - nat.setStunServer(stun); - - if (stun != null && !stun.isEmpty()) { - } - getLc().setNatPolicy(nat); - } - - public void setIceEnabled(boolean enabled) { - if (getLc() == null) return; - NatPolicy nat = getOrCreateNatPolicy(); - nat.enableIce(enabled); - nat.enableStun(enabled); - getLc().setNatPolicy(nat); - } - - public void setTurnEnabled(boolean enabled) { - if (getLc() == null) return; - NatPolicy nat = getOrCreateNatPolicy(); - nat.enableTurn(enabled); - getLc().setNatPolicy(nat); - } - - public void setUpnpEnabled(boolean enabled) { - if (getLc() == null) return; - NatPolicy nat = getOrCreateNatPolicy(); - nat.enableUpnp(enabled); - getLc().setNatPolicy(nat); - } - - public boolean isUpnpEnabled() { - NatPolicy nat = getOrCreateNatPolicy(); - return nat.upnpEnabled(); - } - - public boolean isIceEnabled() { - NatPolicy nat = getOrCreateNatPolicy(); - return nat.iceEnabled(); - } - - public boolean isTurnEnabled() { - NatPolicy nat = getOrCreateNatPolicy(); - return nat.turnEnabled(); - } - - public String getTurnUsername() { - NatPolicy nat = getOrCreateNatPolicy(); - return nat.getStunServerUsername(); - } - - public void setTurnUsername(String username) { - if (getLc() == null) return; - NatPolicy nat = getOrCreateNatPolicy(); - AuthInfo authInfo = getLc().findAuthInfo(null, nat.getStunServerUsername(), null); - - if (authInfo != null) { - AuthInfo cloneAuthInfo = authInfo.clone(); - getLc().removeAuthInfo(authInfo); - cloneAuthInfo.setUsername(username); - cloneAuthInfo.setUserid(username); - getLc().addAuthInfo(cloneAuthInfo); - } else { - authInfo = Factory.instance().createAuthInfo(username, username, null, null, null, null); - getLc().addAuthInfo(authInfo); - } - nat.setStunServerUsername(username); - getLc().setNatPolicy(nat); - } - - public void setTurnPassword(String password) { - if (getLc() == null) return; - NatPolicy nat = getOrCreateNatPolicy(); - AuthInfo authInfo = getLc().findAuthInfo(null, nat.getStunServerUsername(), null); - - if (authInfo != null) { - AuthInfo cloneAuthInfo = authInfo.clone(); - getLc().removeAuthInfo(authInfo); - cloneAuthInfo.setPassword(password); - getLc().addAuthInfo(cloneAuthInfo); - } else { - authInfo = Factory.instance().createAuthInfo(nat.getStunServerUsername(), nat.getStunServerUsername(), password, null, null, null); - getLc().addAuthInfo(authInfo); - } - } - - public MediaEncryption getMediaEncryption() { - if (getLc() == null) return null; - return getLc().getMediaEncryption(); - } - - public void setMediaEncryption(MediaEncryption menc) { - if (getLc() == null) return; - if (menc == null) - return; - - getLc().setMediaEncryption(menc); - } - - public void setPushNotificationEnabled(boolean enable) { - getConfig().setBool("app", "push_notification", enable); - - Core lc = getLc(); - if (lc == null) { - return; - } - - if (enable) { - // Add push infos to exisiting proxy configs - String regId = getPushNotificationRegistrationID(); - String appId = getString(R.string.push_sender_id); - if (regId != null && lc.getProxyConfigList().length > 0) { - for (ProxyConfig lpc : lc.getProxyConfigList()) { - if (lpc == null) continue; - if (!lpc.isPushNotificationAllowed()) { - lpc.edit(); - lpc.setContactUriParameters(null); - lpc.done(); - if (lpc.getIdentityAddress() != null) - Log.d("Push notif infos removed from proxy config " + lpc.getIdentityAddress().asStringUriOnly()); - } else { - String contactInfos = "app-id=" + appId + ";pn-type=" + getString(R.string.push_type) + ";pn-tok=" + regId + ";pn-silent=1"; - String prevContactParams = lpc.getContactParameters(); - if (prevContactParams == null || prevContactParams.compareTo(contactInfos) != 0) { - lpc.edit(); - lpc.setContactUriParameters(contactInfos); - lpc.done(); - if (lpc.getIdentityAddress() != null) - Log.d("Push notif infos added to proxy config " + lpc.getIdentityAddress().asStringUriOnly()); - } - } - } - lc.refreshRegisters(); - } - } else { - if (lc.getProxyConfigList().length > 0) { - for (ProxyConfig lpc : lc.getProxyConfigList()) { - lpc.edit(); - lpc.setContactUriParameters(null); - lpc.done(); - if (lpc.getIdentityAddress() != null) - Log.d("Push notif infos removed from proxy config " + lpc.getIdentityAddress().asStringUriOnly()); - } - lc.refreshRegisters(); - } - } - } - - public boolean isPushNotificationEnabled() { - return getConfig().getBool("app", "push_notification", true); - } - - public void setPushNotificationRegistrationID(String regId) { - if (getConfig() == null) return; - getConfig().setString("app", "push_notification_regid", (regId != null) ? regId: ""); - setPushNotificationEnabled(isPushNotificationEnabled()); - } - - public String getPushNotificationRegistrationID() { - return getConfig().getString("app", "push_notification_regid", null); - } - - public void useIpv6(Boolean enable) { - if (getLc() == null) return; - getLc().enableIpv6(enable); - } - - public boolean isUsingIpv6() { - if (getLc() == null) return false; - return getLc().ipv6Enabled(); - } - // End of network settings - - // Advanced settings - public void setDebugEnabled(boolean enabled) { - getConfig().setBool("app", "debug", enabled); - LinphoneUtils.initLoggingService(enabled, mContext.getString(R.string.app_name)); - } - - public boolean isDebugEnabled() { - return getConfig().getBool("app", "debug", false); - } - - public void setJavaLogger(boolean enabled) { - getConfig().setBool("app", "java_logger", enabled); - LinphoneUtils.initLoggingService(isDebugEnabled(), mContext.getString(R.string.app_name)); - } - - public boolean useJavaLogger() { - return getConfig().getBool("app", "java_logger", false); - } - - public void setBackgroundModeEnabled(boolean enabled) { - getConfig().setBool("app", "background_mode", enabled); - } - - public boolean isBackgroundModeEnabled() { - return getConfig().getBool("app", "background_mode", true); - } - - public boolean isAutoStartEnabled() { - return getConfig().getBool("app", "auto_start", false); - } - - public void setAutoStart(boolean autoStartEnabled) { - getConfig().setBool("app", "auto_start", autoStartEnabled); - } - - public String getSharingPictureServerUrl() { - if (getLc() == null) return null; - return getLc().getFileTransferServer(); - } - - public void setSharingPictureServerUrl(String url) { - if (getLc() == null) return; - getLc().setFileTransferServer(url); - } - - public void setRemoteProvisioningUrl(String url) { - if (getLc() == null) return; - if (url != null && url.length() == 0) { - url = null; - } - getLc().setProvisioningUri(url); - } - - public String getRemoteProvisioningUrl() { - if (getLc() == null) return null; - return getLc().getProvisioningUri(); - } - - public void setDefaultDisplayName(String displayName) { - if (getLc() == null) return; - Address primary = getLc().getPrimaryContactParsed(); - primary.setDisplayName(displayName); - getLc().setPrimaryContact(primary.asString()); - } - - public String getDefaultDisplayName() { - if (getLc() == null) return null; - return getLc().getPrimaryContactParsed().getDisplayName(); - } - - public void setDefaultUsername(String username) { - if (getLc() == null) return; - Address primary = getLc().getPrimaryContactParsed(); - primary.setUsername(username); - getLc().setPrimaryContact(primary.asString()); - } - - public String getDefaultUsername() { - if (getLc() == null) return null; - return getLc().getPrimaryContactParsed().getUsername(); - } - // End of advanced settings - - // Tunnel settings - private TunnelConfig tunnelConfig = null; - - public TunnelConfig getTunnelConfig() { - if (getLc() == null) return null; - if(getLc().tunnelAvailable()) { - Tunnel tunnel = getLc().getTunnel(); - if (tunnelConfig == null) { - TunnelConfig servers[] = tunnel.getServers(); - if(servers.length > 0) { - tunnelConfig = servers[0]; - } else { - tunnelConfig = Factory.instance().createTunnelConfig(); - } - } - return tunnelConfig; - } else { - return null; - } - } - - public String getTunnelHost() { - TunnelConfig config = getTunnelConfig(); - if(config != null) { - return config.getHost(); - } else { - return null; - } - } - - public void setTunnelHost(String host) { - TunnelConfig config = getTunnelConfig(); - if(config != null) { - config.setHost(host); - LinphoneManager.getInstance().initTunnelFromConf(); - } - } - - public int getTunnelPort() { - TunnelConfig config = getTunnelConfig(); - if(config != null) { - return config.getPort(); - } else { - return -1; - } - } - - public void setTunnelPort(int port) { - TunnelConfig config = getTunnelConfig(); - if(config != null) { - config.setPort(port); - LinphoneManager.getInstance().initTunnelFromConf(); - } - } - - public String getTunnelMode() { - return getConfig().getString("app", "tunnel", null); - } - - public void setTunnelMode(String mode) { - getConfig().setString("app", "tunnel", mode); - LinphoneManager.getInstance().initTunnelFromConf(); - } - // End of tunnel settings - - public boolean isProvisioningLoginViewEnabled() { - - return (getConfig() != null) ? getConfig().getBool("app", "show_login_view", false) : false; - } - - public void disableProvisioningLoginView() { - if (isProvisioningLoginViewEnabled()) { // Only do it if it was previously enabled - getConfig().setBool("app", "show_login_view", false); - } else { - Log.w("Remote provisioning login view wasn't enabled, ignoring"); - } - } - - public void firstRemoteProvisioningSuccessful() { - getConfig().setBool("app", "first_remote_provisioning", false); - } - - public boolean isFirstRemoteProvisioning() { - return getConfig().getBool("app", "first_remote_provisioning", true); - } - - public boolean adaptiveRateControlEnabled() { - if (getLc() == null) return false; - return getLc().adaptiveRateControlEnabled(); - } - - public void enableAdaptiveRateControl(boolean enabled) { - if (getLc() == null) return; - getLc().enableAdaptiveRateControl(enabled); - } - - public int getCodecBitrateLimit() { - return getConfig().getInt("audio", "codec_bitrate_limit", 36); - } - - public void setCodecBitrateLimit(int bitrate) { - getConfig().setInt("audio", "codec_bitrate_limit", bitrate); - } - - public void contactsMigrationDone(){ - getConfig().setBool("app", "contacts_migration_done", true); - } - - public boolean isContactsMigrationDone(){ - return getConfig().getBool("app", "contacts_migration_done", false); - } - - public String getInAppPurchaseValidatingServerUrl() { - return getConfig().getString("in-app-purchase", "server_url", null); - } - - public Purchasable getInAppPurchasedItem() { - String id = getConfig().getString("in-app-purchase", "purchase_item_id", null); - String payload = getConfig().getString("in-app-purchase", "purchase_item_payload", null); - String signature = getConfig().getString("in-app-purchase", "purchase_item_signature", null); - String username = getConfig().getString("in-app-purchase", "purchase_item_username", null); - - Purchasable item = new Purchasable(id).setPayloadAndSignature(payload, signature).setUserData(username); - return item; - } - - public void setInAppPurchasedItem(Purchasable item) { - if (item == null) - return; - - getConfig().setString("in-app-purchase", "purchase_item_id", item.getId()); - getConfig().setString("in-app-purchase", "purchase_item_payload", item.getPayload()); - getConfig().setString("in-app-purchase", "purchase_item_signature", item.getPayloadSignature()); - getConfig().setString("in-app-purchase", "purchase_item_username", item.getUserData()); - } - - public ArrayList getInAppPurchasables() { - ArrayList purchasables = new ArrayList(); - String list = getConfig().getString("in-app-purchase", "purchasable_items_ids", null); - if (list != null) { - for(String purchasable : list.split(";")) { - if (purchasable.length() > 0) { - purchasables.add(purchasable); - } - } - } - return purchasables; - } - - public String getXmlrpcUrl(){ - return getConfig().getString("assistant", "xmlrpc_url", null); - } - - public void setXmlrpcUrl(String url){ - getConfig().setString("assistant", "xmlrpc_url", url); - } - - public String getInappPopupTime(){ - return getConfig().getString("app", "inapp_popup_time", null); - } - - public void setInappPopupTime(String date){ - getConfig().setString("app", "inapp_popup_time", date); - } - - public void setLinkPopupTime(String date){ - getConfig().setString("app", "link_popup_time", date); - } - - public String getLinkPopupTime(){ - return getConfig().getString("app", "link_popup_time", null); - } - - public String getXmlRpcServerUrl() { - return getConfig().getString("app", "server_url", null); - } - - public String getDebugPopupAddress(){ - return getConfig().getString("app", "debug_popup_magic", null); - } - - public String getActivityToLaunchOnIncomingReceived() { - return getConfig().getString("app", "incoming_call_activity", "org.linphone.activities.LinphoneActivity"); - } - - public void setActivityToLaunchOnIncomingReceived(String name) { - getConfig().setString("app", "incoming_call_activity", name); - } - - public boolean getServiceNotificationVisibility() { - return getConfig().getBool("app", "show_service_notification", false); - } - - public void setServiceNotificationVisibility(boolean enable) { - getConfig().setBool("app", "show_service_notification", enable); - } - - public boolean isOverlayEnabled() { - return getConfig().getBool("app", "display_overlay", false); - } - - public void enableOverlay(boolean enable) { - getConfig().setBool("app", "display_overlay", enable); - } - - public LimeState limeEnabled() { - if (getLc() == null) return LimeState.Disabled; - return getLc().limeEnabled(); - } - - public void enableLime(LimeState lime) { - if (getLc() == null) return; - getLc().enableLime(lime); - } - - public boolean firstTimeAskingForPermission(String permission) { - return firstTimeAskingForPermission(permission, true); - } - - public boolean firstTimeAskingForPermission(String permission, boolean toggle) { - boolean firstTime = getConfig().getBool("app", permission, true); - if (toggle) { - permissionHasBeenAsked(permission); - } - return firstTime; - } - - public void permissionHasBeenAsked(String permission) { - getConfig().setBool("app", permission, false); - } - - public boolean isDeviceRingtoneEnabled() { - int readExternalStorage = mContext.getPackageManager().checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE, mContext.getPackageName()); - return getConfig().getBool("app", "device_ringtone", true) && readExternalStorage == PackageManager.PERMISSION_GRANTED; - } - - public void enableDeviceRingtone(boolean enable) { - getConfig().setBool("app", "device_ringtone", enable); - } - - public boolean isBisFeatureEnabled() { - return getConfig().getBool("app", "bis_feature", true); - } - - public void enableBisFeature(boolean enable) { - getConfig().setBool("app", "bis_feature", enable); - } - - public boolean isAutoAnswerEnabled() { - return getConfig().getBool("app", "auto_answer", false); - } - - public void enableAutoAnswer(boolean enable) { - getConfig().setBool("app", "auto_answer", enable); - } - - public void setAutoAnswerTime(int time) { - getConfig().setInt("app", "auto_answer_delay", time); - } - - public int getAutoAnswerTime() { - return getConfig().getInt("app", "auto_answer_delay", 0); - } - - public int getCodeLength(){ - return getConfig().getInt("app", "activation_code_length", 0); - } - - public void disableFriendsStorage() { - getConfig().setBool("misc", "store_friends", false); - } - - public void enableFriendsStorage() { - getConfig().setBool("misc", "store_friends", true); - } - - public boolean isFriendsStorageEnabled() { - return getConfig().getBool("misc", "store_friends", true); - } - - public boolean useBasicChatRoomFor1To1() { - return getConfig().getBool("app", "prefer_basic_chat_room", false); - } + // Network settings + public void setWifiOnlyEnabled(Boolean enable) { + getConfig().setBool("app", "wifi_only", enable); + } + + public boolean isWifiOnlyEnabled() { + return getConfig().getBool("app", "wifi_only", false); + } + + public void useRandomPort(boolean enabled) { + useRandomPort(enabled, true); + } + + public void useRandomPort(boolean enabled, boolean apply) { + getConfig().setBool("app", "random_port", enabled); + if (apply) { + if (enabled) { + setSipPort(LINPHONE_CORE_RANDOM_PORT); + } else { + setSipPort(5060); + } + } + } + + public boolean isUsingRandomPort() { + return getConfig().getBool("app", "random_port", true); + } + + public String getSipPort() { + if (getLc() == null) return null; + Transports transports = getLc().getTransports(); + int port; + if (transports.getUdpPort() > 0) + port = transports.getUdpPort(); + else + port = transports.getTcpPort(); + return String.valueOf(port); + } + + public void setSipPort(int port) { + if (getLc() == null) return; + Transports transports = getLc().getTransports(); + transports.setUdpPort(port); + transports.setTcpPort(port); + transports.setTlsPort(LINPHONE_CORE_RANDOM_PORT); + getLc().setTransports(transports); + } + + private NatPolicy getOrCreateNatPolicy() { + if (getLc() == null) return null; + NatPolicy nat = getLc().getNatPolicy(); + if (nat == null) { + nat = getLc().createNatPolicy(); + } + return nat; + } + + public String getStunServer() { + NatPolicy nat = getOrCreateNatPolicy(); + return nat.getStunServer(); + } + + public void setStunServer(String stun) { + if (getLc() == null) return; + NatPolicy nat = getOrCreateNatPolicy(); + nat.setStunServer(stun); + + if (stun != null && !stun.isEmpty()) { + } + getLc().setNatPolicy(nat); + } + + public void setIceEnabled(boolean enabled) { + if (getLc() == null) return; + NatPolicy nat = getOrCreateNatPolicy(); + nat.enableIce(enabled); + nat.enableStun(enabled); + getLc().setNatPolicy(nat); + } + + public void setTurnEnabled(boolean enabled) { + if (getLc() == null) return; + NatPolicy nat = getOrCreateNatPolicy(); + nat.enableTurn(enabled); + getLc().setNatPolicy(nat); + } + + public void setUpnpEnabled(boolean enabled) { + if (getLc() == null) return; + NatPolicy nat = getOrCreateNatPolicy(); + nat.enableUpnp(enabled); + getLc().setNatPolicy(nat); + } + + public boolean isUpnpEnabled() { + NatPolicy nat = getOrCreateNatPolicy(); + return nat.upnpEnabled(); + } + + public boolean isIceEnabled() { + NatPolicy nat = getOrCreateNatPolicy(); + return nat.iceEnabled(); + } + + public boolean isTurnEnabled() { + NatPolicy nat = getOrCreateNatPolicy(); + return nat.turnEnabled(); + } + + public String getTurnUsername() { + NatPolicy nat = getOrCreateNatPolicy(); + return nat.getStunServerUsername(); + } + + public void setTurnUsername(String username) { + if (getLc() == null) return; + NatPolicy nat = getOrCreateNatPolicy(); + AuthInfo authInfo = getLc().findAuthInfo(null, nat.getStunServerUsername(), null); + + if (authInfo != null) { + AuthInfo cloneAuthInfo = authInfo.clone(); + getLc().removeAuthInfo(authInfo); + cloneAuthInfo.setUsername(username); + cloneAuthInfo.setUserid(username); + getLc().addAuthInfo(cloneAuthInfo); + } else { + authInfo = Factory.instance().createAuthInfo(username, username, null, null, null, null); + getLc().addAuthInfo(authInfo); + } + nat.setStunServerUsername(username); + getLc().setNatPolicy(nat); + } + + public void setTurnPassword(String password) { + if (getLc() == null) return; + NatPolicy nat = getOrCreateNatPolicy(); + AuthInfo authInfo = getLc().findAuthInfo(null, nat.getStunServerUsername(), null); + + if (authInfo != null) { + AuthInfo cloneAuthInfo = authInfo.clone(); + getLc().removeAuthInfo(authInfo); + cloneAuthInfo.setPassword(password); + getLc().addAuthInfo(cloneAuthInfo); + } else { + authInfo = Factory.instance().createAuthInfo(nat.getStunServerUsername(), nat.getStunServerUsername(), password, null, null, null); + getLc().addAuthInfo(authInfo); + } + } + + public MediaEncryption getMediaEncryption() { + if (getLc() == null) return null; + return getLc().getMediaEncryption(); + } + + public void setMediaEncryption(MediaEncryption menc) { + if (getLc() == null) return; + if (menc == null) + return; + + getLc().setMediaEncryption(menc); + } + + public void setPushNotificationEnabled(boolean enable) { + getConfig().setBool("app", "push_notification", enable); + + Core lc = getLc(); + if (lc == null) { + return; + } + + if (enable) { + // Add push infos to exisiting proxy configs + String regId = getPushNotificationRegistrationID(); + String appId = getString(R.string.push_sender_id); + if (regId != null && lc.getProxyConfigList().length > 0) { + for (ProxyConfig lpc : lc.getProxyConfigList()) { + if (lpc == null) continue; + if (!lpc.isPushNotificationAllowed()) { + lpc.edit(); + lpc.setContactUriParameters(null); + lpc.done(); + if (lpc.getIdentityAddress() != null) + Log.d("Push notif infos removed from proxy config " + lpc.getIdentityAddress().asStringUriOnly()); + } else { + String contactInfos = "app-id=" + appId + ";pn-type=" + getString(R.string.push_type) + ";pn-tok=" + regId + ";pn-silent=1"; + String prevContactParams = lpc.getContactParameters(); + if (prevContactParams == null || prevContactParams.compareTo(contactInfos) != 0) { + lpc.edit(); + lpc.setContactUriParameters(contactInfos); + lpc.done(); + if (lpc.getIdentityAddress() != null) + Log.d("Push notif infos added to proxy config " + lpc.getIdentityAddress().asStringUriOnly()); + } + } + } + lc.refreshRegisters(); + } + } else { + if (lc.getProxyConfigList().length > 0) { + for (ProxyConfig lpc : lc.getProxyConfigList()) { + lpc.edit(); + lpc.setContactUriParameters(null); + lpc.done(); + if (lpc.getIdentityAddress() != null) + Log.d("Push notif infos removed from proxy config " + lpc.getIdentityAddress().asStringUriOnly()); + } + lc.refreshRegisters(); + } + } + } + + public boolean isPushNotificationEnabled() { + return getConfig().getBool("app", "push_notification", true); + } + + public void setPushNotificationRegistrationID(String regId) { + if (getConfig() == null) return; + getConfig().setString("app", "push_notification_regid", (regId != null) ? regId : ""); + setPushNotificationEnabled(isPushNotificationEnabled()); + } + + public String getPushNotificationRegistrationID() { + return getConfig().getString("app", "push_notification_regid", null); + } + + public void useIpv6(Boolean enable) { + if (getLc() == null) return; + getLc().enableIpv6(enable); + } + + public boolean isUsingIpv6() { + if (getLc() == null) return false; + return getLc().ipv6Enabled(); + } + // End of network settings + + // Advanced settings + public void setDebugEnabled(boolean enabled) { + getConfig().setBool("app", "debug", enabled); + LinphoneUtils.initLoggingService(enabled, mContext.getString(R.string.app_name)); + } + + public boolean isDebugEnabled() { + return getConfig().getBool("app", "debug", false); + } + + public void setJavaLogger(boolean enabled) { + getConfig().setBool("app", "java_logger", enabled); + LinphoneUtils.initLoggingService(isDebugEnabled(), mContext.getString(R.string.app_name)); + } + + public boolean useJavaLogger() { + return getConfig().getBool("app", "java_logger", false); + } + + public void setBackgroundModeEnabled(boolean enabled) { + getConfig().setBool("app", "background_mode", enabled); + } + + public boolean isBackgroundModeEnabled() { + return getConfig().getBool("app", "background_mode", true); + } + + public boolean isAutoStartEnabled() { + return getConfig().getBool("app", "auto_start", false); + } + + public void setAutoStart(boolean autoStartEnabled) { + getConfig().setBool("app", "auto_start", autoStartEnabled); + } + + public String getSharingPictureServerUrl() { + if (getLc() == null) return null; + return getLc().getFileTransferServer(); + } + + public void setSharingPictureServerUrl(String url) { + if (getLc() == null) return; + getLc().setFileTransferServer(url); + } + + public void setRemoteProvisioningUrl(String url) { + if (getLc() == null) return; + if (url != null && url.length() == 0) { + url = null; + } + getLc().setProvisioningUri(url); + } + + public String getRemoteProvisioningUrl() { + if (getLc() == null) return null; + return getLc().getProvisioningUri(); + } + + public void setDefaultDisplayName(String displayName) { + if (getLc() == null) return; + Address primary = getLc().getPrimaryContactParsed(); + primary.setDisplayName(displayName); + getLc().setPrimaryContact(primary.asString()); + } + + public String getDefaultDisplayName() { + if (getLc() == null) return null; + return getLc().getPrimaryContactParsed().getDisplayName(); + } + + public void setDefaultUsername(String username) { + if (getLc() == null) return; + Address primary = getLc().getPrimaryContactParsed(); + primary.setUsername(username); + getLc().setPrimaryContact(primary.asString()); + } + + public String getDefaultUsername() { + if (getLc() == null) return null; + return getLc().getPrimaryContactParsed().getUsername(); + } + // End of advanced settings + + // Tunnel settings + private TunnelConfig tunnelConfig = null; + + public TunnelConfig getTunnelConfig() { + if (getLc() == null) return null; + if (getLc().tunnelAvailable()) { + Tunnel tunnel = getLc().getTunnel(); + if (tunnelConfig == null) { + TunnelConfig servers[] = tunnel.getServers(); + if (servers.length > 0) { + tunnelConfig = servers[0]; + } else { + tunnelConfig = Factory.instance().createTunnelConfig(); + } + } + return tunnelConfig; + } else { + return null; + } + } + + public String getTunnelHost() { + TunnelConfig config = getTunnelConfig(); + if (config != null) { + return config.getHost(); + } else { + return null; + } + } + + public void setTunnelHost(String host) { + TunnelConfig config = getTunnelConfig(); + if (config != null) { + config.setHost(host); + LinphoneManager.getInstance().initTunnelFromConf(); + } + } + + public int getTunnelPort() { + TunnelConfig config = getTunnelConfig(); + if (config != null) { + return config.getPort(); + } else { + return -1; + } + } + + public void setTunnelPort(int port) { + TunnelConfig config = getTunnelConfig(); + if (config != null) { + config.setPort(port); + LinphoneManager.getInstance().initTunnelFromConf(); + } + } + + public String getTunnelMode() { + return getConfig().getString("app", "tunnel", null); + } + + public void setTunnelMode(String mode) { + getConfig().setString("app", "tunnel", mode); + LinphoneManager.getInstance().initTunnelFromConf(); + } + // End of tunnel settings + + public boolean isProvisioningLoginViewEnabled() { + + return (getConfig() != null) ? getConfig().getBool("app", "show_login_view", false) : false; + } + + public void disableProvisioningLoginView() { + if (isProvisioningLoginViewEnabled()) { // Only do it if it was previously enabled + getConfig().setBool("app", "show_login_view", false); + } else { + Log.w("Remote provisioning login view wasn't enabled, ignoring"); + } + } + + public void firstRemoteProvisioningSuccessful() { + getConfig().setBool("app", "first_remote_provisioning", false); + } + + public boolean isFirstRemoteProvisioning() { + return getConfig().getBool("app", "first_remote_provisioning", true); + } + + public boolean adaptiveRateControlEnabled() { + if (getLc() == null) return false; + return getLc().adaptiveRateControlEnabled(); + } + + public void enableAdaptiveRateControl(boolean enabled) { + if (getLc() == null) return; + getLc().enableAdaptiveRateControl(enabled); + } + + public int getCodecBitrateLimit() { + return getConfig().getInt("audio", "codec_bitrate_limit", 36); + } + + public void setCodecBitrateLimit(int bitrate) { + getConfig().setInt("audio", "codec_bitrate_limit", bitrate); + } + + public void contactsMigrationDone() { + getConfig().setBool("app", "contacts_migration_done", true); + } + + public boolean isContactsMigrationDone() { + return getConfig().getBool("app", "contacts_migration_done", false); + } + + public String getInAppPurchaseValidatingServerUrl() { + return getConfig().getString("in-app-purchase", "server_url", null); + } + + public Purchasable getInAppPurchasedItem() { + String id = getConfig().getString("in-app-purchase", "purchase_item_id", null); + String payload = getConfig().getString("in-app-purchase", "purchase_item_payload", null); + String signature = getConfig().getString("in-app-purchase", "purchase_item_signature", null); + String username = getConfig().getString("in-app-purchase", "purchase_item_username", null); + + Purchasable item = new Purchasable(id).setPayloadAndSignature(payload, signature).setUserData(username); + return item; + } + + public void setInAppPurchasedItem(Purchasable item) { + if (item == null) + return; + + getConfig().setString("in-app-purchase", "purchase_item_id", item.getId()); + getConfig().setString("in-app-purchase", "purchase_item_payload", item.getPayload()); + getConfig().setString("in-app-purchase", "purchase_item_signature", item.getPayloadSignature()); + getConfig().setString("in-app-purchase", "purchase_item_username", item.getUserData()); + } + + public ArrayList getInAppPurchasables() { + ArrayList purchasables = new ArrayList(); + String list = getConfig().getString("in-app-purchase", "purchasable_items_ids", null); + if (list != null) { + for (String purchasable : list.split(";")) { + if (purchasable.length() > 0) { + purchasables.add(purchasable); + } + } + } + return purchasables; + } + + public String getXmlrpcUrl() { + return getConfig().getString("assistant", "xmlrpc_url", null); + } + + public void setXmlrpcUrl(String url) { + getConfig().setString("assistant", "xmlrpc_url", url); + } + + public String getInappPopupTime() { + return getConfig().getString("app", "inapp_popup_time", null); + } + + public void setInappPopupTime(String date) { + getConfig().setString("app", "inapp_popup_time", date); + } + + public void setLinkPopupTime(String date) { + getConfig().setString("app", "link_popup_time", date); + } + + public String getLinkPopupTime() { + return getConfig().getString("app", "link_popup_time", null); + } + + public String getXmlRpcServerUrl() { + return getConfig().getString("app", "server_url", null); + } + + public String getDebugPopupAddress() { + return getConfig().getString("app", "debug_popup_magic", null); + } + + public String getActivityToLaunchOnIncomingReceived() { + return getConfig().getString("app", "incoming_call_activity", "org.linphone.activities.LinphoneActivity"); + } + + public void setActivityToLaunchOnIncomingReceived(String name) { + getConfig().setString("app", "incoming_call_activity", name); + } + + public boolean getServiceNotificationVisibility() { + return getConfig().getBool("app", "show_service_notification", false); + } + + public void setServiceNotificationVisibility(boolean enable) { + getConfig().setBool("app", "show_service_notification", enable); + } + + public boolean isOverlayEnabled() { + return getConfig().getBool("app", "display_overlay", false); + } + + public void enableOverlay(boolean enable) { + getConfig().setBool("app", "display_overlay", enable); + } + + public LimeState limeEnabled() { + if (getLc() == null) return LimeState.Disabled; + return getLc().limeEnabled(); + } + + public void enableLime(LimeState lime) { + if (getLc() == null) return; + getLc().enableLime(lime); + } + + public boolean firstTimeAskingForPermission(String permission) { + return firstTimeAskingForPermission(permission, true); + } + + public boolean firstTimeAskingForPermission(String permission, boolean toggle) { + boolean firstTime = getConfig().getBool("app", permission, true); + if (toggle) { + permissionHasBeenAsked(permission); + } + return firstTime; + } + + public void permissionHasBeenAsked(String permission) { + getConfig().setBool("app", permission, false); + } + + public boolean isDeviceRingtoneEnabled() { + int readExternalStorage = mContext.getPackageManager().checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE, mContext.getPackageName()); + return getConfig().getBool("app", "device_ringtone", true) && readExternalStorage == PackageManager.PERMISSION_GRANTED; + } + + public void enableDeviceRingtone(boolean enable) { + getConfig().setBool("app", "device_ringtone", enable); + } + + public boolean isBisFeatureEnabled() { + return getConfig().getBool("app", "bis_feature", true); + } + + public void enableBisFeature(boolean enable) { + getConfig().setBool("app", "bis_feature", enable); + } + + public boolean isAutoAnswerEnabled() { + return getConfig().getBool("app", "auto_answer", false); + } + + public void enableAutoAnswer(boolean enable) { + getConfig().setBool("app", "auto_answer", enable); + } + + public void setAutoAnswerTime(int time) { + getConfig().setInt("app", "auto_answer_delay", time); + } + + public int getAutoAnswerTime() { + return getConfig().getInt("app", "auto_answer_delay", 0); + } + + public int getCodeLength() { + return getConfig().getInt("app", "activation_code_length", 0); + } + + public void disableFriendsStorage() { + getConfig().setBool("misc", "store_friends", false); + } + + public void enableFriendsStorage() { + getConfig().setBool("misc", "store_friends", true); + } + + public boolean isFriendsStorageEnabled() { + return getConfig().getBool("misc", "store_friends", true); + } + + public boolean useBasicChatRoomFor1To1() { + return getConfig().getBool("app", "prefer_basic_chat_room", false); + } } diff --git a/src/android/org/linphone/LinphoneService.java b/src/android/org/linphone/LinphoneService.java index f88e732e5..931a4a5cc 100644 --- a/src/android/org/linphone/LinphoneService.java +++ b/src/android/org/linphone/LinphoneService.java @@ -19,29 +19,6 @@ along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.HashMap; - -import org.linphone.activities.LinphoneActivity; -import org.linphone.compatibility.Compatibility; -import org.linphone.contacts.ContactsManager; -import org.linphone.contacts.LinphoneContact; -import org.linphone.core.Address; -import org.linphone.core.Call; -import org.linphone.core.Call.State; -import org.linphone.core.Core; -import org.linphone.core.GlobalState; -import org.linphone.core.RegistrationState; -import org.linphone.core.Factory; -import org.linphone.core.CoreListenerStub; -import org.linphone.core.ProxyConfig; -import org.linphone.mediastream.Log; -import org.linphone.mediastream.Version; -import org.linphone.receivers.KeepAliveReceiver; -import org.linphone.ui.LinphoneOverlay; - import android.annotation.TargetApi; import android.app.Activity; import android.app.AlarmManager; @@ -66,9 +43,32 @@ import android.provider.ContactsContract; import android.provider.MediaStore; import android.view.WindowManager; +import org.linphone.activities.LinphoneActivity; +import org.linphone.compatibility.Compatibility; +import org.linphone.contacts.ContactsManager; +import org.linphone.contacts.LinphoneContact; +import org.linphone.core.Address; +import org.linphone.core.Call; +import org.linphone.core.Call.State; +import org.linphone.core.Core; +import org.linphone.core.CoreListenerStub; +import org.linphone.core.Factory; +import org.linphone.core.GlobalState; +import org.linphone.core.ProxyConfig; +import org.linphone.core.RegistrationState; +import org.linphone.mediastream.Log; +import org.linphone.mediastream.Version; +import org.linphone.receivers.KeepAliveReceiver; +import org.linphone.ui.LinphoneOverlay; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; + /** * Linphone service, reacting to Incoming calls, ...
- * + *

* Roles include: