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:
* - Starting C liblinphone
@@ -137,211 +136,212 @@ import static android.media.AudioManager.STREAM_VOICE_CALL;
* - Calling Linphone android service listener methods
* - Interacting from Android GUI/service with low level SIP stuff/
*
- *
+ *
* 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:
* - Initializing LinphoneManager
* - Starting C libLinphone through LinphoneManager
@@ -76,823 +76,829 @@ import android.view.WindowManager;
* - Delegating GUI state change actions to GUI listener
*/
public final class LinphoneService extends Service {
- /* Listener needs to be implemented in the Service as it calls
- * setLatestEventInfo and startActivity() which needs a context.
- */
- public static final String START_LINPHONE_LOGS = " ==== Phone information dump ====";
- public static final int IC_LEVEL_ORANGE=0;
+ /* Listener needs to be implemented in the Service as it calls
+ * setLatestEventInfo and startActivity() which needs a context.
+ */
+ public static final String START_LINPHONE_LOGS = " ==== Phone information dump ====";
+ public static final int IC_LEVEL_ORANGE = 0;
/*private static final int IC_LEVEL_GREEN=1;
private static final int IC_LEVEL_RED=2;*/
- //public static final int IC_LEVEL_OFFLINE=3;
+ //public static final int IC_LEVEL_OFFLINE=3;
- private static LinphoneService instance;
+ private static LinphoneService instance;
- private final static int NOTIF_ID=1;
- private final static int INCALL_NOTIF_ID=2;
- private final static int CUSTOM_NOTIF_ID=4;
- private final static int MISSED_NOTIF_ID=5;
- private final static int SAS_NOTIF_ID=6;
+ private final static int NOTIF_ID = 1;
+ private final static int INCALL_NOTIF_ID = 2;
+ private final static int CUSTOM_NOTIF_ID = 4;
+ private final static int MISSED_NOTIF_ID = 5;
+ private final static int SAS_NOTIF_ID = 6;
- public static boolean isReady() {
- return instance != null && instance.mTestDelayElapsed;
- }
+ public static boolean isReady() {
+ return instance != null && instance.mTestDelayElapsed;
+ }
- /**
- * @throws RuntimeException service not instantiated
- */
- public static LinphoneService instance() {
- if (isReady()) return instance;
+ /**
+ * @throws RuntimeException service not instantiated
+ */
+ public static LinphoneService instance() {
+ if (isReady()) return instance;
- throw new RuntimeException("LinphoneService not instantiated yet");
- }
+ throw new RuntimeException("LinphoneService not instantiated yet");
+ }
- public Handler mHandler = new Handler();
+ public Handler mHandler = new Handler();
-// private boolean mTestDelayElapsed; // add a timer for testing
- private boolean mTestDelayElapsed = true; // no timer
- private NotificationManager mNM;
+ // private boolean mTestDelayElapsed; // add a timer for testing
+ private boolean mTestDelayElapsed = true; // no timer
+ private NotificationManager mNM;
- private Notification mNotif;
- private Notification mIncallNotif;
- private Notification mCustomNotif;
- private Notification mSasNotif;
- private PendingIntent mNotifContentIntent;
- private String mNotificationTitle;
- private boolean mDisableRegistrationStatus;
- private CoreListenerStub mListener;
- public static int notifcationsPriority = (Version.sdkAboveOrEqual(Version.API16_JELLY_BEAN_41) ? Notification.PRIORITY_MIN : 0);
- private WindowManager mWindowManager;
- private LinphoneOverlay mOverlay;
- private Application.ActivityLifecycleCallbacks activityCallbacks;
+ private Notification mNotif;
+ private Notification mIncallNotif;
+ private Notification mCustomNotif;
+ private Notification mSasNotif;
+ private PendingIntent mNotifContentIntent;
+ private String mNotificationTitle;
+ private boolean mDisableRegistrationStatus;
+ private CoreListenerStub mListener;
+ public static int notifcationsPriority = (Version.sdkAboveOrEqual(Version.API16_JELLY_BEAN_41) ? Notification.PRIORITY_MIN : 0);
+ private WindowManager mWindowManager;
+ private LinphoneOverlay mOverlay;
+ private Application.ActivityLifecycleCallbacks activityCallbacks;
- private class Notified {
- int notificationId;
- int numberOfUnreadMessage;
- }
+ private class Notified {
+ int notificationId;
+ int numberOfUnreadMessage;
+ }
- private HashMap mChatNotifMap;
- private int mLastNotificationId;
+ private HashMap mChatNotifMap;
+ private int mLastNotificationId;
- public void setCurrentlyDisplayedChatRoom(String address) {
- if (address != null) {
- resetMessageNotifCount(address);
- }
- }
+ public void setCurrentlyDisplayedChatRoom(String address) {
+ if (address != null) {
+ resetMessageNotifCount(address);
+ }
+ }
- private void resetMessageNotifCount(String address) {
- Notified notif = mChatNotifMap.get(address);
- if (notif != null) {
- notif.numberOfUnreadMessage = 0;
- mNM.cancel(notif.notificationId);
- }
- }
+ private void resetMessageNotifCount(String address) {
+ Notified notif = mChatNotifMap.get(address);
+ if (notif != null) {
+ notif.numberOfUnreadMessage = 0;
+ mNM.cancel(notif.notificationId);
+ }
+ }
- /*Believe me or not, but knowing the application visibility state on Android is a nightmare.
- After two days of hard work I ended with the following class, that does the job more or less reliabily.
- */
- class ActivityMonitor implements Application.ActivityLifecycleCallbacks {
- private ArrayList activities = new ArrayList<>();
- private boolean mActive = false;
- private int mRunningActivities = 0;
+ /*Believe me or not, but knowing the application visibility state on Android is a nightmare.
+ After two days of hard work I ended with the following class, that does the job more or less reliabily.
+ */
+ class ActivityMonitor implements Application.ActivityLifecycleCallbacks {
+ private ArrayList activities = new ArrayList<>();
+ private boolean mActive = false;
+ private int mRunningActivities = 0;
- class InactivityChecker implements Runnable {
- private boolean isCanceled;
+ class InactivityChecker implements Runnable {
+ private boolean isCanceled;
- public void cancel() {
- isCanceled = true;
- }
+ public void cancel() {
+ isCanceled = true;
+ }
- @Override
- public void run() {
- synchronized(LinphoneService.this) {
- if (!isCanceled) {
- if (ActivityMonitor.this.mRunningActivities == 0 && mActive) {
- mActive = false;
- LinphoneService.this.onBackgroundMode();
- }
- }
- }
- }
- };
+ @Override
+ public void run() {
+ synchronized (LinphoneService.this) {
+ if (!isCanceled) {
+ if (ActivityMonitor.this.mRunningActivities == 0 && mActive) {
+ mActive = false;
+ LinphoneService.this.onBackgroundMode();
+ }
+ }
+ }
+ }
+ }
- private InactivityChecker mLastChecker;
+ ;
- @Override
- public synchronized void onActivityCreated(Activity activity, Bundle savedInstanceState) {
- Log.i("Activity created:" + activity);
- if (!activities.contains(activity))
- activities.add(activity);
- }
+ private InactivityChecker mLastChecker;
- @Override
- public void onActivityStarted(Activity activity) {
- Log.i("Activity started:" + activity);
- }
+ @Override
+ public synchronized void onActivityCreated(Activity activity, Bundle savedInstanceState) {
+ Log.i("Activity created:" + activity);
+ if (!activities.contains(activity))
+ activities.add(activity);
+ }
- @Override
- public synchronized void onActivityResumed(Activity activity) {
- Log.i("Activity resumed:" + activity);
- if (activities.contains(activity)) {
- mRunningActivities++;
- Log.i("runningActivities=" + mRunningActivities);
- checkActivity();
- }
+ @Override
+ public void onActivityStarted(Activity activity) {
+ Log.i("Activity started:" + activity);
+ }
- }
+ @Override
+ public synchronized void onActivityResumed(Activity activity) {
+ Log.i("Activity resumed:" + activity);
+ if (activities.contains(activity)) {
+ mRunningActivities++;
+ Log.i("runningActivities=" + mRunningActivities);
+ checkActivity();
+ }
- @Override
- public synchronized void onActivityPaused(Activity activity) {
- Log.i("Activity paused:" + activity);
- if (activities.contains(activity)) {
- mRunningActivities--;
- Log.i("runningActivities=" + mRunningActivities);
- checkActivity();
- }
+ }
- }
+ @Override
+ public synchronized void onActivityPaused(Activity activity) {
+ Log.i("Activity paused:" + activity);
+ if (activities.contains(activity)) {
+ mRunningActivities--;
+ Log.i("runningActivities=" + mRunningActivities);
+ checkActivity();
+ }
- @Override
- public void onActivityStopped(Activity activity) {
- Log.i("Activity stopped:" + activity);
- }
+ }
- @Override
- public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
+ @Override
+ public void onActivityStopped(Activity activity) {
+ Log.i("Activity stopped:" + activity);
+ }
- }
+ @Override
+ public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
- @Override
- public synchronized void onActivityDestroyed(Activity activity) {
- Log.i("Activity destroyed:" + activity);
- if (activities.contains(activity)) {
- activities.remove(activity);
- }
- }
+ }
- void startInactivityChecker() {
- if (mLastChecker != null) mLastChecker.cancel();
- LinphoneService.this.mHandler.postDelayed(
- (mLastChecker = new InactivityChecker()), 2000);
- }
+ @Override
+ public synchronized void onActivityDestroyed(Activity activity) {
+ Log.i("Activity destroyed:" + activity);
+ if (activities.contains(activity)) {
+ activities.remove(activity);
+ }
+ }
- void checkActivity() {
+ void startInactivityChecker() {
+ if (mLastChecker != null) mLastChecker.cancel();
+ LinphoneService.this.mHandler.postDelayed(
+ (mLastChecker = new InactivityChecker()), 2000);
+ }
- if (mRunningActivities == 0) {
- if (mActive) startInactivityChecker();
- } else if (mRunningActivities > 0) {
- if (!mActive) {
- mActive = true;
- LinphoneService.this.onForegroundMode();
- }
- if (mLastChecker != null) {
- mLastChecker.cancel();
- mLastChecker = null;
- }
- }
- }
- }
+ void checkActivity() {
- protected void onBackgroundMode(){
- Log.i("App has entered background mode");
- if (LinphonePreferences.instance() != null && LinphonePreferences.instance().isFriendlistsubscriptionEnabled()) {
- if (LinphoneManager.isInstanciated())
- LinphoneManager.getInstance().subscribeFriendList(false);
- }
- if (LinphoneManager.getLcIfManagerNotDestroyedOrNull() != null) {
- LinphoneManager.getLcIfManagerNotDestroyedOrNull().enterBackground();
- }
- }
+ if (mRunningActivities == 0) {
+ if (mActive) startInactivityChecker();
+ } else if (mRunningActivities > 0) {
+ if (!mActive) {
+ mActive = true;
+ LinphoneService.this.onForegroundMode();
+ }
+ if (mLastChecker != null) {
+ mLastChecker.cancel();
+ mLastChecker = null;
+ }
+ }
+ }
+ }
- protected void onForegroundMode() {
- Log.i("App has left background mode");
- if (LinphonePreferences.instance() != null && LinphonePreferences.instance().isFriendlistsubscriptionEnabled()) {
- if (LinphoneManager.isInstanciated())
- LinphoneManager.getInstance().subscribeFriendList(true);
- }
- if (LinphoneManager.getLcIfManagerNotDestroyedOrNull() != null) {
- LinphoneManager.getLcIfManagerNotDestroyedOrNull().enterForeground();
- }
- }
+ protected void onBackgroundMode() {
+ Log.i("App has entered background mode");
+ if (LinphonePreferences.instance() != null && LinphonePreferences.instance().isFriendlistsubscriptionEnabled()) {
+ if (LinphoneManager.isInstanciated())
+ LinphoneManager.getInstance().subscribeFriendList(false);
+ }
+ if (LinphoneManager.getLcIfManagerNotDestroyedOrNull() != null) {
+ LinphoneManager.getLcIfManagerNotDestroyedOrNull().enterBackground();
+ }
+ }
- private void setupActivityMonitor(){
- if (activityCallbacks != null) return;
- getApplication().registerActivityLifecycleCallbacks(activityCallbacks = new ActivityMonitor());
- }
+ protected void onForegroundMode() {
+ Log.i("App has left background mode");
+ if (LinphonePreferences.instance() != null && LinphonePreferences.instance().isFriendlistsubscriptionEnabled()) {
+ if (LinphoneManager.isInstanciated())
+ LinphoneManager.getInstance().subscribeFriendList(true);
+ }
+ if (LinphoneManager.getLcIfManagerNotDestroyedOrNull() != null) {
+ LinphoneManager.getLcIfManagerNotDestroyedOrNull().enterForeground();
+ }
+ }
- public boolean displayServiceNotification() {
- return LinphonePreferences.instance().getServiceNotificationVisibility();
- }
+ private void setupActivityMonitor() {
+ if (activityCallbacks != null) return;
+ getApplication().registerActivityLifecycleCallbacks(activityCallbacks = new ActivityMonitor());
+ }
- public void showServiceNotification() {
- startForegroundCompat(NOTIF_ID, mNotif);
+ public boolean displayServiceNotification() {
+ return LinphonePreferences.instance().getServiceNotificationVisibility();
+ }
- Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- if (lc == null) return;
- ProxyConfig lpc = lc.getDefaultProxyConfig();
- if (lpc != null) {
- if (lpc.getState() == RegistrationState.Ok) {
- sendNotification(IC_LEVEL_ORANGE, R.string.notification_registered);
- } else {
- sendNotification(IC_LEVEL_ORANGE, R.string.notification_register_failure);
- }
- } else {
- sendNotification(IC_LEVEL_ORANGE, R.string.notification_started);
- }
- }
+ public void showServiceNotification() {
+ startForegroundCompat(NOTIF_ID, mNotif);
- public void hideServiceNotification() {
- stopForegroundCompat(NOTIF_ID);
- }
+ Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ if (lc == null) return;
+ ProxyConfig lpc = lc.getDefaultProxyConfig();
+ if (lpc != null) {
+ if (lpc.getState() == RegistrationState.Ok) {
+ sendNotification(IC_LEVEL_ORANGE, R.string.notification_registered);
+ } else {
+ sendNotification(IC_LEVEL_ORANGE, R.string.notification_register_failure);
+ }
+ } else {
+ sendNotification(IC_LEVEL_ORANGE, R.string.notification_started);
+ }
+ }
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {
- super.onStartCommand(intent, flags, startId);
+ public void hideServiceNotification() {
+ stopForegroundCompat(NOTIF_ID);
+ }
- LinphoneManager.createAndStart(LinphoneService.this);
+ @Override
+ public int onStartCommand(Intent intent, int flags, int startId) {
+ super.onStartCommand(intent, flags, startId);
- instance = this; // instance is ready once linphone manager has been created
- LinphoneManager.getLc().addListener(mListener = new CoreListenerStub() {
- @Override
- public void onCallStateChanged(Core lc, Call call, Call.State state, String message) {
- if (instance == null) {
- Log.i("Service not ready, discarding call state change to ",state.toString());
- return;
- }
+ LinphoneManager.createAndStart(LinphoneService.this);
- if (state == Call.State.IncomingReceived) {
- if(! LinphoneManager.getInstance().getCallGsmON())
- onIncomingReceived();
- }
+ instance = this; // instance is ready once linphone manager has been created
+ LinphoneManager.getLc().addListener(mListener = new CoreListenerStub() {
+ @Override
+ public void onCallStateChanged(Core lc, Call call, Call.State state, String message) {
+ if (instance == null) {
+ Log.i("Service not ready, discarding call state change to ", state.toString());
+ return;
+ }
- if (state == State.End || state == State.Released || state == State.Error) {
- if (LinphoneManager.isInstanciated() && LinphoneManager.getLc() != null && LinphoneManager.getLc().getCallsNb() == 0) {
- if (LinphoneActivity.isInstanciated() && LinphoneActivity.instance().getStatusFragment() != null) {
- removeSasNotification();
- LinphoneActivity.instance().getStatusFragment().setisZrtpAsk(false);
- }
- }
- destroyOverlay();
- }
+ if (state == Call.State.IncomingReceived) {
+ if (!LinphoneManager.getInstance().getCallGsmON())
+ onIncomingReceived();
+ }
- if (state == State.End && call.getCallLog().getStatus() == Call.Status.Missed) {
- int missedCallCount = LinphoneManager.getLcIfManagerNotDestroyedOrNull().getMissedCallsCount();
- String body;
- if (missedCallCount > 1) {
- body = getString(R.string.missed_calls_notif_body).replace("%i", String.valueOf(missedCallCount));
- } else {
- Address address = call.getRemoteAddress();
- LinphoneContact c = ContactsManager.getInstance().findContactFromAddress(address);
- if (c != null) {
- body = c.getFullName();
- } else {
- body = address.getDisplayName();
- if (body == null) {
- body = address.asStringUriOnly();
- }
- }
- }
+ if (state == State.End || state == State.Released || state == State.Error) {
+ if (LinphoneManager.isInstanciated() && LinphoneManager.getLc() != null && LinphoneManager.getLc().getCallsNb() == 0) {
+ if (LinphoneActivity.isInstanciated() && LinphoneActivity.instance().getStatusFragment() != null) {
+ removeSasNotification();
+ LinphoneActivity.instance().getStatusFragment().setisZrtpAsk(false);
+ }
+ }
+ destroyOverlay();
+ }
+
+ if (state == State.End && call.getCallLog().getStatus() == Call.Status.Missed) {
+ int missedCallCount = LinphoneManager.getLcIfManagerNotDestroyedOrNull().getMissedCallsCount();
+ String body;
+ if (missedCallCount > 1) {
+ body = getString(R.string.missed_calls_notif_body).replace("%i", String.valueOf(missedCallCount));
+ } else {
+ Address address = call.getRemoteAddress();
+ LinphoneContact c = ContactsManager.getInstance().findContactFromAddress(address);
+ if (c != null) {
+ body = c.getFullName();
+ } else {
+ body = address.getDisplayName();
+ if (body == null) {
+ body = address.asStringUriOnly();
+ }
+ }
+ }
- Intent missedCallNotifIntent = new Intent(LinphoneService.this, incomingReceivedActivity);
- missedCallNotifIntent.putExtra("GoToHistory", true);
- PendingIntent intent = PendingIntent.getActivity(LinphoneService.this, 0, missedCallNotifIntent, PendingIntent.FLAG_UPDATE_CURRENT);
- Notification notif = Compatibility.createMissedCallNotification(instance, getString(R.string.missed_calls_notif_title), body, intent);
- notifyWrapper(MISSED_NOTIF_ID, notif);
- }
+ Intent missedCallNotifIntent = new Intent(LinphoneService.this, incomingReceivedActivity);
+ missedCallNotifIntent.putExtra("GoToHistory", true);
+ PendingIntent intent = PendingIntent.getActivity(LinphoneService.this, 0, missedCallNotifIntent, PendingIntent.FLAG_UPDATE_CURRENT);
+ Notification notif = Compatibility.createMissedCallNotification(instance, getString(R.string.missed_calls_notif_title), body, intent);
+ notifyWrapper(MISSED_NOTIF_ID, notif);
+ }
- if (state == State.StreamsRunning) {
- // Workaround bug current call seems to be updated after state changed to streams running
- if (getResources().getBoolean(R.bool.enable_call_notification))
- refreshIncallIcon(call);
- } else {
- if (getResources().getBoolean(R.bool.enable_call_notification))
- refreshIncallIcon(LinphoneManager.getLc().getCurrentCall());
- }
- }
+ if (state == State.StreamsRunning) {
+ // Workaround bug current call seems to be updated after state changed to streams running
+ if (getResources().getBoolean(R.bool.enable_call_notification))
+ refreshIncallIcon(call);
+ } else {
+ if (getResources().getBoolean(R.bool.enable_call_notification))
+ refreshIncallIcon(LinphoneManager.getLc().getCurrentCall());
+ }
+ }
- @Override
- public void onGlobalStateChanged(Core lc,GlobalState state, String message) {
- if (!mDisableRegistrationStatus && state == GlobalState.On && displayServiceNotification()) {
- sendNotification(IC_LEVEL_ORANGE, R.string.notification_started);
- }
- }
+ @Override
+ public void onGlobalStateChanged(Core lc, GlobalState state, String message) {
+ if (!mDisableRegistrationStatus && state == GlobalState.On && displayServiceNotification()) {
+ sendNotification(IC_LEVEL_ORANGE, R.string.notification_started);
+ }
+ }
- @Override
- public void onRegistrationStateChanged(Core lc, ProxyConfig cfg, RegistrationState state, String smessage) {
+ @Override
+ public void onRegistrationStateChanged(Core lc, ProxyConfig cfg, RegistrationState state, String smessage) {
// if (instance == null) {
// Log.i("Service not ready, discarding registration state change to ",state.toString());
// return;
// }
- if (!mDisableRegistrationStatus) {
- if (displayServiceNotification() && state == RegistrationState.Ok && LinphoneManager.getLc().getDefaultProxyConfig() != null && LinphoneManager.getLc().getDefaultProxyConfig().getState() == RegistrationState.Ok) {
- sendNotification(IC_LEVEL_ORANGE, R.string.notification_registered);
- }
-
- if (displayServiceNotification() && (state == RegistrationState.Failed || state == RegistrationState.Cleared) && (LinphoneManager.getLc().getDefaultProxyConfig() == null || !(LinphoneManager.getLc().getDefaultProxyConfig().getState() == RegistrationState.Ok))) {
- sendNotification(IC_LEVEL_ORANGE, R.string.notification_register_failure);
- }
-
- if (displayServiceNotification() && state == RegistrationState.None) {
- sendNotification(IC_LEVEL_ORANGE, R.string.notification_started);
- }
- }
- }
- });
-
- if (displayServiceNotification() || (Version.sdkAboveOrEqual(Version.API26_O_80) && intent.getBooleanExtra("ForceStartForeground", false))) {
- startForegroundCompat(NOTIF_ID, mNotif);
- }
-
- if (!Version.sdkAboveOrEqual(Version.API26_O_80)
- || (ContactsManager.getInstance() != null && ContactsManager.getInstance().hasContactsAccess())) {
- getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, ContactsManager.getInstance());
- }
-
- if (!mTestDelayElapsed) {
- // Only used when testing. Simulates a 5 seconds delay for launching service
- mHandler.postDelayed(new Runnable() {
- @Override public void run() {
- mTestDelayElapsed = true;
- }
- }, 5000);
- }
-
- //make sure the application will at least wakes up every 10 mn
- Intent keepAliveIntent = new Intent(this, KeepAliveReceiver.class);
- PendingIntent keepAlivePendingIntent = PendingIntent.getBroadcast(this, 0, keepAliveIntent, PendingIntent.FLAG_ONE_SHOT);
- AlarmManager alarmManager = ((AlarmManager) this.getSystemService(Context.ALARM_SERVICE));
- Compatibility.scheduleAlarm(alarmManager, AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 600000, keepAlivePendingIntent);
-
- return START_STICKY;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public void onCreate() {
- super.onCreate();
- mLastNotificationId = 8; // To not interfere with other notifs ids
- mChatNotifMap = new HashMap();
-
- setupActivityMonitor();
- // In case restart after a crash. Main in LinphoneActivity
- mNotificationTitle = getString(R.string.service_name);
-
- // Needed in order for the two next calls to succeed, libraries must have been loaded first
- LinphonePreferences.instance().setContext(getBaseContext());
- Factory.instance().setLogCollectionPath(getFilesDir().getAbsolutePath());
- boolean isDebugEnabled = LinphonePreferences.instance().isDebugEnabled();
- LinphoneUtils.initLoggingService(isDebugEnabled, getString(R.string.app_name));
-
- // Dump some debugging information to the logs
- Log.i(START_LINPHONE_LOGS);
- dumpDeviceInformation();
- dumpInstalledLinphoneInformation();
-
- //Disable service notification for Android O
- if ((Version.sdkAboveOrEqual(Version.API26_O_80))) {
- LinphonePreferences.instance().setServiceNotificationVisibility(false);
- mDisableRegistrationStatus = true;
- }
-
- mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
- mNM.cancel(INCALL_NOTIF_ID); // in case of crash the icon is not removed
- Compatibility.CreateChannel(this);
-
- Intent notifIntent = new Intent(this, incomingReceivedActivity);
- notifIntent.putExtra("Notification", true);
- mNotifContentIntent = PendingIntent.getActivity(this, 0, notifIntent, PendingIntent.FLAG_UPDATE_CURRENT);
-
- Bitmap bm = null;
- try {
- bm = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
- } catch (Exception e) {
- }
- mNotif = Compatibility.createNotification(this, mNotificationTitle, "", R.drawable.linphone_notification_icon, R.mipmap.ic_launcher, bm, mNotifContentIntent, true,notifcationsPriority);
-
- incomingReceivedActivityName = LinphonePreferences.instance().getActivityToLaunchOnIncomingReceived();
- try {
- incomingReceivedActivity = (Class extends Activity>) Class.forName(incomingReceivedActivityName);
- } catch (ClassNotFoundException e) {
- Log.e(e);
- }
-
- try {
- mStartForeground = getClass().getMethod("startForeground", mStartFgSign);
- mStopForeground = getClass().getMethod("stopForeground", mStopFgSign);
- } catch (NoSuchMethodException e) {
- Log.e(e, "Couldn't find startForeground or stopForeground");
- }
-
- mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
- }
-
- public void createOverlay() {
- if (mOverlay != null) destroyOverlay();
-
- Call call = LinphoneManager.getLc().getCurrentCall();
- if (call == null || !call.getCurrentParams().videoEnabled()) return;
-
- mOverlay = new LinphoneOverlay(this);
- WindowManager.LayoutParams params = mOverlay.getWindowManagerLayoutParams();
- params.x = 0;
- params.y = 0;
- mWindowManager.addView(mOverlay, params);
- }
-
- public void destroyOverlay() {
- if (mOverlay != null) {
- mWindowManager.removeViewImmediate(mOverlay);
- mOverlay.destroy();
- }
- mOverlay = null;
- }
-
- private enum IncallIconState {INCALL, PAUSE, VIDEO, IDLE}
- private IncallIconState mCurrentIncallIconState = IncallIconState.IDLE;
- private synchronized void setIncallIcon(IncallIconState state) {
- if (state == mCurrentIncallIconState) return;
- mCurrentIncallIconState = state;
-
- int notificationTextId = 0;
- int inconId = 0;
-
- switch (state) {
- case IDLE:
- if (!displayServiceNotification()) {
- stopForegroundCompat(INCALL_NOTIF_ID);
- } else {
- mNM.cancel(INCALL_NOTIF_ID);
- }
- return;
- case INCALL:
- inconId = R.drawable.topbar_call_notification;
- notificationTextId = R.string.incall_notif_active;
- break;
- case PAUSE:
- inconId = R.drawable.topbar_call_notification;
- notificationTextId = R.string.incall_notif_paused;
- break;
- case VIDEO:
- inconId = R.drawable.topbar_videocall_notification;
- notificationTextId = R.string.incall_notif_video;
- break;
- default:
- throw new IllegalArgumentException("Unknown state " + state);
- }
-
- if (LinphoneManager.getLc().getCallsNb() == 0) {
- return;
- }
-
- Call call = LinphoneManager.getLc().getCalls()[0];
- Address address = call.getRemoteAddress();
-
- LinphoneContact contact = ContactsManager.getInstance().findContactFromAddress(address);
- Uri pictureUri = contact != null ? contact.getPhotoUri() : null;
- Bitmap bm = null;
- try {
- bm = MediaStore.Images.Media.getBitmap(getContentResolver(), pictureUri);
- } catch (Exception e) {
- bm = BitmapFactory.decodeResource(getResources(), R.drawable.avatar);
- }
- String name = address.getDisplayName() == null ? address.getUsername() : address.getDisplayName();
- Intent notifIntent = new Intent(this, incomingReceivedActivity);
- notifIntent.putExtra("Notification", true);
- mNotifContentIntent = PendingIntent.getActivity(this, 0, notifIntent, PendingIntent.FLAG_UPDATE_CURRENT);
- mIncallNotif = Compatibility.createInCallNotification(getApplicationContext(), mNotificationTitle, getString(notificationTextId), inconId, bm, name, mNotifContentIntent);
-
- if (!displayServiceNotification()) {
- startForegroundCompat(INCALL_NOTIF_ID, mIncallNotif);
- } else {
- notifyWrapper(INCALL_NOTIF_ID, mIncallNotif);
- }
- }
-
- public void refreshIncallIcon(Call currentCall) {
- Core lc = LinphoneManager.getLc();
- if (currentCall != null) {
- if (currentCall.getCurrentParams().videoEnabled() && currentCall.cameraEnabled()) {
- // checking first current params is mandatory
- setIncallIcon(IncallIconState.VIDEO);
- } else {
- setIncallIcon(IncallIconState.INCALL);
- }
- } else if (lc.getCallsNb() == 0) {
- setIncallIcon(IncallIconState.IDLE);
- } else if (lc.getConference() != null) {
- setIncallIcon(IncallIconState.INCALL);
- } else {
- setIncallIcon(IncallIconState.PAUSE);
- }
- }
-
- @Deprecated
- public void addNotification(Intent onClickIntent, int iconResourceID, String title, String message) {
- addCustomNotification(onClickIntent, iconResourceID, title, message, true);
- }
-
- public void addCustomNotification(Intent onClickIntent, int iconResourceID, String title, String message, boolean isOngoingEvent) {
- PendingIntent notifContentIntent = PendingIntent.getActivity(this, 0, onClickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
-
- Bitmap bm = null;
- try {
- bm = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
- } catch (Exception e) {
- }
- mCustomNotif = Compatibility.createNotification(this, title, message, iconResourceID, 0, bm, notifContentIntent, isOngoingEvent,notifcationsPriority);
-
- mCustomNotif.defaults |= Notification.DEFAULT_VIBRATE;
- mCustomNotif.defaults |= Notification.DEFAULT_SOUND;
- mCustomNotif.defaults |= Notification.DEFAULT_LIGHTS;
-
- notifyWrapper(CUSTOM_NOTIF_ID, mCustomNotif);
- }
-
- public void displayGroupChatMessageNotification(String subject, String conferenceAddress, String fromName, Uri fromPictureUri, String message) {
- Intent notifIntent = new Intent(this, LinphoneActivity.class);
- notifIntent.putExtra("GoToChat", true);
- notifIntent.putExtra("ChatContactSipUri", conferenceAddress);
-
- PendingIntent notifContentIntent = PendingIntent.getActivity(this, 0, notifIntent, PendingIntent.FLAG_UPDATE_CURRENT);
-
- Notified notif = mChatNotifMap.get(conferenceAddress);
- if (notif != null) {
- notif.numberOfUnreadMessage += 1;
- } else {
- notif = new Notified();
- notif.numberOfUnreadMessage = 1;
- notif.notificationId = mLastNotificationId;
- mLastNotificationId += 1;
- mChatNotifMap.put(conferenceAddress, notif);
- }
-
- Bitmap bm = null;
- if (fromPictureUri != null) {
- try {
- bm = MediaStore.Images.Media.getBitmap(getContentResolver(), fromPictureUri);
- } catch (Exception e) {
- bm = BitmapFactory.decodeResource(getResources(), R.drawable.topbar_avatar);
- }
- } else {
- bm = BitmapFactory.decodeResource(getResources(), R.drawable.topbar_avatar);
- }
- Notification notification = Compatibility.createMessageNotification(getApplicationContext(), notif.numberOfUnreadMessage, subject,
- getString(R.string.group_chat_notif).replace("%1", fromName).replace("%2", message), bm, notifContentIntent);
-
- notifyWrapper(notif.notificationId, notification);
- }
-
- public void displayMessageNotification(String fromSipUri, String fromName, Uri fromPictureUri, String message) {
- Intent notifIntent = new Intent(this, LinphoneActivity.class);
- notifIntent.putExtra("GoToChat", true);
- notifIntent.putExtra("ChatContactSipUri", fromSipUri);
-
- PendingIntent notifContentIntent = PendingIntent.getActivity(this, 0, notifIntent, PendingIntent.FLAG_UPDATE_CURRENT);
-
- if (fromName == null) {
- fromName = fromSipUri;
- }
-
- Notified notif = mChatNotifMap.get(fromSipUri);
- if (notif != null) {
- notif.numberOfUnreadMessage += 1;
- } else {
- notif = new Notified();
- notif.numberOfUnreadMessage = 1;
- notif.notificationId = mLastNotificationId;
- mLastNotificationId += 1;
- mChatNotifMap.put(fromSipUri, notif);
- }
-
- Bitmap bm = null;
- if (fromPictureUri != null) {
- try {
- bm = MediaStore.Images.Media.getBitmap(getContentResolver(), fromPictureUri);
- } catch (Exception e) {
- bm = BitmapFactory.decodeResource(getResources(), R.drawable.topbar_avatar);
- }
- } else {
- bm = BitmapFactory.decodeResource(getResources(), R.drawable.topbar_avatar);
- }
- Notification notification = Compatibility.createMessageNotification(getApplicationContext(), notif.numberOfUnreadMessage, fromName, message, bm, notifContentIntent);
-
- notifyWrapper(notif.notificationId, notification);
- }
-
- public void displayInappNotification(String message) {
- Intent notifIntent = new Intent(this, LinphoneActivity.class);
- notifIntent.putExtra("GoToInapp", true);
-
- PendingIntent notifContentIntent = PendingIntent.getActivity(this, 0, notifIntent, PendingIntent.FLAG_UPDATE_CURRENT);
- mNotif = Compatibility.createSimpleNotification(getApplicationContext(), getString(R.string.inapp_notification_title), message, notifContentIntent);
-
- notifyWrapper(NOTIF_ID, mNotif);
- }
-
- public void displaySasNotification(String sas) {
- mSasNotif = Compatibility.createSimpleNotification(getApplicationContext(),
- getString(R.string.zrtp_notification_title),
- sas + " " + getString(R.string.zrtp_notification_message),
- null);
-
- notifyWrapper(SAS_NOTIF_ID, mSasNotif);
- }
-
- public void removeSasNotification() {
- mNM.cancel(SAS_NOTIF_ID);
- }
-
- private static final Class>[] mSetFgSign = new Class[] {boolean.class};
- private static final Class>[] mStartFgSign = new Class[] {
- int.class, Notification.class};
- private static final Class>[] mStopFgSign = new Class[] {boolean.class};
-
- private Method mStartForeground;
- private Method mStopForeground;
- private Object[] mSetForegroundArgs = new Object[1];
- private Object[] mStartForegroundArgs = new Object[2];
- private Object[] mStopForegroundArgs = new Object[1];
- private String incomingReceivedActivityName;
- private Class extends Activity> incomingReceivedActivity = LinphoneActivity.class;
-
- void invokeMethod(Method method, Object[] args) {
- try {
- method.invoke(this, args);
- } catch (InvocationTargetException e) {
- // Should not happen.
- Log.w(e, "Unable to invoke method");
- } catch (IllegalAccessException e) {
- // Should not happen.
- Log.w(e, "Unable to invoke method");
- }
- }
-
- /**
- * This is a wrapper around the new startForeground method, using the older
- * APIs if it is not available.
- */
- void startForegroundCompat(int id, Notification notification) {
- // If we have the new startForeground API, then use it.
- if (mStartForeground != null) {
- mStartForegroundArgs[0] = Integer.valueOf(id);
- mStartForegroundArgs[1] = notification;
- invokeMethod(mStartForeground, mStartForegroundArgs);
- return;
- }
-
- notifyWrapper(id, notification);
- }
-
- /**
- * This is a wrapper around the new stopForeground method, using the older
- * APIs if it is not available.
- */
- void stopForegroundCompat(int id) {
- // If we have the new stopForeground API, then use it.
- if (mStopForeground != null) {
- mStopForegroundArgs[0] = Boolean.TRUE;
- invokeMethod(mStopForeground, mStopForegroundArgs);
- return;
- }
-
- // Fall back on the old API. Note to cancel BEFORE changing the
- // foreground state, since we could be killed at that point.
- mNM.cancel(id);
- }
-
- private void dumpDeviceInformation() {
- StringBuilder sb = new StringBuilder();
- sb.append("DEVICE=").append(Build.DEVICE).append("\n");
- sb.append("MODEL=").append(Build.MODEL).append("\n");
- sb.append("MANUFACTURER=").append(Build.MANUFACTURER).append("\n");
- sb.append("SDK=").append(Build.VERSION.SDK_INT).append("\n");
- sb.append("Supported ABIs=");
- for (String abi : Version.getCpuAbis()) {
- sb.append(abi + ", ");
- }
- sb.append("\n");
- Log.i(sb.toString());
- }
-
- private void dumpInstalledLinphoneInformation() {
- PackageInfo info = null;
- try {
- info = getPackageManager().getPackageInfo(getPackageName(),0);
- } catch (NameNotFoundException nnfe) {}
-
- if (info != null) {
- Log.i("Linphone version is ", info.versionName + " (" + info.versionCode + ")");
- } else {
- Log.i("Linphone version is unknown");
- }
- }
-
- private synchronized void sendNotification(int level, int textId) {
- String text = getString(textId);
- if (text.contains("%s") && LinphoneManager.getLc() != null) {
- // Test for null lc is to avoid a NPE when Android mess up badly with the String resources.
- ProxyConfig lpc = LinphoneManager.getLc().getDefaultProxyConfig();
- String id = lpc != null ? lpc.getIdentityAddress().asString() : "";
- text = String.format(text, id);
- }
-
- Bitmap bm = null;
- try {
- bm = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
- } catch (Exception e) {
- }
- mNotif = Compatibility.createNotification(this, mNotificationTitle, text, R.drawable.status_level, 0, bm, mNotifContentIntent, true,notifcationsPriority);
- notifyWrapper(NOTIF_ID, mNotif);
- }
-
- /**
- * Wrap notifier to avoid setting the linphone icons while the service
- * is stopping. When the (rare) bug is triggered, the linphone icon is
- * present despite the service is not running. To trigger it one could
- * stop linphone as soon as it is started. Transport configured with TLS.
- */
- private synchronized void notifyWrapper(int id, Notification notification) {
- if (instance != null && notification != null) {
- mNM.notify(id, notification);
- } else {
- Log.i("Service not ready, discarding notification");
- }
- }
-
- @Override
- public IBinder onBind(Intent intent) {
- return null;
- }
-
- @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
- @Override
- public void onTaskRemoved(Intent rootIntent) {
- if (getResources().getBoolean(R.bool.kill_service_with_task_manager)) {
- Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- if (lc != null) {
- lc.terminateAllCalls();
- }
-
- Log.d("Task removed, stop service");
-
- // If push is enabled, don't unregister account, otherwise do unregister
- if (LinphonePreferences.instance().isPushNotificationEnabled()) {
- if (lc != null) lc.setNetworkReachable(false);
- }
- stopSelf();
- }
- super.onTaskRemoved(rootIntent);
- }
-
- @Override
- public synchronized void onDestroy() {
- if (activityCallbacks != null){
- getApplication().unregisterActivityLifecycleCallbacks(activityCallbacks);
- activityCallbacks = null;
- }
-
- destroyOverlay();
- Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- if (lc != null) {
- lc.removeListener(mListener);
- }
-
- instance = null;
- LinphoneManager.destroy();
-
- // Make sure our notification is gone.
- stopForegroundCompat(NOTIF_ID);
- mNM.cancel(INCALL_NOTIF_ID);
- for (Notified notif : mChatNotifMap.values()) {
- mNM.cancel(notif.notificationId);
- }
-
-
- // This will prevent the app from crashing if the service gets killed in background mode
- if (LinphoneActivity.isInstanciated()) {
- Log.w("Service is getting destroyed, finish LinphoneActivity");
- LinphoneActivity.instance().finish();
- }
-
- super.onDestroy();
- }
-
- @SuppressWarnings("unchecked")
- public void setActivityToLaunchOnIncomingReceived(String activityName) {
- try {
- incomingReceivedActivity = (Class extends Activity>) Class.forName(activityName);
- incomingReceivedActivityName = activityName;
- LinphonePreferences.instance().setActivityToLaunchOnIncomingReceived(incomingReceivedActivityName);
- } catch (ClassNotFoundException e) {
- Log.e(e);
- }
- }
-
- protected void onIncomingReceived() {
- //wakeup linphone
- startActivity(new Intent()
- .setClass(this, incomingReceivedActivity)
- .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
- }
+ if (!mDisableRegistrationStatus) {
+ if (displayServiceNotification() && state == RegistrationState.Ok && LinphoneManager.getLc().getDefaultProxyConfig() != null && LinphoneManager.getLc().getDefaultProxyConfig().getState() == RegistrationState.Ok) {
+ sendNotification(IC_LEVEL_ORANGE, R.string.notification_registered);
+ }
+
+ if (displayServiceNotification() && (state == RegistrationState.Failed || state == RegistrationState.Cleared) && (LinphoneManager.getLc().getDefaultProxyConfig() == null || !(LinphoneManager.getLc().getDefaultProxyConfig().getState() == RegistrationState.Ok))) {
+ sendNotification(IC_LEVEL_ORANGE, R.string.notification_register_failure);
+ }
+
+ if (displayServiceNotification() && state == RegistrationState.None) {
+ sendNotification(IC_LEVEL_ORANGE, R.string.notification_started);
+ }
+ }
+ }
+ });
+
+ if (displayServiceNotification() || (Version.sdkAboveOrEqual(Version.API26_O_80) && intent.getBooleanExtra("ForceStartForeground", false))) {
+ startForegroundCompat(NOTIF_ID, mNotif);
+ }
+
+ if (!Version.sdkAboveOrEqual(Version.API26_O_80)
+ || (ContactsManager.getInstance() != null && ContactsManager.getInstance().hasContactsAccess())) {
+ getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, ContactsManager.getInstance());
+ }
+
+ if (!mTestDelayElapsed) {
+ // Only used when testing. Simulates a 5 seconds delay for launching service
+ mHandler.postDelayed(new Runnable() {
+ @Override
+ public void run() {
+ mTestDelayElapsed = true;
+ }
+ }, 5000);
+ }
+
+ //make sure the application will at least wakes up every 10 mn
+ Intent keepAliveIntent = new Intent(this, KeepAliveReceiver.class);
+ PendingIntent keepAlivePendingIntent = PendingIntent.getBroadcast(this, 0, keepAliveIntent, PendingIntent.FLAG_ONE_SHOT);
+ AlarmManager alarmManager = ((AlarmManager) this.getSystemService(Context.ALARM_SERVICE));
+ Compatibility.scheduleAlarm(alarmManager, AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 600000, keepAlivePendingIntent);
+
+ return START_STICKY;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ mLastNotificationId = 8; // To not interfere with other notifs ids
+ mChatNotifMap = new HashMap();
+
+ setupActivityMonitor();
+ // In case restart after a crash. Main in LinphoneActivity
+ mNotificationTitle = getString(R.string.service_name);
+
+ // Needed in order for the two next calls to succeed, libraries must have been loaded first
+ LinphonePreferences.instance().setContext(getBaseContext());
+ Factory.instance().setLogCollectionPath(getFilesDir().getAbsolutePath());
+ boolean isDebugEnabled = LinphonePreferences.instance().isDebugEnabled();
+ LinphoneUtils.initLoggingService(isDebugEnabled, getString(R.string.app_name));
+
+ // Dump some debugging information to the logs
+ Log.i(START_LINPHONE_LOGS);
+ dumpDeviceInformation();
+ dumpInstalledLinphoneInformation();
+
+ //Disable service notification for Android O
+ if ((Version.sdkAboveOrEqual(Version.API26_O_80))) {
+ LinphonePreferences.instance().setServiceNotificationVisibility(false);
+ mDisableRegistrationStatus = true;
+ }
+
+ mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
+ mNM.cancel(INCALL_NOTIF_ID); // in case of crash the icon is not removed
+ Compatibility.CreateChannel(this);
+
+ Intent notifIntent = new Intent(this, incomingReceivedActivity);
+ notifIntent.putExtra("Notification", true);
+ mNotifContentIntent = PendingIntent.getActivity(this, 0, notifIntent, PendingIntent.FLAG_UPDATE_CURRENT);
+
+ Bitmap bm = null;
+ try {
+ bm = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
+ } catch (Exception e) {
+ }
+ mNotif = Compatibility.createNotification(this, mNotificationTitle, "", R.drawable.linphone_notification_icon, R.mipmap.ic_launcher, bm, mNotifContentIntent, true, notifcationsPriority);
+
+ incomingReceivedActivityName = LinphonePreferences.instance().getActivityToLaunchOnIncomingReceived();
+ try {
+ incomingReceivedActivity = (Class extends Activity>) Class.forName(incomingReceivedActivityName);
+ } catch (ClassNotFoundException e) {
+ Log.e(e);
+ }
+
+ try {
+ mStartForeground = getClass().getMethod("startForeground", mStartFgSign);
+ mStopForeground = getClass().getMethod("stopForeground", mStopFgSign);
+ } catch (NoSuchMethodException e) {
+ Log.e(e, "Couldn't find startForeground or stopForeground");
+ }
+
+ mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
+ }
+
+ public void createOverlay() {
+ if (mOverlay != null) destroyOverlay();
+
+ Call call = LinphoneManager.getLc().getCurrentCall();
+ if (call == null || !call.getCurrentParams().videoEnabled()) return;
+
+ mOverlay = new LinphoneOverlay(this);
+ WindowManager.LayoutParams params = mOverlay.getWindowManagerLayoutParams();
+ params.x = 0;
+ params.y = 0;
+ mWindowManager.addView(mOverlay, params);
+ }
+
+ public void destroyOverlay() {
+ if (mOverlay != null) {
+ mWindowManager.removeViewImmediate(mOverlay);
+ mOverlay.destroy();
+ }
+ mOverlay = null;
+ }
+
+ private enum IncallIconState {INCALL, PAUSE, VIDEO, IDLE}
+
+ private IncallIconState mCurrentIncallIconState = IncallIconState.IDLE;
+
+ private synchronized void setIncallIcon(IncallIconState state) {
+ if (state == mCurrentIncallIconState) return;
+ mCurrentIncallIconState = state;
+
+ int notificationTextId = 0;
+ int inconId = 0;
+
+ switch (state) {
+ case IDLE:
+ if (!displayServiceNotification()) {
+ stopForegroundCompat(INCALL_NOTIF_ID);
+ } else {
+ mNM.cancel(INCALL_NOTIF_ID);
+ }
+ return;
+ case INCALL:
+ inconId = R.drawable.topbar_call_notification;
+ notificationTextId = R.string.incall_notif_active;
+ break;
+ case PAUSE:
+ inconId = R.drawable.topbar_call_notification;
+ notificationTextId = R.string.incall_notif_paused;
+ break;
+ case VIDEO:
+ inconId = R.drawable.topbar_videocall_notification;
+ notificationTextId = R.string.incall_notif_video;
+ break;
+ default:
+ throw new IllegalArgumentException("Unknown state " + state);
+ }
+
+ if (LinphoneManager.getLc().getCallsNb() == 0) {
+ return;
+ }
+
+ Call call = LinphoneManager.getLc().getCalls()[0];
+ Address address = call.getRemoteAddress();
+
+ LinphoneContact contact = ContactsManager.getInstance().findContactFromAddress(address);
+ Uri pictureUri = contact != null ? contact.getPhotoUri() : null;
+ Bitmap bm = null;
+ try {
+ bm = MediaStore.Images.Media.getBitmap(getContentResolver(), pictureUri);
+ } catch (Exception e) {
+ bm = BitmapFactory.decodeResource(getResources(), R.drawable.avatar);
+ }
+ String name = address.getDisplayName() == null ? address.getUsername() : address.getDisplayName();
+ Intent notifIntent = new Intent(this, incomingReceivedActivity);
+ notifIntent.putExtra("Notification", true);
+ mNotifContentIntent = PendingIntent.getActivity(this, 0, notifIntent, PendingIntent.FLAG_UPDATE_CURRENT);
+ mIncallNotif = Compatibility.createInCallNotification(getApplicationContext(), mNotificationTitle, getString(notificationTextId), inconId, bm, name, mNotifContentIntent);
+
+ if (!displayServiceNotification()) {
+ startForegroundCompat(INCALL_NOTIF_ID, mIncallNotif);
+ } else {
+ notifyWrapper(INCALL_NOTIF_ID, mIncallNotif);
+ }
+ }
+
+ public void refreshIncallIcon(Call currentCall) {
+ Core lc = LinphoneManager.getLc();
+ if (currentCall != null) {
+ if (currentCall.getCurrentParams().videoEnabled() && currentCall.cameraEnabled()) {
+ // checking first current params is mandatory
+ setIncallIcon(IncallIconState.VIDEO);
+ } else {
+ setIncallIcon(IncallIconState.INCALL);
+ }
+ } else if (lc.getCallsNb() == 0) {
+ setIncallIcon(IncallIconState.IDLE);
+ } else if (lc.getConference() != null) {
+ setIncallIcon(IncallIconState.INCALL);
+ } else {
+ setIncallIcon(IncallIconState.PAUSE);
+ }
+ }
+
+ @Deprecated
+ public void addNotification(Intent onClickIntent, int iconResourceID, String title, String message) {
+ addCustomNotification(onClickIntent, iconResourceID, title, message, true);
+ }
+
+ public void addCustomNotification(Intent onClickIntent, int iconResourceID, String title, String message, boolean isOngoingEvent) {
+ PendingIntent notifContentIntent = PendingIntent.getActivity(this, 0, onClickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
+
+ Bitmap bm = null;
+ try {
+ bm = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
+ } catch (Exception e) {
+ }
+ mCustomNotif = Compatibility.createNotification(this, title, message, iconResourceID, 0, bm, notifContentIntent, isOngoingEvent, notifcationsPriority);
+
+ mCustomNotif.defaults |= Notification.DEFAULT_VIBRATE;
+ mCustomNotif.defaults |= Notification.DEFAULT_SOUND;
+ mCustomNotif.defaults |= Notification.DEFAULT_LIGHTS;
+
+ notifyWrapper(CUSTOM_NOTIF_ID, mCustomNotif);
+ }
+
+ public void displayGroupChatMessageNotification(String subject, String conferenceAddress, String fromName, Uri fromPictureUri, String message) {
+ Intent notifIntent = new Intent(this, LinphoneActivity.class);
+ notifIntent.putExtra("GoToChat", true);
+ notifIntent.putExtra("ChatContactSipUri", conferenceAddress);
+
+ PendingIntent notifContentIntent = PendingIntent.getActivity(this, 0, notifIntent, PendingIntent.FLAG_UPDATE_CURRENT);
+
+ Notified notif = mChatNotifMap.get(conferenceAddress);
+ if (notif != null) {
+ notif.numberOfUnreadMessage += 1;
+ } else {
+ notif = new Notified();
+ notif.numberOfUnreadMessage = 1;
+ notif.notificationId = mLastNotificationId;
+ mLastNotificationId += 1;
+ mChatNotifMap.put(conferenceAddress, notif);
+ }
+
+ Bitmap bm = null;
+ if (fromPictureUri != null) {
+ try {
+ bm = MediaStore.Images.Media.getBitmap(getContentResolver(), fromPictureUri);
+ } catch (Exception e) {
+ bm = BitmapFactory.decodeResource(getResources(), R.drawable.topbar_avatar);
+ }
+ } else {
+ bm = BitmapFactory.decodeResource(getResources(), R.drawable.topbar_avatar);
+ }
+ Notification notification = Compatibility.createMessageNotification(getApplicationContext(), notif.numberOfUnreadMessage, subject,
+ getString(R.string.group_chat_notif).replace("%1", fromName).replace("%2", message), bm, notifContentIntent);
+
+ notifyWrapper(notif.notificationId, notification);
+ }
+
+ public void displayMessageNotification(String fromSipUri, String fromName, Uri fromPictureUri, String message) {
+ Intent notifIntent = new Intent(this, LinphoneActivity.class);
+ notifIntent.putExtra("GoToChat", true);
+ notifIntent.putExtra("ChatContactSipUri", fromSipUri);
+
+ PendingIntent notifContentIntent = PendingIntent.getActivity(this, 0, notifIntent, PendingIntent.FLAG_UPDATE_CURRENT);
+
+ if (fromName == null) {
+ fromName = fromSipUri;
+ }
+
+ Notified notif = mChatNotifMap.get(fromSipUri);
+ if (notif != null) {
+ notif.numberOfUnreadMessage += 1;
+ } else {
+ notif = new Notified();
+ notif.numberOfUnreadMessage = 1;
+ notif.notificationId = mLastNotificationId;
+ mLastNotificationId += 1;
+ mChatNotifMap.put(fromSipUri, notif);
+ }
+
+ Bitmap bm = null;
+ if (fromPictureUri != null) {
+ try {
+ bm = MediaStore.Images.Media.getBitmap(getContentResolver(), fromPictureUri);
+ } catch (Exception e) {
+ bm = BitmapFactory.decodeResource(getResources(), R.drawable.topbar_avatar);
+ }
+ } else {
+ bm = BitmapFactory.decodeResource(getResources(), R.drawable.topbar_avatar);
+ }
+ Notification notification = Compatibility.createMessageNotification(getApplicationContext(), notif.numberOfUnreadMessage, fromName, message, bm, notifContentIntent);
+
+ notifyWrapper(notif.notificationId, notification);
+ }
+
+ public void displayInappNotification(String message) {
+ Intent notifIntent = new Intent(this, LinphoneActivity.class);
+ notifIntent.putExtra("GoToInapp", true);
+
+ PendingIntent notifContentIntent = PendingIntent.getActivity(this, 0, notifIntent, PendingIntent.FLAG_UPDATE_CURRENT);
+ mNotif = Compatibility.createSimpleNotification(getApplicationContext(), getString(R.string.inapp_notification_title), message, notifContentIntent);
+
+ notifyWrapper(NOTIF_ID, mNotif);
+ }
+
+ public void displaySasNotification(String sas) {
+ mSasNotif = Compatibility.createSimpleNotification(getApplicationContext(),
+ getString(R.string.zrtp_notification_title),
+ sas + " " + getString(R.string.zrtp_notification_message),
+ null);
+
+ notifyWrapper(SAS_NOTIF_ID, mSasNotif);
+ }
+
+ public void removeSasNotification() {
+ mNM.cancel(SAS_NOTIF_ID);
+ }
+
+ private static final Class>[] mSetFgSign = new Class[]{boolean.class};
+ private static final Class>[] mStartFgSign = new Class[]{
+ int.class, Notification.class};
+ private static final Class>[] mStopFgSign = new Class[]{boolean.class};
+
+ private Method mStartForeground;
+ private Method mStopForeground;
+ private Object[] mSetForegroundArgs = new Object[1];
+ private Object[] mStartForegroundArgs = new Object[2];
+ private Object[] mStopForegroundArgs = new Object[1];
+ private String incomingReceivedActivityName;
+ private Class extends Activity> incomingReceivedActivity = LinphoneActivity.class;
+
+ void invokeMethod(Method method, Object[] args) {
+ try {
+ method.invoke(this, args);
+ } catch (InvocationTargetException e) {
+ // Should not happen.
+ Log.w(e, "Unable to invoke method");
+ } catch (IllegalAccessException e) {
+ // Should not happen.
+ Log.w(e, "Unable to invoke method");
+ }
+ }
+
+ /**
+ * This is a wrapper around the new startForeground method, using the older
+ * APIs if it is not available.
+ */
+ void startForegroundCompat(int id, Notification notification) {
+ // If we have the new startForeground API, then use it.
+ if (mStartForeground != null) {
+ mStartForegroundArgs[0] = Integer.valueOf(id);
+ mStartForegroundArgs[1] = notification;
+ invokeMethod(mStartForeground, mStartForegroundArgs);
+ return;
+ }
+
+ notifyWrapper(id, notification);
+ }
+
+ /**
+ * This is a wrapper around the new stopForeground method, using the older
+ * APIs if it is not available.
+ */
+ void stopForegroundCompat(int id) {
+ // If we have the new stopForeground API, then use it.
+ if (mStopForeground != null) {
+ mStopForegroundArgs[0] = Boolean.TRUE;
+ invokeMethod(mStopForeground, mStopForegroundArgs);
+ return;
+ }
+
+ // Fall back on the old API. Note to cancel BEFORE changing the
+ // foreground state, since we could be killed at that point.
+ mNM.cancel(id);
+ }
+
+ private void dumpDeviceInformation() {
+ StringBuilder sb = new StringBuilder();
+ sb.append("DEVICE=").append(Build.DEVICE).append("\n");
+ sb.append("MODEL=").append(Build.MODEL).append("\n");
+ sb.append("MANUFACTURER=").append(Build.MANUFACTURER).append("\n");
+ sb.append("SDK=").append(Build.VERSION.SDK_INT).append("\n");
+ sb.append("Supported ABIs=");
+ for (String abi : Version.getCpuAbis()) {
+ sb.append(abi + ", ");
+ }
+ sb.append("\n");
+ Log.i(sb.toString());
+ }
+
+ private void dumpInstalledLinphoneInformation() {
+ PackageInfo info = null;
+ try {
+ info = getPackageManager().getPackageInfo(getPackageName(), 0);
+ } catch (NameNotFoundException nnfe) {
+ }
+
+ if (info != null) {
+ Log.i("Linphone version is ", info.versionName + " (" + info.versionCode + ")");
+ } else {
+ Log.i("Linphone version is unknown");
+ }
+ }
+
+ private synchronized void sendNotification(int level, int textId) {
+ String text = getString(textId);
+ if (text.contains("%s") && LinphoneManager.getLc() != null) {
+ // Test for null lc is to avoid a NPE when Android mess up badly with the String resources.
+ ProxyConfig lpc = LinphoneManager.getLc().getDefaultProxyConfig();
+ String id = lpc != null ? lpc.getIdentityAddress().asString() : "";
+ text = String.format(text, id);
+ }
+
+ Bitmap bm = null;
+ try {
+ bm = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
+ } catch (Exception e) {
+ }
+ mNotif = Compatibility.createNotification(this, mNotificationTitle, text, R.drawable.status_level, 0, bm, mNotifContentIntent, true, notifcationsPriority);
+ notifyWrapper(NOTIF_ID, mNotif);
+ }
+
+ /**
+ * Wrap notifier to avoid setting the linphone icons while the service
+ * is stopping. When the (rare) bug is triggered, the linphone icon is
+ * present despite the service is not running. To trigger it one could
+ * stop linphone as soon as it is started. Transport configured with TLS.
+ */
+ private synchronized void notifyWrapper(int id, Notification notification) {
+ if (instance != null && notification != null) {
+ mNM.notify(id, notification);
+ } else {
+ Log.i("Service not ready, discarding notification");
+ }
+ }
+
+ @Override
+ public IBinder onBind(Intent intent) {
+ return null;
+ }
+
+ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
+ @Override
+ public void onTaskRemoved(Intent rootIntent) {
+ if (getResources().getBoolean(R.bool.kill_service_with_task_manager)) {
+ Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ if (lc != null) {
+ lc.terminateAllCalls();
+ }
+
+ Log.d("Task removed, stop service");
+
+ // If push is enabled, don't unregister account, otherwise do unregister
+ if (LinphonePreferences.instance().isPushNotificationEnabled()) {
+ if (lc != null) lc.setNetworkReachable(false);
+ }
+ stopSelf();
+ }
+ super.onTaskRemoved(rootIntent);
+ }
+
+ @Override
+ public synchronized void onDestroy() {
+ if (activityCallbacks != null) {
+ getApplication().unregisterActivityLifecycleCallbacks(activityCallbacks);
+ activityCallbacks = null;
+ }
+
+ destroyOverlay();
+ Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ if (lc != null) {
+ lc.removeListener(mListener);
+ }
+
+ instance = null;
+ LinphoneManager.destroy();
+
+ // Make sure our notification is gone.
+ stopForegroundCompat(NOTIF_ID);
+ mNM.cancel(INCALL_NOTIF_ID);
+ for (Notified notif : mChatNotifMap.values()) {
+ mNM.cancel(notif.notificationId);
+ }
+
+
+ // This will prevent the app from crashing if the service gets killed in background mode
+ if (LinphoneActivity.isInstanciated()) {
+ Log.w("Service is getting destroyed, finish LinphoneActivity");
+ LinphoneActivity.instance().finish();
+ }
+
+ super.onDestroy();
+ }
+
+ @SuppressWarnings("unchecked")
+ public void setActivityToLaunchOnIncomingReceived(String activityName) {
+ try {
+ incomingReceivedActivity = (Class extends Activity>) Class.forName(activityName);
+ incomingReceivedActivityName = activityName;
+ LinphonePreferences.instance().setActivityToLaunchOnIncomingReceived(incomingReceivedActivityName);
+ } catch (ClassNotFoundException e) {
+ Log.e(e);
+ }
+ }
+
+ protected void onIncomingReceived() {
+ //wakeup linphone
+ startActivity(new Intent()
+ .setClass(this, incomingReceivedActivity)
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
+ }
}
diff --git a/src/android/org/linphone/LinphoneUtils.java b/src/android/org/linphone/LinphoneUtils.java
index cf21cad46..afe1fcd88 100644
--- a/src/android/org/linphone/LinphoneUtils.java
+++ b/src/android/org/linphone/LinphoneUtils.java
@@ -87,621 +87,621 @@ import static android.view.View.VISIBLE;
* Helpers.
*/
public final class LinphoneUtils {
- private static Context context = null;
- private static Handler mHandler = new Handler(Looper.getMainLooper());
+ private static Context context = null;
+ private static Handler mHandler = new Handler(Looper.getMainLooper());
- private LinphoneUtils() {
+ private LinphoneUtils() {
- }
-
- public static void initLoggingService(boolean isDebugEnabled, String appName) {
- if (!LinphonePreferences.instance().useJavaLogger()) {
- Factory.instance().enableLogCollection(LogCollectionState.Enabled);
- Factory.instance().setDebugMode(isDebugEnabled, appName);
- } else {
- Factory.instance().setDebugMode(isDebugEnabled, appName);
- Factory.instance().enableLogCollection(LogCollectionState.EnabledWithoutPreviousLogHandler);
- Factory.instance().getLoggingService().setListener(new LoggingServiceListener() {
- @Override
- public void onLogMessageWritten(LoggingService logService, String domain, LogLevel lev, String message) {
- switch (lev) {
- case Debug:
- android.util.Log.d(domain, message);
- break;
- case Message:
- android.util.Log.i(domain, message);
- break;
- case Warning:
- android.util.Log.w(domain, message);
- break;
- case Error:
- android.util.Log.e(domain, message);
- break;
- case Fatal:
- default:
- android.util.Log.wtf(domain, message);
- break;
- }
- }
- });
- }
- }
-
- public static void dispatchOnUIThread(Runnable r) {
- mHandler.post(r);
- }
-
- //private static final String sipAddressRegExp = "^(sip:)?(\\+)?[a-z0-9]+([_\\.-][a-z0-9]+)*@([a-z0-9]+([\\.-][a-z0-9]+)*)+\\.[a-z]{2,}(:[0-9]{2,5})?$";
- //private static final String strictSipAddressRegExp = "^sip:(\\+)?[a-z0-9]+([_\\.-][a-z0-9]+)*@([a-z0-9]+([\\.-][a-z0-9]+)*)+\\.[a-z]{2,}$";
-
- public static boolean isSipAddress(String numberOrAddress) {
- Factory.instance().createAddress(numberOrAddress);
- return true;
- }
-
- public static boolean isNumberAddress(String numberOrAddress) {
- ProxyConfig proxy = LinphoneManager.getLc().createProxyConfig();
- return proxy.normalizePhoneNumber(numberOrAddress) != null;
- }
-
- public static boolean isStrictSipAddress(String numberOrAddress) {
- return isSipAddress(numberOrAddress) && numberOrAddress.startsWith("sip:");
- }
-
- public static String getAddressDisplayName(String uri){
- Address lAddress;
- lAddress = Factory.instance().createAddress(uri);
- return getAddressDisplayName(lAddress);
- }
-
- public static String getAddressDisplayName(Address address) {
- if (address == null) return null;
-
- String displayName = address.getDisplayName();
- if (displayName == null || displayName.isEmpty()) {
- displayName = address.getUsername();
- }
- if (displayName == null || displayName.isEmpty()) {
- displayName = address.asStringUriOnly();
- }
- return displayName;
- }
-
- public static String getUsernameFromAddress(String address) {
- if (address.contains("sip:"))
- address = address.replace("sip:", "");
-
- if (address.contains("@"))
- address = address.split("@")[0];
-
- return address;
- }
-
- public static boolean onKeyBackGoHome(Activity activity, int keyCode, KeyEvent event) {
- if (!(keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)) {
- return false; // continue
- }
-
- activity.startActivity(new Intent()
- .setAction(Intent.ACTION_MAIN)
- .addCategory(Intent.CATEGORY_HOME));
- return true;
- }
-
- public static String timestampToHumanDate(Context context, long timestamp, int resFormat) {
- return LinphoneUtils.timestampToHumanDate(context, timestamp, context.getString(resFormat));
- }
-
- public static String timestampToHumanDate(Context context, long timestamp, String format) {
- try {
- Calendar cal = Calendar.getInstance();
- cal.setTimeInMillis(timestamp * 1000); // Core returns timestamps in seconds...
-
- SimpleDateFormat dateFormat;
- if (isToday(cal)) {
- dateFormat = new SimpleDateFormat(context.getResources().getString(R.string.today_date_format), Locale.getDefault());
- } else {
- dateFormat = new SimpleDateFormat(format, Locale.getDefault());
- }
-
- return dateFormat.format(cal.getTime());
- } catch (NumberFormatException nfe) {
- return String.valueOf(timestamp);
- }
- }
-
- static boolean isToday(Calendar cal) {
- return isSameDay(cal, Calendar.getInstance());
- }
-
- static boolean isSameDay(Calendar cal1, Calendar cal2) {
- if (cal1 == null || cal2 == null) {
- return false;
- }
-
- return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) &&
- cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
- cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR));
- }
-
- public static boolean onKeyVolumeAdjust(int keyCode) {
- if (!((keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)
- && (Hacks.needSoftvolume())|| Build.VERSION.SDK_INT >= 15)) {
- return false; // continue
- }
-
- if (!LinphoneService.isReady()) {
- Log.i("Couldn't change softvolume has service is not running");
- return true;
- } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
- LinphoneManager.getInstance().adjustVolume(1);
- } else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
- LinphoneManager.getInstance().adjustVolume(-1);
- }
- return true;
- }
-
-
-
-
-
- public static Bitmap downloadBitmap(Uri uri) {
- URL url;
- InputStream is = null;
- try {
- url = new URL(uri.toString());
- is = url.openStream();
- return BitmapFactory.decodeStream(is);
- } catch (MalformedURLException e) {
- Log.e(e, e.getMessage());
- } catch (IOException e) {
- Log.e(e, e.getMessage());
- } finally {
- try {is.close();} catch (IOException x) {}
- }
- return null;
- }
-
-
- public static void setImagePictureFromUri(Context c, ImageView view, Uri pictureUri, Uri thumbnailUri) {
- if (pictureUri == null && thumbnailUri == null) {
- view.setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap());
- return;
- }
- if (pictureUri.getScheme().startsWith("http")) {
- Bitmap bm = downloadBitmap(pictureUri);
- if (bm == null) view.setImageResource(R.drawable.avatar);
- view.setImageBitmap(bm);
- } else {
- Bitmap bm = null;
- try {
- bm = MediaStore.Images.Media.getBitmap(c.getContentResolver(), pictureUri);
- } catch (IOException e) {
- if (thumbnailUri != null) {
- try {
- bm = MediaStore.Images.Media.getBitmap(c.getContentResolver(), thumbnailUri);
- } catch (IOException ie) {
- }
- }
- }
- if (bm != null) {
- view.setImageBitmap(bm);
- } else {
- view.setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap());
- }
- }
- }
-
- public static void setThumbnailPictureFromUri(Context c, ImageView view, Uri tUri) {
- if (tUri == null) {
- view.setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap());
- return;
- }
- if (tUri.getScheme().startsWith("http")) {
- Bitmap bm = downloadBitmap(tUri);
- if (bm == null) view.setImageResource(R.drawable.avatar);
- view.setImageBitmap(bm);
- } else {
- Bitmap bm = null;
- try {
- bm = MediaStore.Images.Media.getBitmap(c.getContentResolver(),tUri);
- } catch (IOException e) {
- return;
- }
- if (bm != null) {
- view.setImageBitmap(bm);
- } else {
- view.setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap());
- }
- }
- }
-
- public static final List getCalls(Core lc) {
- // return a modifiable list
- return new ArrayList<>(Arrays.asList(lc.getCalls()));
- }
-
- public static final List getCallsInState(Core lc, Collection states) {
- List foundCalls = new ArrayList<>();
- for (Call call : getCalls(lc)) {
- if (states.contains(call.getState())) {
- foundCalls.add(call);
- }
- }
- return foundCalls;
- }
-
- public static void setVisibility(View v, int id, boolean visible) {
- v.findViewById(id).setVisibility(visible ? VISIBLE : GONE);
- }
- public static void setVisibility(View v, boolean visible) {
- v.setVisibility(visible ? VISIBLE : GONE);
- }
-
- public static boolean isCallRunning(Call call)
- {
- if (call == null) {
- return false;
- }
-
- Call.State state = call.getState();
-
- return state == Call.State.Connected ||
- state == Call.State.Updating ||
- state == Call.State.UpdatedByRemote ||
- state == Call.State.StreamsRunning ||
- state == Call.State.Resuming;
- }
-
- public static boolean isCallEstablished(Call call) {
- if (call == null) {
- return false;
- }
-
- Call.State state = call.getState();
-
- return isCallRunning(call) ||
- state == Call.State.Paused ||
- state == Call.State.PausedByRemote ||
- state == Call.State.Pausing;
- }
-
- public static boolean isHighBandwidthConnection(Context context){
- ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
- NetworkInfo info = cm.getActiveNetworkInfo();
- return (info != null && info.isConnected() && isConnectionFast(info.getType(),info.getSubtype()));
}
- private static boolean isConnectionFast(int type, int subType){
- if (type == ConnectivityManager.TYPE_MOBILE) {
- switch (subType) {
- case TelephonyManager.NETWORK_TYPE_EDGE:
- case TelephonyManager.NETWORK_TYPE_GPRS:
- case TelephonyManager.NETWORK_TYPE_IDEN:
- return false;
+ public static void initLoggingService(boolean isDebugEnabled, String appName) {
+ if (!LinphonePreferences.instance().useJavaLogger()) {
+ Factory.instance().enableLogCollection(LogCollectionState.Enabled);
+ Factory.instance().setDebugMode(isDebugEnabled, appName);
+ } else {
+ Factory.instance().setDebugMode(isDebugEnabled, appName);
+ Factory.instance().enableLogCollection(LogCollectionState.EnabledWithoutPreviousLogHandler);
+ Factory.instance().getLoggingService().setListener(new LoggingServiceListener() {
+ @Override
+ public void onLogMessageWritten(LoggingService logService, String domain, LogLevel lev, String message) {
+ switch (lev) {
+ case Debug:
+ android.util.Log.d(domain, message);
+ break;
+ case Message:
+ android.util.Log.i(domain, message);
+ break;
+ case Warning:
+ android.util.Log.w(domain, message);
+ break;
+ case Error:
+ android.util.Log.e(domain, message);
+ break;
+ case Fatal:
+ default:
+ android.util.Log.wtf(domain, message);
+ break;
+ }
+ }
+ });
+ }
+ }
+
+ public static void dispatchOnUIThread(Runnable r) {
+ mHandler.post(r);
+ }
+
+ //private static final String sipAddressRegExp = "^(sip:)?(\\+)?[a-z0-9]+([_\\.-][a-z0-9]+)*@([a-z0-9]+([\\.-][a-z0-9]+)*)+\\.[a-z]{2,}(:[0-9]{2,5})?$";
+ //private static final String strictSipAddressRegExp = "^sip:(\\+)?[a-z0-9]+([_\\.-][a-z0-9]+)*@([a-z0-9]+([\\.-][a-z0-9]+)*)+\\.[a-z]{2,}$";
+
+ public static boolean isSipAddress(String numberOrAddress) {
+ Factory.instance().createAddress(numberOrAddress);
+ return true;
+ }
+
+ public static boolean isNumberAddress(String numberOrAddress) {
+ ProxyConfig proxy = LinphoneManager.getLc().createProxyConfig();
+ return proxy.normalizePhoneNumber(numberOrAddress) != null;
+ }
+
+ public static boolean isStrictSipAddress(String numberOrAddress) {
+ return isSipAddress(numberOrAddress) && numberOrAddress.startsWith("sip:");
+ }
+
+ public static String getAddressDisplayName(String uri) {
+ Address lAddress;
+ lAddress = Factory.instance().createAddress(uri);
+ return getAddressDisplayName(lAddress);
+ }
+
+ public static String getAddressDisplayName(Address address) {
+ if (address == null) return null;
+
+ String displayName = address.getDisplayName();
+ if (displayName == null || displayName.isEmpty()) {
+ displayName = address.getUsername();
+ }
+ if (displayName == null || displayName.isEmpty()) {
+ displayName = address.asStringUriOnly();
+ }
+ return displayName;
+ }
+
+ public static String getUsernameFromAddress(String address) {
+ if (address.contains("sip:"))
+ address = address.replace("sip:", "");
+
+ if (address.contains("@"))
+ address = address.split("@")[0];
+
+ return address;
+ }
+
+ public static boolean onKeyBackGoHome(Activity activity, int keyCode, KeyEvent event) {
+ if (!(keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)) {
+ return false; // continue
+ }
+
+ activity.startActivity(new Intent()
+ .setAction(Intent.ACTION_MAIN)
+ .addCategory(Intent.CATEGORY_HOME));
+ return true;
+ }
+
+ public static String timestampToHumanDate(Context context, long timestamp, int resFormat) {
+ return LinphoneUtils.timestampToHumanDate(context, timestamp, context.getString(resFormat));
+ }
+
+ public static String timestampToHumanDate(Context context, long timestamp, String format) {
+ try {
+ Calendar cal = Calendar.getInstance();
+ cal.setTimeInMillis(timestamp * 1000); // Core returns timestamps in seconds...
+
+ SimpleDateFormat dateFormat;
+ if (isToday(cal)) {
+ dateFormat = new SimpleDateFormat(context.getResources().getString(R.string.today_date_format), Locale.getDefault());
+ } else {
+ dateFormat = new SimpleDateFormat(format, Locale.getDefault());
}
- }
+
+ return dateFormat.format(cal.getTime());
+ } catch (NumberFormatException nfe) {
+ return String.valueOf(timestamp);
+ }
+ }
+
+ static boolean isToday(Calendar cal) {
+ return isSameDay(cal, Calendar.getInstance());
+ }
+
+ static boolean isSameDay(Calendar cal1, Calendar cal2) {
+ if (cal1 == null || cal2 == null) {
+ return false;
+ }
+
+ return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) &&
+ cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
+ cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR));
+ }
+
+ public static boolean onKeyVolumeAdjust(int keyCode) {
+ if (!((keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)
+ && (Hacks.needSoftvolume()) || Build.VERSION.SDK_INT >= 15)) {
+ return false; // continue
+ }
+
+ if (!LinphoneService.isReady()) {
+ Log.i("Couldn't change softvolume has service is not running");
+ return true;
+ } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
+ LinphoneManager.getInstance().adjustVolume(1);
+ } else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
+ LinphoneManager.getInstance().adjustVolume(-1);
+ }
+ return true;
+ }
+
+
+ public static Bitmap downloadBitmap(Uri uri) {
+ URL url;
+ InputStream is = null;
+ try {
+ url = new URL(uri.toString());
+ is = url.openStream();
+ return BitmapFactory.decodeStream(is);
+ } catch (MalformedURLException e) {
+ Log.e(e, e.getMessage());
+ } catch (IOException e) {
+ Log.e(e, e.getMessage());
+ } finally {
+ try {
+ is.close();
+ } catch (IOException x) {
+ }
+ }
+ return null;
+ }
+
+
+ public static void setImagePictureFromUri(Context c, ImageView view, Uri pictureUri, Uri thumbnailUri) {
+ if (pictureUri == null && thumbnailUri == null) {
+ view.setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap());
+ return;
+ }
+ if (pictureUri.getScheme().startsWith("http")) {
+ Bitmap bm = downloadBitmap(pictureUri);
+ if (bm == null) view.setImageResource(R.drawable.avatar);
+ view.setImageBitmap(bm);
+ } else {
+ Bitmap bm = null;
+ try {
+ bm = MediaStore.Images.Media.getBitmap(c.getContentResolver(), pictureUri);
+ } catch (IOException e) {
+ if (thumbnailUri != null) {
+ try {
+ bm = MediaStore.Images.Media.getBitmap(c.getContentResolver(), thumbnailUri);
+ } catch (IOException ie) {
+ }
+ }
+ }
+ if (bm != null) {
+ view.setImageBitmap(bm);
+ } else {
+ view.setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap());
+ }
+ }
+ }
+
+ public static void setThumbnailPictureFromUri(Context c, ImageView view, Uri tUri) {
+ if (tUri == null) {
+ view.setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap());
+ return;
+ }
+ if (tUri.getScheme().startsWith("http")) {
+ Bitmap bm = downloadBitmap(tUri);
+ if (bm == null) view.setImageResource(R.drawable.avatar);
+ view.setImageBitmap(bm);
+ } else {
+ Bitmap bm = null;
+ try {
+ bm = MediaStore.Images.Media.getBitmap(c.getContentResolver(), tUri);
+ } catch (IOException e) {
+ return;
+ }
+ if (bm != null) {
+ view.setImageBitmap(bm);
+ } else {
+ view.setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap());
+ }
+ }
+ }
+
+ public static final List getCalls(Core lc) {
+ // return a modifiable list
+ return new ArrayList<>(Arrays.asList(lc.getCalls()));
+ }
+
+ public static final List getCallsInState(Core lc, Collection states) {
+ List foundCalls = new ArrayList<>();
+ for (Call call : getCalls(lc)) {
+ if (states.contains(call.getState())) {
+ foundCalls.add(call);
+ }
+ }
+ return foundCalls;
+ }
+
+ public static void setVisibility(View v, int id, boolean visible) {
+ v.findViewById(id).setVisibility(visible ? VISIBLE : GONE);
+ }
+
+ public static void setVisibility(View v, boolean visible) {
+ v.setVisibility(visible ? VISIBLE : GONE);
+ }
+
+ public static boolean isCallRunning(Call call) {
+ if (call == null) {
+ return false;
+ }
+
+ Call.State state = call.getState();
+
+ return state == Call.State.Connected ||
+ state == Call.State.Updating ||
+ state == Call.State.UpdatedByRemote ||
+ state == Call.State.StreamsRunning ||
+ state == Call.State.Resuming;
+ }
+
+ public static boolean isCallEstablished(Call call) {
+ if (call == null) {
+ return false;
+ }
+
+ Call.State state = call.getState();
+
+ return isCallRunning(call) ||
+ state == Call.State.Paused ||
+ state == Call.State.PausedByRemote ||
+ state == Call.State.Pausing;
+ }
+
+ public static boolean isHighBandwidthConnection(Context context) {
+ ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
+ NetworkInfo info = cm.getActiveNetworkInfo();
+ return (info != null && info.isConnected() && isConnectionFast(info.getType(), info.getSubtype()));
+ }
+
+ private static boolean isConnectionFast(int type, int subType) {
+ if (type == ConnectivityManager.TYPE_MOBILE) {
+ switch (subType) {
+ case TelephonyManager.NETWORK_TYPE_EDGE:
+ case TelephonyManager.NETWORK_TYPE_GPRS:
+ case TelephonyManager.NETWORK_TYPE_IDEN:
+ return false;
+ }
+ }
//in doubt, assume connection is good.
return true;
}
- public static String getNameFromFilePath(String filePath) {
- String name = filePath;
- int i = filePath.lastIndexOf('/');
- if (i > 0) {
- name = filePath.substring(i+1);
- }
- return name;
- }
+ public static String getNameFromFilePath(String filePath) {
+ String name = filePath;
+ int i = filePath.lastIndexOf('/');
+ if (i > 0) {
+ name = filePath.substring(i + 1);
+ }
+ return name;
+ }
- public static String getExtensionFromFileName(String fileName) {
- String extension = null;
- int i = fileName.lastIndexOf('.');
- if (i > 0) {
- extension = fileName.substring(i+1);
- }
- return extension;
- }
+ public static String getExtensionFromFileName(String fileName) {
+ String extension = null;
+ int i = fileName.lastIndexOf('.');
+ if (i > 0) {
+ extension = fileName.substring(i + 1);
+ }
+ return extension;
+ }
- public static Boolean isExtensionImage(String path){
- String extension = LinphoneUtils.getExtensionFromFileName(path);
- if(extension != null)
- extension = extension.toLowerCase();
- return (extension != null && extension.matches("(png|jpg|jpeg|bmp|gif)"));
- }
+ public static Boolean isExtensionImage(String path) {
+ String extension = LinphoneUtils.getExtensionFromFileName(path);
+ if (extension != null)
+ extension = extension.toLowerCase();
+ return (extension != null && extension.matches("(png|jpg|jpeg|bmp|gif)"));
+ }
- public static void recursiveFileRemoval(File root) {
- if (!root.delete()) {
- if (root.isDirectory()) {
- File[] files = root.listFiles();
- if (files != null) {
- for (File f : files) {
- recursiveFileRemoval(f);
- }
- }
- }
- }
- }
+ public static void recursiveFileRemoval(File root) {
+ if (!root.delete()) {
+ if (root.isDirectory()) {
+ File[] files = root.listFiles();
+ if (files != null) {
+ for (File f : files) {
+ recursiveFileRemoval(f);
+ }
+ }
+ }
+ }
+ }
- public static String getDisplayableUsernameFromAddress(String sipAddress) {
- String username = sipAddress;
- Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- if (lc == null) return username;
+ public static String getDisplayableUsernameFromAddress(String sipAddress) {
+ String username = sipAddress;
+ Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ if (lc == null) return username;
- if (username.startsWith("sip:")) {
- username = username.substring(4);
- }
+ if (username.startsWith("sip:")) {
+ username = username.substring(4);
+ }
- if (username.contains("@")) {
- String domain = username.split("@")[1];
- ProxyConfig lpc = lc.getDefaultProxyConfig();
- if (lpc != null) {
- if (domain.equals(lpc.getDomain())) {
- return username.split("@")[0];
- }
- } else {
- if (domain.equals(LinphoneManager.getInstance().getContext().getString(R.string.default_domain))) {
- return username.split("@")[0];
- }
- }
- }
- return username;
- }
+ if (username.contains("@")) {
+ String domain = username.split("@")[1];
+ ProxyConfig lpc = lc.getDefaultProxyConfig();
+ if (lpc != null) {
+ if (domain.equals(lpc.getDomain())) {
+ return username.split("@")[0];
+ }
+ } else {
+ if (domain.equals(LinphoneManager.getInstance().getContext().getString(R.string.default_domain))) {
+ return username.split("@")[0];
+ }
+ }
+ }
+ return username;
+ }
- public static String getFullAddressFromUsername(String username) {
- String sipAddress = username;
- Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- if (lc == null || username == null) return sipAddress;
+ public static String getFullAddressFromUsername(String username) {
+ String sipAddress = username;
+ Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ if (lc == null || username == null) return sipAddress;
- if (!sipAddress.startsWith("sip:")) {
- sipAddress = "sip:" + sipAddress;
- }
+ if (!sipAddress.startsWith("sip:")) {
+ sipAddress = "sip:" + sipAddress;
+ }
- if (!sipAddress.contains("@")) {
- ProxyConfig lpc = lc.getDefaultProxyConfig();
- if (lpc != null) {
- sipAddress = sipAddress + "@" + lpc.getDomain();
- } else {
- sipAddress = sipAddress + "@" + LinphoneManager.getInstance().getContext().getString(R.string.default_domain);
- }
- }
- return sipAddress;
- }
+ if (!sipAddress.contains("@")) {
+ ProxyConfig lpc = lc.getDefaultProxyConfig();
+ if (lpc != null) {
+ sipAddress = sipAddress + "@" + lpc.getDomain();
+ } else {
+ sipAddress = sipAddress + "@" + LinphoneManager.getInstance().getContext().getString(R.string.default_domain);
+ }
+ }
+ return sipAddress;
+ }
- private static Context getContext() {
- if (context == null && LinphoneManager.isInstanciated())
- context = LinphoneManager.getInstance().getContext();
- return context;
- }
+ private static Context getContext() {
+ if (context == null && LinphoneManager.isInstanciated())
+ context = LinphoneManager.getInstance().getContext();
+ return context;
+ }
- public static void displayError(boolean isOk, TextView error, String errorText) {
- if (isOk) {
- error.setVisibility(View.INVISIBLE);
- error.setText("");
- } else {
- error.setVisibility(View.VISIBLE);
- error.setText(errorText);
- }
- }
+ public static void displayError(boolean isOk, TextView error, String errorText) {
+ if (isOk) {
+ error.setVisibility(View.INVISIBLE);
+ error.setText("");
+ } else {
+ error.setVisibility(View.VISIBLE);
+ error.setText(errorText);
+ }
+ }
- public static String errorForPhoneNumberStatus(int status) {
- Context ctxt = getContext();
- if (ctxt != null) {
- if (AccountCreator.PhoneNumberStatus.InvalidCountryCode.toInt()
- == (status & AccountCreator.PhoneNumberStatus.InvalidCountryCode.toInt()))
- return ctxt.getString(R.string.country_code_invalid);
- if (AccountCreator.PhoneNumberStatus.TooShort.toInt()
- == (status & AccountCreator.PhoneNumberStatus.TooShort.toInt()))
- return ctxt.getString(R.string.phone_number_too_short);
- if (AccountCreator.PhoneNumberStatus.TooLong.toInt()
- == (status & AccountCreator.PhoneNumberStatus.TooLong.toInt()))
- return ctxt.getString(R.string.phone_number_too_long);
- if (AccountCreator.PhoneNumberStatus.Invalid.toInt()
- == (status & AccountCreator.PhoneNumberStatus.Invalid.toInt()))
- return ctxt.getString(R.string.phone_number_invalid);
- }
- return null;
- }
+ public static String errorForPhoneNumberStatus(int status) {
+ Context ctxt = getContext();
+ if (ctxt != null) {
+ if (AccountCreator.PhoneNumberStatus.InvalidCountryCode.toInt()
+ == (status & AccountCreator.PhoneNumberStatus.InvalidCountryCode.toInt()))
+ return ctxt.getString(R.string.country_code_invalid);
+ if (AccountCreator.PhoneNumberStatus.TooShort.toInt()
+ == (status & AccountCreator.PhoneNumberStatus.TooShort.toInt()))
+ return ctxt.getString(R.string.phone_number_too_short);
+ if (AccountCreator.PhoneNumberStatus.TooLong.toInt()
+ == (status & AccountCreator.PhoneNumberStatus.TooLong.toInt()))
+ return ctxt.getString(R.string.phone_number_too_long);
+ if (AccountCreator.PhoneNumberStatus.Invalid.toInt()
+ == (status & AccountCreator.PhoneNumberStatus.Invalid.toInt()))
+ return ctxt.getString(R.string.phone_number_invalid);
+ }
+ return null;
+ }
- public static String errorForEmailStatus(AccountCreator.EmailStatus status) {
- Context ctxt = getContext();
- if (ctxt != null) {
- if (status.equals(AccountCreator.EmailStatus.InvalidCharacters)
- || status.equals(AccountCreator.EmailStatus.Malformed))
- return ctxt.getString(R.string.invalid_email);
- }
- return null;
- }
+ public static String errorForEmailStatus(AccountCreator.EmailStatus status) {
+ Context ctxt = getContext();
+ if (ctxt != null) {
+ if (status.equals(AccountCreator.EmailStatus.InvalidCharacters)
+ || status.equals(AccountCreator.EmailStatus.Malformed))
+ return ctxt.getString(R.string.invalid_email);
+ }
+ return null;
+ }
- public static String errorForUsernameStatus(AccountCreator.UsernameStatus status) {
- Context ctxt = getContext();
- if (ctxt != null) {
- if (status.equals(AccountCreator.UsernameStatus.InvalidCharacters))
- return ctxt.getString(R.string.invalid_username);
- if (status.equals(AccountCreator.UsernameStatus.TooShort))
- return ctxt.getString(R.string.username_too_short);
- if (status.equals(AccountCreator.UsernameStatus.TooLong))
- return ctxt.getString(R.string.username_too_long);
- if (status.equals(AccountCreator.UsernameStatus.Invalid))
- return ctxt.getString(R.string.username_invalid_size);
- if (status.equals(AccountCreator.UsernameStatus.InvalidCharacters))
- return ctxt.getString(R.string.invalid_display_name);
- }
- return null;
- }
+ public static String errorForUsernameStatus(AccountCreator.UsernameStatus status) {
+ Context ctxt = getContext();
+ if (ctxt != null) {
+ if (status.equals(AccountCreator.UsernameStatus.InvalidCharacters))
+ return ctxt.getString(R.string.invalid_username);
+ if (status.equals(AccountCreator.UsernameStatus.TooShort))
+ return ctxt.getString(R.string.username_too_short);
+ if (status.equals(AccountCreator.UsernameStatus.TooLong))
+ return ctxt.getString(R.string.username_too_long);
+ if (status.equals(AccountCreator.UsernameStatus.Invalid))
+ return ctxt.getString(R.string.username_invalid_size);
+ if (status.equals(AccountCreator.UsernameStatus.InvalidCharacters))
+ return ctxt.getString(R.string.invalid_display_name);
+ }
+ return null;
+ }
- public static String errorForPasswordStatus(AccountCreator.PasswordStatus status) {
- Context ctxt = getContext();
- if (ctxt != null) {
- if (status.equals(AccountCreator.PasswordStatus.TooShort))
- return ctxt.getString(R.string.password_too_short);
- if (status.equals(AccountCreator.PasswordStatus.TooLong))
- return ctxt.getString(R.string.password_too_long);
- }
- return null;
- }
+ public static String errorForPasswordStatus(AccountCreator.PasswordStatus status) {
+ Context ctxt = getContext();
+ if (ctxt != null) {
+ if (status.equals(AccountCreator.PasswordStatus.TooShort))
+ return ctxt.getString(R.string.password_too_short);
+ if (status.equals(AccountCreator.PasswordStatus.TooLong))
+ return ctxt.getString(R.string.password_too_long);
+ }
+ return null;
+ }
- public static String errorForStatus(AccountCreator.Status status) {
- Context ctxt = getContext();
- if (ctxt != null) {
- if (status.equals(AccountCreator.Status.RequestFailed))
- return ctxt.getString(R.string.request_failed);
- if (status.equals(AccountCreator.Status.ServerError))
- return ctxt.getString(R.string.wizard_failed);
- if (status.equals(AccountCreator.Status.AccountExist)
- || status.equals(AccountCreator.Status.AccountExistWithAlias))
- return ctxt.getString(R.string.account_already_exist);
- if (status.equals(AccountCreator.Status.AliasIsAccount)
- || status.equals(AccountCreator.Status.AliasExist))
- return ctxt.getString(R.string.assistant_phone_number_unavailable);
- if (status.equals(AccountCreator.Status.AccountNotExist))
- return ctxt.getString(R.string.assistant_error_bad_credentials);
- if (status.equals(AccountCreator.Status.AliasNotExist))
- return ctxt.getString(R.string.phone_number_not_exist);
- if (status.equals(AccountCreator.Status.AliasNotExist)
- || status.equals(AccountCreator.Status.AccountNotActivated)
- || status.equals(AccountCreator.Status.AccountAlreadyActivated)
- || status.equals(AccountCreator.Status.AccountActivated)
- || status.equals(AccountCreator.Status.AccountNotCreated)
- || status.equals(AccountCreator.Status.RequestOk))
- return "";
- }
- return null;
- }
+ public static String errorForStatus(AccountCreator.Status status) {
+ Context ctxt = getContext();
+ if (ctxt != null) {
+ if (status.equals(AccountCreator.Status.RequestFailed))
+ return ctxt.getString(R.string.request_failed);
+ if (status.equals(AccountCreator.Status.ServerError))
+ return ctxt.getString(R.string.wizard_failed);
+ if (status.equals(AccountCreator.Status.AccountExist)
+ || status.equals(AccountCreator.Status.AccountExistWithAlias))
+ return ctxt.getString(R.string.account_already_exist);
+ if (status.equals(AccountCreator.Status.AliasIsAccount)
+ || status.equals(AccountCreator.Status.AliasExist))
+ return ctxt.getString(R.string.assistant_phone_number_unavailable);
+ if (status.equals(AccountCreator.Status.AccountNotExist))
+ return ctxt.getString(R.string.assistant_error_bad_credentials);
+ if (status.equals(AccountCreator.Status.AliasNotExist))
+ return ctxt.getString(R.string.phone_number_not_exist);
+ if (status.equals(AccountCreator.Status.AliasNotExist)
+ || status.equals(AccountCreator.Status.AccountNotActivated)
+ || status.equals(AccountCreator.Status.AccountAlreadyActivated)
+ || status.equals(AccountCreator.Status.AccountActivated)
+ || status.equals(AccountCreator.Status.AccountNotCreated)
+ || status.equals(AccountCreator.Status.RequestOk))
+ return "";
+ }
+ return null;
+ }
- public static String getCountryCode(EditText dialCode) {
- if(dialCode != null) {
- String code = dialCode.getText().toString();
- if(code != null && code.startsWith("+")) {
- code = code.substring(1);
- }
- return code;
- }
- return null;
- }
+ public static String getCountryCode(EditText dialCode) {
+ if (dialCode != null) {
+ String code = dialCode.getText().toString();
+ if (code != null && code.startsWith("+")) {
+ code = code.substring(1);
+ }
+ return code;
+ }
+ return null;
+ }
- public static void displayErrorAlert(String msg, Context ctxt) {
- if (ctxt != null && msg != null) {
- AlertDialog.Builder builder = new AlertDialog.Builder(ctxt);
- builder.setMessage(msg)
- .setCancelable(false)
- .setNeutralButton(ctxt.getString(R.string.ok), null)
- .show();
- }
- }
+ public static void displayErrorAlert(String msg, Context ctxt) {
+ if (ctxt != null && msg != null) {
+ AlertDialog.Builder builder = new AlertDialog.Builder(ctxt);
+ builder.setMessage(msg)
+ .setCancelable(false)
+ .setNeutralButton(ctxt.getString(R.string.ok), null)
+ .show();
+ }
+ }
- public static String getFilePath(final Context context, final Uri uri) {
- if (uri == null) return null;
+ public static String getFilePath(final Context context, final Uri uri) {
+ if (uri == null) return null;
- String result = null;
- String name = getNameFromUri(uri, context);
+ String result = null;
+ String name = getNameFromUri(uri, context);
- try {
- File localFile = createFile(context, name);
- InputStream remoteFile = context.getContentResolver().openInputStream(uri);
+ try {
+ File localFile = createFile(context, name);
+ InputStream remoteFile = context.getContentResolver().openInputStream(uri);
- if(copyToFile(remoteFile, localFile)) {
- result = localFile.getAbsolutePath();
- }
+ if (copyToFile(remoteFile, localFile)) {
+ result = localFile.getAbsolutePath();
+ }
- remoteFile.close();
- } catch (IOException e) {
- Log.e("Enable to get sharing file", e);
- }
+ remoteFile.close();
+ } catch (IOException e) {
+ Log.e("Enable to get sharing file", e);
+ }
- return result;
- }
+ return result;
+ }
- private static String getNameFromUri(Uri uri, Context context) {
- String name = null;
- if (uri.getScheme().equals("content")) {
- Cursor returnCursor = context.getContentResolver().query(uri, null, null, null, null);
- if (returnCursor != null) {
- returnCursor.moveToFirst();
- int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
- name = returnCursor.getString(nameIndex);
- returnCursor.close();
- }
- } else if (uri.getScheme().equals("file")) {
- name = uri.getLastPathSegment();
- }
- return name;
- }
+ private static String getNameFromUri(Uri uri, Context context) {
+ String name = null;
+ if (uri.getScheme().equals("content")) {
+ Cursor returnCursor = context.getContentResolver().query(uri, null, null, null, null);
+ if (returnCursor != null) {
+ returnCursor.moveToFirst();
+ int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
+ name = returnCursor.getString(nameIndex);
+ returnCursor.close();
+ }
+ } else if (uri.getScheme().equals("file")) {
+ name = uri.getLastPathSegment();
+ }
+ return name;
+ }
- /**
- * Copy data from a source stream to destFile.
- * Return true if succeed, return false if failed.
- */
- private static boolean copyToFile(InputStream inputStream, File destFile) {
- if (inputStream == null || destFile == null) return false;
- try {
- OutputStream out = new FileOutputStream(destFile);
- try {
- byte[] buffer = new byte[4096];
- int bytesRead;
- while ((bytesRead = inputStream.read(buffer)) >= 0) {
- out.write(buffer, 0, bytesRead);
- }
- } finally {
- out.close();
- }
- return true;
- } catch (IOException e) {
- return false;
- }
- }
+ /**
+ * Copy data from a source stream to destFile.
+ * Return true if succeed, return false if failed.
+ */
+ private static boolean copyToFile(InputStream inputStream, File destFile) {
+ if (inputStream == null || destFile == null) return false;
+ try {
+ OutputStream out = new FileOutputStream(destFile);
+ try {
+ byte[] buffer = new byte[4096];
+ int bytesRead;
+ while ((bytesRead = inputStream.read(buffer)) >= 0) {
+ out.write(buffer, 0, bytesRead);
+ }
+ } finally {
+ out.close();
+ }
+ return true;
+ } catch (IOException e) {
+ return false;
+ }
+ }
- public static String getStartDate() {
- try {
- return new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.ROOT).format(new Date());
- } catch (RuntimeException e) {
- return new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
- }
- }
+ public static String getStartDate() {
+ try {
+ return new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.ROOT).format(new Date());
+ } catch (RuntimeException e) {
+ return new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
+ }
+ }
- public static File createFile(Context context, String fileName) throws IOException {
- if (TextUtils.isEmpty(fileName))
- fileName = getStartDate();
+ public static File createFile(Context context, String fileName) throws IOException {
+ if (TextUtils.isEmpty(fileName))
+ fileName = getStartDate();
- if (!fileName.contains(".")) {
- fileName = fileName + ".unknown";
- }
+ if (!fileName.contains(".")) {
+ fileName = fileName + ".unknown";
+ }
- final File root;
- root = context.getExternalCacheDir();
+ final File root;
+ root = context.getExternalCacheDir();
- if (root != null && !root.exists())
- root.mkdirs();
- return new File(root, fileName);
- }
+ if (root != null && !root.exists())
+ root.mkdirs();
+ return new File(root, fileName);
+ }
- public static String getRealPathFromURI(Context context, Uri contentUri) {
- String[] proj = {MediaStore.Images.Media.DATA};
- Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
- if (cursor != null && cursor.moveToFirst()) {
- int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
- String result = cursor.getString(column_index);
- cursor.close();
- return result;
- }
- return null;
- }
+ public static String getRealPathFromURI(Context context, Uri contentUri) {
+ String[] proj = {MediaStore.Images.Media.DATA};
+ Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
+ if (cursor != null && cursor.moveToFirst()) {
+ int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
+ String result = cursor.getString(column_index);
+ cursor.close();
+ return result;
+ }
+ return null;
+ }
- public static String getContactNameFromVcard(String vcard){
- if(vcard != null) {
- String contactName = vcard.substring(vcard.indexOf("FN:") + 3);
- contactName = contactName.substring(0, contactName.indexOf("\n") - 1);
- contactName = contactName.replace(";", "");
- contactName = contactName.replace(" ", "");
- return contactName;
- }
- return null;
- }
+ public static String getContactNameFromVcard(String vcard) {
+ if (vcard != null) {
+ String contactName = vcard.substring(vcard.indexOf("FN:") + 3);
+ contactName = contactName.substring(0, contactName.indexOf("\n") - 1);
+ contactName = contactName.replace(";", "");
+ contactName = contactName.replace(" ", "");
+ return contactName;
+ }
+ return null;
+ }
- public static Uri createCvsFromString(String vcardString){
- String contactName = getContactNameFromVcard(vcardString);
- File vcfFile = new File(Environment.getExternalStorageDirectory(), contactName+".cvs");
+ public static Uri createCvsFromString(String vcardString) {
+ String contactName = getContactNameFromVcard(vcardString);
+ File vcfFile = new File(Environment.getExternalStorageDirectory(), contactName + ".cvs");
try {
FileWriter fw = new FileWriter(vcfFile);
fw.write(vcardString);
@@ -713,49 +713,49 @@ public final class LinphoneUtils {
return null;
}
- public static Spanned getTextWithHttpLinks(String text) {
- if (text == null) return null;
+ public static Spanned getTextWithHttpLinks(String text) {
+ if (text == null) return null;
- if (text.contains("<")) {
- text = text.replace("<", "<");
- }
- if (text.contains(">")) {
- text = text.replace(">", ">");
- }
- if (text.contains("\n")) {
- text = text.replace("\n", "
");
- }
- if (text.contains("http://")) {
- int indexHttp = text.indexOf("http://");
- int indexFinHttp = text.indexOf(" ", indexHttp) == -1 ? text.length() : text.indexOf(" ", indexHttp);
- String link = text.substring(indexHttp, indexFinHttp);
- String linkWithoutScheme = link.replace("http://", "");
- text = text.replaceFirst(Pattern.quote(link), "" + linkWithoutScheme + "");
- }
- if (text.contains("https://")) {
- int indexHttp = text.indexOf("https://");
- int indexFinHttp = text.indexOf(" ", indexHttp) == -1 ? text.length() : text.indexOf(" ", indexHttp);
- String link = text.substring(indexHttp, indexFinHttp);
- String linkWithoutScheme = link.replace("https://", "");
- text = text.replaceFirst(Pattern.quote(link), "" + linkWithoutScheme + "");
- }
+ if (text.contains("<")) {
+ text = text.replace("<", "<");
+ }
+ if (text.contains(">")) {
+ text = text.replace(">", ">");
+ }
+ if (text.contains("\n")) {
+ text = text.replace("\n", "
");
+ }
+ if (text.contains("http://")) {
+ int indexHttp = text.indexOf("http://");
+ int indexFinHttp = text.indexOf(" ", indexHttp) == -1 ? text.length() : text.indexOf(" ", indexHttp);
+ String link = text.substring(indexHttp, indexFinHttp);
+ String linkWithoutScheme = link.replace("http://", "");
+ text = text.replaceFirst(Pattern.quote(link), "" + linkWithoutScheme + "");
+ }
+ if (text.contains("https://")) {
+ int indexHttp = text.indexOf("https://");
+ int indexFinHttp = text.indexOf(" ", indexHttp) == -1 ? text.length() : text.indexOf(" ", indexHttp);
+ String link = text.substring(indexHttp, indexFinHttp);
+ String linkWithoutScheme = link.replace("https://", "");
+ text = text.replaceFirst(Pattern.quote(link), "" + linkWithoutScheme + "");
+ }
- return Compatibility.fromHtml(text);
- }
+ return Compatibility.fromHtml(text);
+ }
- public static Uri getCVSPathFromLookupUri(String content) {
- String contactId = LinphoneUtils.getNameFromFilePath(content);
- FriendList[] friendList = LinphoneManager.getLc().getFriendsLists();
- for (FriendList list : friendList) {
- for (Friend friend : list.getFriends()) {
- if (friend.getRefKey().toString().equals(contactId)) {
- String contactVcard = friend.getVcard().asVcard4String();
- Uri path = LinphoneUtils.createCvsFromString(contactVcard);
- return path;
- }
- }
- }
- return null;
- }
+ public static Uri getCVSPathFromLookupUri(String content) {
+ String contactId = LinphoneUtils.getNameFromFilePath(content);
+ FriendList[] friendList = LinphoneManager.getLc().getFriendsLists();
+ for (FriendList list : friendList) {
+ for (Friend friend : list.getFriends()) {
+ if (friend.getRefKey().toString().equals(contactId)) {
+ String contactVcard = friend.getVcard().asVcard4String();
+ Uri path = LinphoneUtils.createCvsFromString(contactVcard);
+ return path;
+ }
+ }
+ }
+ return null;
+ }
}
diff --git a/src/android/org/linphone/activities/LinphoneActivity.java b/src/android/org/linphone/activities/LinphoneActivity.java
index 837ee25be..819029165 100644
--- a/src/android/org/linphone/activities/LinphoneActivity.java
+++ b/src/android/org/linphone/activities/LinphoneActivity.java
@@ -27,7 +27,6 @@ import android.app.Dialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
-import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
@@ -54,7 +53,6 @@ import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
-import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
@@ -62,39 +60,30 @@ import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
-import org.linphone.call.CallActivity;
-import org.linphone.call.CallIncomingActivity;
-import org.linphone.call.CallOutgoingActivity;
-import org.linphone.chat.ImdnFragment;
-import org.linphone.contacts.ContactPicked;
-import org.linphone.fragments.AboutFragment;
-import org.linphone.fragments.AccountPreferencesFragment;
-import org.linphone.contacts.ContactAddress;
-import org.linphone.contacts.ContactDetailsFragment;
-import org.linphone.contacts.ContactEditorFragment;
-import org.linphone.contacts.ContactsListFragment;
-import org.linphone.contacts.ContactsManager;
-import org.linphone.fragments.DialerFragment;
-import org.linphone.fragments.EmptyFragment;
-import org.linphone.fragments.FragmentsAvailable;
-import org.linphone.fragments.HistoryDetailFragment;
-import org.linphone.fragments.HistoryListFragment;
-import org.linphone.chat.GroupInfoFragment;
-import org.linphone.contacts.LinphoneContact;
import org.linphone.LinphoneManager;
import org.linphone.LinphoneManager.AddressType;
import org.linphone.LinphonePreferences;
import org.linphone.LinphoneService;
import org.linphone.LinphoneUtils;
import org.linphone.R;
-import org.linphone.fragments.SettingsFragment;
-import org.linphone.fragments.StatusFragment;
import org.linphone.assistant.AssistantActivity;
import org.linphone.assistant.RemoteProvisioningLoginActivity;
+import org.linphone.call.CallActivity;
+import org.linphone.call.CallIncomingActivity;
+import org.linphone.call.CallOutgoingActivity;
import org.linphone.chat.ChatCreationFragment;
import org.linphone.chat.ChatListFragment;
import org.linphone.chat.GroupChatFragment;
+import org.linphone.chat.GroupInfoFragment;
+import org.linphone.chat.ImdnFragment;
import org.linphone.compatibility.Compatibility;
+import org.linphone.contacts.ContactAddress;
+import org.linphone.contacts.ContactDetailsFragment;
+import org.linphone.contacts.ContactEditorFragment;
+import org.linphone.contacts.ContactPicked;
+import org.linphone.contacts.ContactsListFragment;
+import org.linphone.contacts.ContactsManager;
+import org.linphone.contacts.LinphoneContact;
import org.linphone.core.Address;
import org.linphone.core.AuthInfo;
import org.linphone.core.Call;
@@ -103,11 +92,20 @@ import org.linphone.core.CallLog;
import org.linphone.core.ChatMessage;
import org.linphone.core.ChatRoom;
import org.linphone.core.Core;
-import org.linphone.core.RegistrationState;
-import org.linphone.core.Factory;
import org.linphone.core.CoreListenerStub;
+import org.linphone.core.Factory;
import org.linphone.core.ProxyConfig;
import org.linphone.core.Reason;
+import org.linphone.core.RegistrationState;
+import org.linphone.fragments.AboutFragment;
+import org.linphone.fragments.AccountPreferencesFragment;
+import org.linphone.fragments.DialerFragment;
+import org.linphone.fragments.EmptyFragment;
+import org.linphone.fragments.FragmentsAvailable;
+import org.linphone.fragments.HistoryDetailFragment;
+import org.linphone.fragments.HistoryListFragment;
+import org.linphone.fragments.SettingsFragment;
+import org.linphone.fragments.StatusFragment;
import org.linphone.mediastream.Log;
import org.linphone.purchase.InAppPurchaseActivity;
import org.linphone.ui.AddressText;
@@ -123,346 +121,346 @@ import java.util.Date;
import java.util.List;
public class LinphoneActivity extends LinphoneGenericActivity implements OnClickListener, ContactPicked, ActivityCompat.OnRequestPermissionsResultCallback {
- private static final int SETTINGS_ACTIVITY = 123;
- private static final int CALL_ACTIVITY = 19;
- private static final int PERMISSIONS_REQUEST_OVERLAY = 206;
- private static final int PERMISSIONS_REQUEST_SYNC = 207;
- private static final int PERMISSIONS_REQUEST_CONTACTS = 208;
- private static final int PERMISSIONS_RECORD_AUDIO_ECHO_CANCELLER = 209;
- private static final int PERMISSIONS_READ_EXTERNAL_STORAGE_DEVICE_RINGTONE = 210;
- private static final int PERMISSIONS_RECORD_AUDIO_ECHO_TESTER = 211;
+ private static final int SETTINGS_ACTIVITY = 123;
+ private static final int CALL_ACTIVITY = 19;
+ private static final int PERMISSIONS_REQUEST_OVERLAY = 206;
+ private static final int PERMISSIONS_REQUEST_SYNC = 207;
+ private static final int PERMISSIONS_REQUEST_CONTACTS = 208;
+ private static final int PERMISSIONS_RECORD_AUDIO_ECHO_CANCELLER = 209;
+ private static final int PERMISSIONS_READ_EXTERNAL_STORAGE_DEVICE_RINGTONE = 210;
+ private static final int PERMISSIONS_RECORD_AUDIO_ECHO_TESTER = 211;
- private static LinphoneActivity instance;
+ private static LinphoneActivity instance;
- private StatusFragment statusFragment;
- private TextView missedCalls, missedChats;
- private RelativeLayout contacts, history, dialer, chat;
- private View contacts_selected, history_selected, dialer_selected, chat_selected;
- private RelativeLayout mTopBar;
- private ImageView cancel;
- private FragmentsAvailable pendingFragmentTransaction, currentFragment, leftFragment;
- private Fragment fragment;
- private List fragmentsHistory;
- private Fragment.SavedState dialerSavedState;
- private boolean newProxyConfig;
- private boolean emptyFragment = false;
- private boolean isTrialAccount = false;
- private OrientationEventListener mOrientationHelper;
- private CoreListenerStub mListener;
- private LinearLayout mTabBar;
+ private StatusFragment statusFragment;
+ private TextView missedCalls, missedChats;
+ private RelativeLayout contacts, history, dialer, chat;
+ private View contacts_selected, history_selected, dialer_selected, chat_selected;
+ private RelativeLayout mTopBar;
+ private ImageView cancel;
+ private FragmentsAvailable pendingFragmentTransaction, currentFragment, leftFragment;
+ private Fragment fragment;
+ private List fragmentsHistory;
+ private Fragment.SavedState dialerSavedState;
+ private boolean newProxyConfig;
+ private boolean emptyFragment = false;
+ private boolean isTrialAccount = false;
+ private OrientationEventListener mOrientationHelper;
+ private CoreListenerStub mListener;
+ private LinearLayout mTabBar;
- private DrawerLayout sideMenu;
- private RelativeLayout sideMenuContent, quitLayout, defaultAccount;
- private ListView accountsList, sideMenuItemList;
- private ImageView menu;
- private boolean doNotGoToCallActivity = false;
- private List sideMenuItems;
- private boolean callTransfer = false;
- private boolean isOnBackground = false;
+ private DrawerLayout sideMenu;
+ private RelativeLayout sideMenuContent, quitLayout, defaultAccount;
+ private ListView accountsList, sideMenuItemList;
+ private ImageView menu;
+ private boolean doNotGoToCallActivity = false;
+ private List sideMenuItems;
+ private boolean callTransfer = false;
+ private boolean isOnBackground = false;
- public String mAddressWaitingToBeCalled;
+ public String mAddressWaitingToBeCalled;
- static public final boolean isInstanciated() {
- return instance != null;
- }
+ static public final boolean isInstanciated() {
+ return instance != null;
+ }
- public static final LinphoneActivity instance() {
- if (instance != null)
- return instance;
- throw new RuntimeException("LinphoneActivity not instantiated yet");
- }
+ public static final LinphoneActivity instance() {
+ if (instance != null)
+ return instance;
+ throw new RuntimeException("LinphoneActivity not instantiated yet");
+ }
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- //This must be done before calling super.onCreate().
- super.onCreate(savedInstanceState);
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ //This must be done before calling super.onCreate().
+ super.onCreate(savedInstanceState);
if (getResources().getBoolean(R.bool.orientation_portrait_only)) {
- setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
+ setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
+ }
+ boolean useFirstLoginActivity = getResources().getBoolean(R.bool.display_account_assistant_at_first_start);
+ if (LinphonePreferences.instance().isProvisioningLoginViewEnabled()) {
+ Intent wizard = new Intent();
+ wizard.setClass(this, RemoteProvisioningLoginActivity.class);
+ wizard.putExtra("Domain", LinphoneManager.getInstance().wizardLoginViewDomain);
+ startActivity(wizard);
+ finish();
+ return;
+ } else if (savedInstanceState == null && (useFirstLoginActivity && LinphoneManager.getLcIfManagerNotDestroyedOrNull() != null
+ && LinphonePreferences.instance().isFirstLaunch())) {
+ if (LinphonePreferences.instance().getAccountCount() > 0) {
+ LinphonePreferences.instance().firstLaunchSuccessful();
+ } else {
+ startActivity(new Intent().setClass(this, AssistantActivity.class));
+ finish();
+ return;
+ }
}
- boolean useFirstLoginActivity = getResources().getBoolean(R.bool.display_account_assistant_at_first_start);
- if (LinphonePreferences.instance().isProvisioningLoginViewEnabled()) {
- Intent wizard = new Intent();
- wizard.setClass(this, RemoteProvisioningLoginActivity.class);
- wizard.putExtra("Domain", LinphoneManager.getInstance().wizardLoginViewDomain);
- startActivity(wizard);
- finish();
- return;
- } else if (savedInstanceState == null && (useFirstLoginActivity && LinphoneManager.getLcIfManagerNotDestroyedOrNull() != null
- && LinphonePreferences.instance().isFirstLaunch())) {
- if (LinphonePreferences.instance().getAccountCount() > 0) {
- LinphonePreferences.instance().firstLaunchSuccessful();
- } else {
- startActivity(new Intent().setClass(this, AssistantActivity.class));
- finish();
- return;
- }
- }
- if (getResources().getBoolean(R.bool.use_linphone_tag)) {
- if (getPackageManager().checkPermission(Manifest.permission.WRITE_SYNC_SETTINGS, getPackageName()) != PackageManager.PERMISSION_GRANTED) {
- checkSyncPermission();
- } else {
- if (LinphoneService.isReady())
- ContactsManager.getInstance().initializeSyncAccount(getApplicationContext(), getContentResolver());
- }
- } else {
- if (LinphoneService.isReady())
- ContactsManager.getInstance().initializeContactManager(getApplicationContext(), getContentResolver());
- }
+ if (getResources().getBoolean(R.bool.use_linphone_tag)) {
+ if (getPackageManager().checkPermission(Manifest.permission.WRITE_SYNC_SETTINGS, getPackageName()) != PackageManager.PERMISSION_GRANTED) {
+ checkSyncPermission();
+ } else {
+ if (LinphoneService.isReady())
+ ContactsManager.getInstance().initializeSyncAccount(getApplicationContext(), getContentResolver());
+ }
+ } else {
+ if (LinphoneService.isReady())
+ ContactsManager.getInstance().initializeContactManager(getApplicationContext(), getContentResolver());
+ }
- setContentView(R.layout.main);
- instance = this;
- fragmentsHistory = new ArrayList();
- pendingFragmentTransaction = FragmentsAvailable.UNKNOW;
+ setContentView(R.layout.main);
+ instance = this;
+ fragmentsHistory = new ArrayList();
+ pendingFragmentTransaction = FragmentsAvailable.UNKNOW;
- initButtons();
- initSideMenu();
+ initButtons();
+ initSideMenu();
- currentFragment = FragmentsAvailable.EMPTY;
- if (savedInstanceState == null) {
- changeCurrentFragment(FragmentsAvailable.DIALER, getIntent().getExtras());
- } else {
- currentFragment = (FragmentsAvailable) savedInstanceState.getSerializable("currentFragment");
- }
+ currentFragment = FragmentsAvailable.EMPTY;
+ if (savedInstanceState == null) {
+ changeCurrentFragment(FragmentsAvailable.DIALER, getIntent().getExtras());
+ } else {
+ currentFragment = (FragmentsAvailable) savedInstanceState.getSerializable("currentFragment");
+ }
- mListener = new CoreListenerStub(){
- @Override
- public void onMessageReceived(Core lc, ChatRoom cr, ChatMessage message) {
- displayMissedChats(LinphoneManager.getInstance().getUnreadMessageCount());
- }
+ mListener = new CoreListenerStub() {
+ @Override
+ public void onMessageReceived(Core lc, ChatRoom cr, ChatMessage message) {
+ displayMissedChats(LinphoneManager.getInstance().getUnreadMessageCount());
+ }
- @Override
- public void onRegistrationStateChanged(Core lc, ProxyConfig proxy, RegistrationState state, String smessage) {
- AuthInfo authInfo = lc.findAuthInfo(proxy.getRealm(), proxy.getIdentityAddress().getUsername(), proxy.getDomain());
+ @Override
+ public void onRegistrationStateChanged(Core lc, ProxyConfig proxy, RegistrationState state, String smessage) {
+ AuthInfo authInfo = lc.findAuthInfo(proxy.getRealm(), proxy.getIdentityAddress().getUsername(), proxy.getDomain());
- refreshAccounts();
+ refreshAccounts();
- if(getResources().getBoolean(R.bool.use_phone_number_validation)
- && authInfo != null && authInfo.getDomain().equals(getString(R.string.default_domain))) {
- if (state.equals(RegistrationState.Ok)) {
- LinphoneManager.getInstance().isAccountWithAlias();
- }
- }
+ if (getResources().getBoolean(R.bool.use_phone_number_validation)
+ && authInfo != null && authInfo.getDomain().equals(getString(R.string.default_domain))) {
+ if (state.equals(RegistrationState.Ok)) {
+ LinphoneManager.getInstance().isAccountWithAlias();
+ }
+ }
- if(state.equals(RegistrationState.Failed) && newProxyConfig) {
- newProxyConfig = false;
- if (proxy.getError() == Reason.Forbidden) {
- //displayCustomToast(getString(R.string.error_bad_credentials), Toast.LENGTH_LONG);
- }
- if (proxy.getError() == Reason.Unauthorized) {
- displayCustomToast(getString(R.string.error_unauthorized), Toast.LENGTH_LONG);
- }
- if (proxy.getError() == Reason.IOError) {
- displayCustomToast(getString(R.string.error_io_error), Toast.LENGTH_LONG);
- }
- }
- }
+ if (state.equals(RegistrationState.Failed) && newProxyConfig) {
+ newProxyConfig = false;
+ if (proxy.getError() == Reason.Forbidden) {
+ //displayCustomToast(getString(R.string.error_bad_credentials), Toast.LENGTH_LONG);
+ }
+ if (proxy.getError() == Reason.Unauthorized) {
+ displayCustomToast(getString(R.string.error_unauthorized), Toast.LENGTH_LONG);
+ }
+ if (proxy.getError() == Reason.IOError) {
+ displayCustomToast(getString(R.string.error_io_error), Toast.LENGTH_LONG);
+ }
+ }
+ }
- @Override
- public void onCallStateChanged(Core lc, Call call, Call.State state, String message) {
- if (state == State.IncomingReceived) {
- startActivity(new Intent(LinphoneActivity.instance(), CallIncomingActivity.class));
- } else if (state == State.OutgoingInit || state == State.OutgoingProgress) {
- startActivity(new Intent(LinphoneActivity.instance(), CallOutgoingActivity.class));
- } else if (state == State.End || state == State.Error || state == State.Released) {
- resetClassicMenuLayoutAndGoBackToCallIfStillRunning();
- }
+ @Override
+ public void onCallStateChanged(Core lc, Call call, Call.State state, String message) {
+ if (state == State.IncomingReceived) {
+ startActivity(new Intent(LinphoneActivity.instance(), CallIncomingActivity.class));
+ } else if (state == State.OutgoingInit || state == State.OutgoingProgress) {
+ startActivity(new Intent(LinphoneActivity.instance(), CallOutgoingActivity.class));
+ } else if (state == State.End || state == State.Error || state == State.Released) {
+ resetClassicMenuLayoutAndGoBackToCallIfStillRunning();
+ }
- int missedCalls = LinphoneManager.getLc().getMissedCallsCount();
- displayMissedCalls(missedCalls);
- }
- };
+ int missedCalls = LinphoneManager.getLc().getMissedCallsCount();
+ displayMissedCalls(missedCalls);
+ }
+ };
- Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- if (lc != null) {
- int missedCalls = lc.getMissedCallsCount();
- displayMissedCalls(missedCalls);
- }
+ Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ if (lc != null) {
+ int missedCalls = lc.getMissedCallsCount();
+ displayMissedCalls(missedCalls);
+ }
- int rotation = getWindowManager().getDefaultDisplay().getRotation();
- switch (rotation) {
- case Surface.ROTATION_0:
- rotation = 0;
- break;
- case Surface.ROTATION_90:
- rotation = 90;
- break;
- case Surface.ROTATION_180:
- rotation = 180;
- break;
- case Surface.ROTATION_270:
- rotation = 270;
- break;
- }
+ int rotation = getWindowManager().getDefaultDisplay().getRotation();
+ switch (rotation) {
+ case Surface.ROTATION_0:
+ rotation = 0;
+ break;
+ case Surface.ROTATION_90:
+ rotation = 90;
+ break;
+ case Surface.ROTATION_180:
+ rotation = 180;
+ break;
+ case Surface.ROTATION_270:
+ rotation = 270;
+ break;
+ }
- if (LinphoneManager.isInstanciated()) {
- LinphoneManager.getLc().setDeviceRotation(rotation);
- }
- mAlwaysChangingPhoneAngle = rotation;
+ if (LinphoneManager.isInstanciated()) {
+ LinphoneManager.getLc().setDeviceRotation(rotation);
+ }
+ mAlwaysChangingPhoneAngle = rotation;
- Bundle extras = getIntent().getExtras();
- if (extras != null && extras.getBoolean("GoToChat", false)) {
- onNewIntent(getIntent());
- }
- }
+ Bundle extras = getIntent().getExtras();
+ if (extras != null && extras.getBoolean("GoToChat", false)) {
+ onNewIntent(getIntent());
+ }
+ }
- private void initButtons() {
- mTabBar = findViewById(R.id.footer);
- mTopBar = findViewById(R.id.top_bar);
+ private void initButtons() {
+ mTabBar = findViewById(R.id.footer);
+ mTopBar = findViewById(R.id.top_bar);
- cancel = findViewById(R.id.cancel);
- cancel.setOnClickListener(this);
+ cancel = findViewById(R.id.cancel);
+ cancel.setOnClickListener(this);
- history = findViewById(R.id.history);
- history.setOnClickListener(this);
- contacts = findViewById(R.id.contacts);
- contacts.setOnClickListener(this);
- dialer = findViewById(R.id.dialer);
- dialer.setOnClickListener(this);
- chat = findViewById(R.id.chat);
- chat.setOnClickListener(this);
+ history = findViewById(R.id.history);
+ history.setOnClickListener(this);
+ contacts = findViewById(R.id.contacts);
+ contacts.setOnClickListener(this);
+ dialer = findViewById(R.id.dialer);
+ dialer.setOnClickListener(this);
+ chat = findViewById(R.id.chat);
+ chat.setOnClickListener(this);
- history_selected = findViewById(R.id.history_select);
- contacts_selected = findViewById(R.id.contacts_select);
- dialer_selected = findViewById(R.id.dialer_select);
- chat_selected = findViewById(R.id.chat_select);
+ history_selected = findViewById(R.id.history_select);
+ contacts_selected = findViewById(R.id.contacts_select);
+ dialer_selected = findViewById(R.id.dialer_select);
+ chat_selected = findViewById(R.id.chat_select);
- missedCalls = findViewById(R.id.missed_calls);
- missedChats = findViewById(R.id.missed_chats);
- }
+ missedCalls = findViewById(R.id.missed_calls);
+ missedChats = findViewById(R.id.missed_chats);
+ }
- public boolean isTablet() {
- return getResources().getBoolean(R.bool.isTablet);
- }
+ public boolean isTablet() {
+ return getResources().getBoolean(R.bool.isTablet);
+ }
- public void hideStatusBar() {
- if (isTablet()) {
- return;
- }
+ public void hideStatusBar() {
+ if (isTablet()) {
+ return;
+ }
- findViewById(R.id.status).setVisibility(View.GONE);
- }
+ findViewById(R.id.status).setVisibility(View.GONE);
+ }
- public void showStatusBar() {
- if (isTablet()) {
- return;
- }
+ public void showStatusBar() {
+ if (isTablet()) {
+ return;
+ }
- if (statusFragment != null && !statusFragment.isVisible()) {
- statusFragment.getView().setVisibility(View.VISIBLE);
- }
- findViewById(R.id.status).setVisibility(View.VISIBLE);
- }
+ if (statusFragment != null && !statusFragment.isVisible()) {
+ statusFragment.getView().setVisibility(View.VISIBLE);
+ }
+ findViewById(R.id.status).setVisibility(View.VISIBLE);
+ }
- public void isNewProxyConfig(){
- newProxyConfig = true;
- }
+ public void isNewProxyConfig() {
+ newProxyConfig = true;
+ }
- public void popBackStack() {
- getFragmentManager().popBackStackImmediate();
- currentFragment = FragmentsAvailable.EMPTY;
- }
+ public void popBackStack() {
+ getFragmentManager().popBackStackImmediate();
+ currentFragment = FragmentsAvailable.EMPTY;
+ }
- private void changeCurrentFragment(FragmentsAvailable newFragmentType, Bundle extras) {
- changeCurrentFragment(newFragmentType, extras, false);
- }
+ private void changeCurrentFragment(FragmentsAvailable newFragmentType, Bundle extras) {
+ changeCurrentFragment(newFragmentType, extras, false);
+ }
- private void changeCurrentFragment(FragmentsAvailable newFragmentType, Bundle extras, boolean withoutAnimation) {
- if (newFragmentType == currentFragment && newFragmentType != FragmentsAvailable.CHAT
- && newFragmentType != FragmentsAvailable.GROUP_CHAT) {
- return;
- }
+ private void changeCurrentFragment(FragmentsAvailable newFragmentType, Bundle extras, boolean withoutAnimation) {
+ if (newFragmentType == currentFragment && newFragmentType != FragmentsAvailable.CHAT
+ && newFragmentType != FragmentsAvailable.GROUP_CHAT) {
+ return;
+ }
- if (currentFragment == FragmentsAvailable.DIALER) {
- try {
- DialerFragment dialerFragment = DialerFragment.instance();
- dialerSavedState = getFragmentManager().saveFragmentInstanceState(dialerFragment);
- } catch (Exception e) {
- }
- }
+ if (currentFragment == FragmentsAvailable.DIALER) {
+ try {
+ DialerFragment dialerFragment = DialerFragment.instance();
+ dialerSavedState = getFragmentManager().saveFragmentInstanceState(dialerFragment);
+ } catch (Exception e) {
+ }
+ }
- fragment = null;
+ fragment = null;
- switch (newFragmentType) {
- case HISTORY_LIST:
- fragment = new HistoryListFragment();
- break;
- case HISTORY_DETAIL:
- fragment = new HistoryDetailFragment();
- break;
- case CONTACTS_LIST:
- checkAndRequestWriteContactsPermission();
- fragment = new ContactsListFragment();
- break;
- case CONTACT_DETAIL:
- fragment = new ContactDetailsFragment();
- break;
- case CONTACT_EDITOR:
- fragment = new ContactEditorFragment();
- break;
- case DIALER:
- fragment = new DialerFragment();
- if (extras == null) {
- fragment.setInitialSavedState(dialerSavedState);
- }
- break;
- case SETTINGS:
- fragment = new SettingsFragment();
- break;
- case ACCOUNT_SETTINGS:
- fragment = new AccountPreferencesFragment();
- break;
- case ABOUT:
- fragment = new AboutFragment();
- break;
- case EMPTY:
- fragment = new EmptyFragment();
- break;
- case CHAT_LIST:
- fragment = new ChatListFragment();
- break;
- case CREATE_CHAT:
- checkAndRequestWriteContactsPermission();
- fragment = new ChatCreationFragment();
- break;
- case INFO_GROUP_CHAT:
- fragment = new GroupInfoFragment();
- break;
- case GROUP_CHAT:
- fragment = new GroupChatFragment();
- break;
- case MESSAGE_IMDN:
- fragment = new ImdnFragment();
- break;
- default:
- break;
- }
+ switch (newFragmentType) {
+ case HISTORY_LIST:
+ fragment = new HistoryListFragment();
+ break;
+ case HISTORY_DETAIL:
+ fragment = new HistoryDetailFragment();
+ break;
+ case CONTACTS_LIST:
+ checkAndRequestWriteContactsPermission();
+ fragment = new ContactsListFragment();
+ break;
+ case CONTACT_DETAIL:
+ fragment = new ContactDetailsFragment();
+ break;
+ case CONTACT_EDITOR:
+ fragment = new ContactEditorFragment();
+ break;
+ case DIALER:
+ fragment = new DialerFragment();
+ if (extras == null) {
+ fragment.setInitialSavedState(dialerSavedState);
+ }
+ break;
+ case SETTINGS:
+ fragment = new SettingsFragment();
+ break;
+ case ACCOUNT_SETTINGS:
+ fragment = new AccountPreferencesFragment();
+ break;
+ case ABOUT:
+ fragment = new AboutFragment();
+ break;
+ case EMPTY:
+ fragment = new EmptyFragment();
+ break;
+ case CHAT_LIST:
+ fragment = new ChatListFragment();
+ break;
+ case CREATE_CHAT:
+ checkAndRequestWriteContactsPermission();
+ fragment = new ChatCreationFragment();
+ break;
+ case INFO_GROUP_CHAT:
+ fragment = new GroupInfoFragment();
+ break;
+ case GROUP_CHAT:
+ fragment = new GroupChatFragment();
+ break;
+ case MESSAGE_IMDN:
+ fragment = new ImdnFragment();
+ break;
+ default:
+ break;
+ }
- if (fragment != null) {
- fragment.setArguments(extras);
- if (isTablet()) {
- changeFragmentForTablets(fragment, newFragmentType, withoutAnimation);
- switch (newFragmentType) {
- case HISTORY_LIST:
- ((HistoryListFragment) fragment).displayFirstLog();
- break;
- case CONTACTS_LIST:
- ((ContactsListFragment) fragment).displayFirstContact();
- break;
- case CHAT_LIST:
- ((ChatListFragment) fragment).displayFirstChat();
- break;
- }
- } else {
- changeFragment(fragment, newFragmentType, withoutAnimation);
- }
- }
- }
+ if (fragment != null) {
+ fragment.setArguments(extras);
+ if (isTablet()) {
+ changeFragmentForTablets(fragment, newFragmentType, withoutAnimation);
+ switch (newFragmentType) {
+ case HISTORY_LIST:
+ ((HistoryListFragment) fragment).displayFirstLog();
+ break;
+ case CONTACTS_LIST:
+ ((ContactsListFragment) fragment).displayFirstContact();
+ break;
+ case CHAT_LIST:
+ ((ChatListFragment) fragment).displayFirstChat();
+ break;
+ }
+ } else {
+ changeFragment(fragment, newFragmentType, withoutAnimation);
+ }
+ }
+ }
- private void changeFragment(Fragment newFragment, FragmentsAvailable newFragmentType, boolean withoutAnimation) {
- FragmentManager fm = getFragmentManager();
- FragmentTransaction transaction = fm.beginTransaction();
+ private void changeFragment(Fragment newFragment, FragmentsAvailable newFragmentType, boolean withoutAnimation) {
+ FragmentManager fm = getFragmentManager();
+ FragmentTransaction transaction = fm.beginTransaction();
/*if (!withoutAnimation && !isAnimationDisabled && currentFragment.shouldAnimate()) {
if (newFragmentType.isRightOf(currentFragment)) {
@@ -478,76 +476,76 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick
}
}*/
- if (newFragmentType != FragmentsAvailable.DIALER
- && newFragmentType != FragmentsAvailable.CONTACTS_LIST
- && newFragmentType != FragmentsAvailable.CHAT_LIST
- && newFragmentType != FragmentsAvailable.HISTORY_LIST) {
- transaction.addToBackStack(newFragmentType.toString());
- } else {
- while (fm.getBackStackEntryCount() > 0) {
- fm.popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
- }
- }
+ if (newFragmentType != FragmentsAvailable.DIALER
+ && newFragmentType != FragmentsAvailable.CONTACTS_LIST
+ && newFragmentType != FragmentsAvailable.CHAT_LIST
+ && newFragmentType != FragmentsAvailable.HISTORY_LIST) {
+ transaction.addToBackStack(newFragmentType.toString());
+ } else {
+ while (fm.getBackStackEntryCount() > 0) {
+ fm.popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
+ }
+ }
- Compatibility.setFragmentTransactionReorderingAllowed(transaction, false);
- transaction.replace(R.id.fragmentContainer, newFragment, newFragmentType.toString());
- transaction.commitAllowingStateLoss();
- fm.executePendingTransactions();
+ Compatibility.setFragmentTransactionReorderingAllowed(transaction, false);
+ transaction.replace(R.id.fragmentContainer, newFragment, newFragmentType.toString());
+ transaction.commitAllowingStateLoss();
+ fm.executePendingTransactions();
- currentFragment = newFragmentType;
- }
+ currentFragment = newFragmentType;
+ }
- private void changeFragmentForTablets(Fragment newFragment, FragmentsAvailable newFragmentType, boolean withoutAnimation) {
- if (getResources().getBoolean(R.bool.show_statusbar_only_on_dialer)) {
- if (newFragmentType == FragmentsAvailable.DIALER) {
- showStatusBar();
- } else {
- hideStatusBar();
- }
- }
- emptyFragment = false;
- LinearLayout ll = (LinearLayout) findViewById(R.id.fragmentContainer2);
+ private void changeFragmentForTablets(Fragment newFragment, FragmentsAvailable newFragmentType, boolean withoutAnimation) {
+ if (getResources().getBoolean(R.bool.show_statusbar_only_on_dialer)) {
+ if (newFragmentType == FragmentsAvailable.DIALER) {
+ showStatusBar();
+ } else {
+ hideStatusBar();
+ }
+ }
+ emptyFragment = false;
+ LinearLayout ll = (LinearLayout) findViewById(R.id.fragmentContainer2);
- FragmentTransaction transaction = getFragmentManager().beginTransaction();
+ FragmentTransaction transaction = getFragmentManager().beginTransaction();
- if(newFragmentType == FragmentsAvailable.EMPTY){
- ll.setVisibility(View.VISIBLE);
- emptyFragment = true;
- transaction.replace(R.id.fragmentContainer2, newFragment);
- transaction.commitAllowingStateLoss();
- getFragmentManager().executePendingTransactions();
- } else {
- if (newFragmentType.shouldAddItselfToTheRightOf(currentFragment) || newFragmentType.shouldAddItselfToTheRightOf(leftFragment)) {
- ll.setVisibility(View.VISIBLE);
+ if (newFragmentType == FragmentsAvailable.EMPTY) {
+ ll.setVisibility(View.VISIBLE);
+ emptyFragment = true;
+ transaction.replace(R.id.fragmentContainer2, newFragment);
+ transaction.commitAllowingStateLoss();
+ getFragmentManager().executePendingTransactions();
+ } else {
+ if (newFragmentType.shouldAddItselfToTheRightOf(currentFragment) || newFragmentType.shouldAddItselfToTheRightOf(leftFragment)) {
+ ll.setVisibility(View.VISIBLE);
- if (newFragmentType == FragmentsAvailable.CONTACT_EDITOR) {
- transaction.addToBackStack(newFragmentType.toString());
- }
- transaction.replace(R.id.fragmentContainer2, newFragment);
- leftFragment = currentFragment;
+ if (newFragmentType == FragmentsAvailable.CONTACT_EDITOR) {
+ transaction.addToBackStack(newFragmentType.toString());
+ }
+ transaction.replace(R.id.fragmentContainer2, newFragment);
+ leftFragment = currentFragment;
- if (newFragmentType == FragmentsAvailable.GROUP_CHAT && leftFragment != FragmentsAvailable.CHAT_LIST) {
- leftFragment = FragmentsAvailable.CHAT_LIST;
- transaction.replace(R.id.fragmentContainer, new ChatListFragment());
- }
- } else {
- if (newFragmentType == FragmentsAvailable.EMPTY) {
- ll.setVisibility(View.VISIBLE);
- transaction.replace(R.id.fragmentContainer2, new EmptyFragment());
- emptyFragment = true;
- }
+ if (newFragmentType == FragmentsAvailable.GROUP_CHAT && leftFragment != FragmentsAvailable.CHAT_LIST) {
+ leftFragment = FragmentsAvailable.CHAT_LIST;
+ transaction.replace(R.id.fragmentContainer, new ChatListFragment());
+ }
+ } else {
+ if (newFragmentType == FragmentsAvailable.EMPTY) {
+ ll.setVisibility(View.VISIBLE);
+ transaction.replace(R.id.fragmentContainer2, new EmptyFragment());
+ emptyFragment = true;
+ }
- if (newFragmentType == FragmentsAvailable.DIALER
- || newFragmentType == FragmentsAvailable.ABOUT
- || newFragmentType == FragmentsAvailable.SETTINGS
- || newFragmentType == FragmentsAvailable.ACCOUNT_SETTINGS
- || newFragmentType == FragmentsAvailable.CREATE_CHAT
- || newFragmentType == FragmentsAvailable.INFO_GROUP_CHAT) {
- ll.setVisibility(View.GONE);
- } else {
- ll.setVisibility(View.VISIBLE);
- transaction.replace(R.id.fragmentContainer2, new EmptyFragment());
- }
+ if (newFragmentType == FragmentsAvailable.DIALER
+ || newFragmentType == FragmentsAvailable.ABOUT
+ || newFragmentType == FragmentsAvailable.SETTINGS
+ || newFragmentType == FragmentsAvailable.ACCOUNT_SETTINGS
+ || newFragmentType == FragmentsAvailable.CREATE_CHAT
+ || newFragmentType == FragmentsAvailable.INFO_GROUP_CHAT) {
+ ll.setVisibility(View.GONE);
+ } else {
+ ll.setVisibility(View.VISIBLE);
+ transaction.replace(R.id.fragmentContainer2, new EmptyFragment());
+ }
/*if (!withoutAnimation && !isAnimationDisabled && currentFragment.shouldAnimate()) {
if (newFragmentType.isRightOf(currentFragment)) {
@@ -556,1308 +554,1304 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick
transaction.setCustomAnimations(R.anim.slide_in_left_to_right, R.anim.slide_out_left_to_right, R.anim.slide_in_right_to_left, R.anim.slide_out_right_to_left);
}
}*/
- transaction.replace(R.id.fragmentContainer, newFragment);
- }
- transaction.commitAllowingStateLoss();
- getFragmentManager().executePendingTransactions();
-
- currentFragment = newFragmentType;
- if (newFragmentType == FragmentsAvailable.DIALER
- || newFragmentType == FragmentsAvailable.SETTINGS
- || newFragmentType == FragmentsAvailable.CONTACTS_LIST
- || newFragmentType == FragmentsAvailable.CHAT_LIST
- || newFragmentType == FragmentsAvailable.HISTORY_LIST) {
- try {
- getFragmentManager().popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
- } catch (java.lang.IllegalStateException e) {
-
- }
- }
- fragmentsHistory.add(currentFragment);
- }
- }
-
- public void displayHistoryDetail(String sipUri, CallLog log) {
- Address lAddress = null;
- LinphoneContact c = null;
-
- lAddress = Factory.instance().createAddress(sipUri);
- if (lAddress != null) {
- c = ContactsManager.getInstance().findContactFromAddress(lAddress);
- }
-
- String displayName = c != null ? c.getFullName() : LinphoneUtils.getAddressDisplayName(sipUri);
- String pictureUri = c != null && c.getPhotoUri() != null ? c.getPhotoUri().toString() : null;
-
- String status;
- if (log.getDir() == Call.Dir.Outgoing) {
- status = getString(R.string.outgoing);
- } else {
- if (log.getStatus() == Call.Status.Missed) {
- status = getString(R.string.missed);
- } else {
- status = getString(R.string.incoming);
- }
- }
-
- String callTime = secondsToDisplayableString(log.getDuration());
- String callDate = String.valueOf(log.getStartDate());
-
- Fragment fragment2 = getFragmentManager().findFragmentById(R.id.fragmentContainer2);
- if (fragment2 != null && fragment2.isVisible() && currentFragment == FragmentsAvailable.HISTORY_DETAIL) {
- HistoryDetailFragment historyDetailFragment = (HistoryDetailFragment) fragment2;
- historyDetailFragment.changeDisplayedHistory(sipUri, displayName, pictureUri, status, callTime, callDate);
- } else {
- Bundle extras = new Bundle();
- extras.putString("SipUri", sipUri);
- if (displayName != null) {
- extras.putString("DisplayName", displayName);
- extras.putString("PictureUri", pictureUri);
- }
- extras.putString("Call.Status", status);
- extras.putString("CallTime", callTime);
- extras.putString("CallDate", callDate);
-
- changeCurrentFragment(FragmentsAvailable.HISTORY_DETAIL, extras);
- }
- }
-
- public void displayEmptyFragment(){
- changeCurrentFragment(FragmentsAvailable.EMPTY, new Bundle());
- }
-
- @SuppressLint("SimpleDateFormat")
- private String secondsToDisplayableString(int secs) {
- SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
- Calendar cal = Calendar.getInstance();
- cal.set(0, 0, 0, 0, 0, secs);
- return dateFormat.format(cal.getTime());
- }
-
- public void displayContact(LinphoneContact contact, boolean chatOnly) {
- Fragment fragment2 = getFragmentManager().findFragmentById(R.id.fragmentContainer2);
- if (fragment2 != null && fragment2.isVisible() && currentFragment == FragmentsAvailable.CONTACT_DETAIL) {
- ContactDetailsFragment contactFragment = (ContactDetailsFragment) fragment2;
- contactFragment.changeDisplayedContact(contact);
- } else {
- Bundle extras = new Bundle();
- extras.putSerializable("Contact", contact);
- extras.putBoolean("ChatAddressOnly", chatOnly);
- changeCurrentFragment(FragmentsAvailable.CONTACT_DETAIL, extras);
- }
- }
-
- public void displayContacts(boolean chatOnly) {
- Bundle extras = new Bundle();
- extras.putBoolean("ChatAddressOnly", chatOnly);
- changeCurrentFragment(FragmentsAvailable.CONTACTS_LIST, extras);
- }
-
- public void displayContactsForEdition(String sipAddress) {
- Bundle extras = new Bundle();
- extras.putBoolean("EditOnClick", true);
- extras.putString("SipAddress", sipAddress);
- changeCurrentFragment(FragmentsAvailable.CONTACTS_LIST, extras);
- }
-
- public void displayAbout() {
- changeCurrentFragment(FragmentsAvailable.ABOUT, null);
- }
-
- public void displayContactsForEdition(String sipAddress, String displayName) {
- Bundle extras = new Bundle();
- extras.putBoolean("EditOnClick", true);
- extras.putString("SipAddress", sipAddress);
- extras.putString("DisplayName", displayName);
- changeCurrentFragment(FragmentsAvailable.CONTACTS_LIST, extras);
- }
-
- public void displayAssistant() {
- startActivity(new Intent(LinphoneActivity.this, AssistantActivity.class));
- }
-
-
-
- public void displayInapp() {
- startActivity(new Intent(LinphoneActivity.this, InAppPurchaseActivity.class));
- }
-
- private void displayChat(String sipUri, String message, String fileUri, String pictureUri, String thumbnailUri, String displayName, Address lAddress) {
- Bundle extras = new Bundle();
- extras.putString("SipUri", sipUri);
-
- if (message != null)
- extras.putString("messageDraft", message);
- if (fileUri != null)
- extras.putString("fileSharedUri", fileUri);
- if (sipUri != null && lAddress.getDisplayName() != null) {
- extras.putString("DisplayName", displayName);
- extras.putString("PictureUri", pictureUri);
- extras.putString("ThumbnailUri", thumbnailUri);
- }
-
- if (sipUri == null) {
- changeCurrentFragment(FragmentsAvailable.CREATE_CHAT, extras);
- } else {
- changeCurrentFragment(FragmentsAvailable.GROUP_CHAT, extras);
- }
- }
-
- public void goToChatCreator(String address, ArrayList selectedContacts, String subject, boolean isGoBack, Bundle shareInfos) {
- if (currentFragment == FragmentsAvailable.INFO_GROUP_CHAT && isGoBack) {
- getFragmentManager().popBackStackImmediate();
- getFragmentManager().popBackStackImmediate();
- }
- Bundle extras = new Bundle();
- extras.putSerializable("selectedContacts", selectedContacts);
- extras.putString("subject", subject);
- extras.putString("groupChatRoomAddress", address);
-
- if (shareInfos != null) {
- if (shareInfos.getString("fileSharedUri") != null)
- extras.putString("fileSharedUri", shareInfos.getString("fileSharedUri"));
- if (shareInfos.getString("messageDraft") != null)
- extras.putString("messageDraft", shareInfos.getString("messageDraft"));
- }
-
- changeCurrentFragment(FragmentsAvailable.CREATE_CHAT, extras);
- }
-
- public void goToChat(String sipUri, Bundle shareInfos) {
- Bundle extras = new Bundle();
- extras.putString("SipUri", sipUri);
-
- if (shareInfos != null) {
- if (shareInfos.getString("fileSharedUri") != null)
- extras.putString("fileSharedUri", shareInfos.getString("fileSharedUri"));
- if (shareInfos.getString("messageDraft") != null)
- extras.putString("messageDraft", shareInfos.getString("messageDraft"));
- }
-
- if (isTablet()) {
- Fragment fragment2 = getFragmentManager().findFragmentById(R.id.fragmentContainer2);
- if (fragment2 != null && fragment2.isVisible() && currentFragment == FragmentsAvailable.GROUP_CHAT && !emptyFragment) {
- GroupChatFragment chatFragment = (GroupChatFragment) fragment2;
- chatFragment.changeDisplayedChat(sipUri);
- } else {
- changeCurrentFragment(FragmentsAvailable.GROUP_CHAT, extras);
- }
- } else {
- changeCurrentFragment(FragmentsAvailable.GROUP_CHAT, extras);
- }
-
- LinphoneManager.getInstance().updateUnreadCountForChatRoom(sipUri, 0);
- displayMissedChats(LinphoneManager.getInstance().getUnreadMessageCount());
- }
-
- public void goToChatGroupInfos(String address, ArrayList contacts, String subject, boolean isEditionEnabled, boolean isGoBack, Bundle shareInfos) {
- if (currentFragment == FragmentsAvailable.CREATE_CHAT && isGoBack) {
- getFragmentManager().popBackStackImmediate();
- getFragmentManager().popBackStackImmediate();
- }
- Bundle extras = new Bundle();
- extras.putString("groupChatRoomAddress", address);
- extras.putBoolean("isEditionEnabled", isEditionEnabled);
- extras.putSerializable("ContactAddress", contacts);
- extras.putString("subject", subject);
-
- if (shareInfos != null) {
- if (shareInfos.getString("fileSharedUri") != null)
- extras.putString("fileSharedUri", shareInfos.getString("fileSharedUri"));
- if (shareInfos.getString("messageDraft") != null)
- extras.putString("messageDraft", shareInfos.getString("messageDraft"));
- }
-
- changeCurrentFragment(FragmentsAvailable.INFO_GROUP_CHAT, extras);
- }
-
- public void goToChatMessageImdnInfos(String sipUri, String messageId) {
- Bundle extras = new Bundle();
- extras.putSerializable("SipUri", sipUri);
- extras.putString("MessageId", messageId);
- changeCurrentFragment(FragmentsAvailable.MESSAGE_IMDN, extras);
- }
-
- public void goToChatList() {
- changeCurrentFragment(FragmentsAvailable.CHAT_LIST, null);
- }
-
- public void displayChat(String sipUri, String message, String fileUri) {
- if (getResources().getBoolean(R.bool.disable_chat)) {
- return;
- }
-
- String pictureUri = null;
- String thumbnailUri = null;
- String displayName = null;
-
- Address lAddress = null;
- if (sipUri != null) {
- lAddress = LinphoneManager.getLc().interpretUrl(sipUri);
- if (lAddress == null) return;
- LinphoneContact contact = ContactsManager.getInstance().findContactFromAddress(lAddress);
- displayName = contact != null ? contact.getFullName() : null;
-
- if (contact != null && contact.getPhotoUri() != null) {
- pictureUri = contact.getPhotoUri().toString();
- thumbnailUri = contact.getThumbnailUri().toString();
- }
- }
-
- if (currentFragment == FragmentsAvailable.CHAT_LIST || currentFragment == FragmentsAvailable.GROUP_CHAT) {
- Fragment fragment2 = getFragmentManager().findFragmentById(R.id.fragmentContainer2);
- if (fragment2 != null && fragment2.isVisible() && currentFragment == FragmentsAvailable.GROUP_CHAT && !emptyFragment) {
- GroupChatFragment chatFragment = (GroupChatFragment) fragment2;
- chatFragment.changeDisplayedChat(sipUri);
- } else {
- displayChat(sipUri, message, fileUri, pictureUri, thumbnailUri, displayName, lAddress);
- }
- } else {
- if(isTablet()){
- changeCurrentFragment(FragmentsAvailable.CHAT_LIST, null);
- } else {
- displayChat(sipUri, message, fileUri, pictureUri, thumbnailUri, displayName, lAddress);
- }
- }
-
- LinphoneManager.getInstance().updateUnreadCountForChatRoom(sipUri, 0);
- displayMissedChats(LinphoneManager.getInstance().getUnreadMessageCount());
- }
-
- @Override
- public void onClick(View v) {
- int id = v.getId();
- resetSelection();
-
- if (id == R.id.history) {
- changeCurrentFragment(FragmentsAvailable.HISTORY_LIST, null);
- history_selected.setVisibility(View.VISIBLE);
- LinphoneManager.getLc().resetMissedCallsCount();
- displayMissedCalls(0);
- } else if (id == R.id.contacts) {
- changeCurrentFragment(FragmentsAvailable.CONTACTS_LIST, null);
- contacts_selected.setVisibility(View.VISIBLE);
- } else if (id == R.id.dialer) {
- changeCurrentFragment(FragmentsAvailable.DIALER, null);
- dialer_selected.setVisibility(View.VISIBLE);
- } else if (id == R.id.chat) {
- changeCurrentFragment(FragmentsAvailable.CHAT_LIST, null);
- chat_selected.setVisibility(View.VISIBLE);
- } else if (id == R.id.cancel){
- hideTopBar();
- displayDialer();
- }
- }
-
- private void resetSelection() {
- history_selected.setVisibility(View.GONE);
- contacts_selected.setVisibility(View.GONE);
- dialer_selected.setVisibility(View.GONE);
- chat_selected.setVisibility(View.GONE);
- }
-
- public void hideTabBar(Boolean hide) {
- if(hide){
- mTabBar.setVisibility(View.GONE);
- } else {
- mTabBar.setVisibility(View.VISIBLE);
- }
- }
-
- public void hideTopBar() {
- mTopBar.setVisibility(View.GONE);
- }
-
- @SuppressWarnings("incomplete-switch")
- public void selectMenu(FragmentsAvailable menuToSelect) {
- currentFragment = menuToSelect;
- resetSelection();
-
- switch (menuToSelect) {
- case HISTORY_LIST:
- case HISTORY_DETAIL:
- history_selected.setVisibility(View.VISIBLE);
- break;
- case CONTACTS_LIST:
- case CONTACT_DETAIL:
- case CONTACT_EDITOR:
- contacts_selected.setVisibility(View.VISIBLE);
- break;
- case DIALER:
- dialer_selected.setVisibility(View.VISIBLE);
- break;
- case SETTINGS:
- case ACCOUNT_SETTINGS:
- hideTabBar(true);
- mTopBar.setVisibility(View.VISIBLE);
- break;
- case ABOUT:
- hideTabBar(true);
- break;
- case CHAT_LIST:
- case CREATE_CHAT:
- case GROUP_CHAT:
- case INFO_GROUP_CHAT:
- case MESSAGE_IMDN:
- case CHAT:
- chat_selected.setVisibility(View.VISIBLE);
- break;
- }
- }
-
- public void updateDialerFragment(DialerFragment fragment) {
- // Hack to maintain soft input flags
- getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
- }
-
- public void goToDialerFragment() {
- changeCurrentFragment(FragmentsAvailable.DIALER, null);
- dialer_selected.setVisibility(View.VISIBLE);
- }
-
- public void updateStatusFragment(StatusFragment fragment) {
- statusFragment = fragment;
- }
-
- public void displaySettings() {
- changeCurrentFragment(FragmentsAvailable.SETTINGS, null);
- }
-
- public void displayDialer() {
- changeCurrentFragment(FragmentsAvailable.DIALER, null);
- }
-
- public void displayAccountSettings(int accountNumber) {
- Bundle bundle = new Bundle();
- bundle.putInt("Account", accountNumber);
- changeCurrentFragment(FragmentsAvailable.ACCOUNT_SETTINGS, bundle);
- //settings.setSelected(true);
- }
-
- public StatusFragment getStatusFragment() {
- return statusFragment;
- }
-
- public void refreshMissedChatCountDisplay() {
- displayMissedChats(LinphoneManager.getInstance().getUnreadMessageCount());
- }
-
- public void displayMissedCalls(final int missedCallsCount) {
- if (missedCallsCount > 0) {
- missedCalls.setText(missedCallsCount + "");
- missedCalls.setVisibility(View.VISIBLE);
- } else {
- if (LinphoneManager.isInstanciated()) LinphoneManager.getLc().resetMissedCallsCount();
- missedCalls.clearAnimation();
- missedCalls.setVisibility(View.GONE);
- }
- }
-
- private void displayMissedChats(final int missedChatCount) {
- if (missedChatCount > 0) {
- missedChats.setText(missedChatCount + "");
- missedChats.setVisibility(View.VISIBLE);
- } else {
- missedChats.clearAnimation();
- missedChats.setVisibility(View.GONE);
- }
- }
-
- public void displayCustomToast(final String message, final int duration) {
- LayoutInflater inflater = getLayoutInflater();
- View layout = inflater.inflate(R.layout.toast, (ViewGroup) findViewById(R.id.toastRoot));
-
- TextView toastText = (TextView) layout.findViewById(R.id.toastMessage);
- toastText.setText(message);
-
- final Toast toast = new Toast(getApplicationContext());
- toast.setGravity(Gravity.CENTER, 0, 0);
- toast.setDuration(duration);
- toast.setView(layout);
- toast.show();
- }
-
- public void displayChatRoomError() {
- final Dialog dialog = LinphoneActivity.instance().displayDialog(getString(R.string.chat_room_creation_failed));
- Button delete = dialog.findViewById(R.id.delete_button);
- Button cancel = dialog.findViewById(R.id.cancel);
- delete.setVisibility(View.GONE);
- cancel.setText(getString(R.string.ok));
- cancel.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- dialog.dismiss();
- }
- });
-
- dialog.show();
- }
-
- public Dialog displayDialog(String text){
- Dialog dialog = new Dialog(this);
- dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
- Drawable d = new ColorDrawable(ContextCompat.getColor(this, R.color.colorC));
- d.setAlpha(200);
- dialog.setContentView(R.layout.dialog);
- dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
- dialog.getWindow().setBackgroundDrawable(d);
-
- TextView customText = (TextView) dialog.findViewById(R.id.customText);
- customText.setText(text);
- return dialog;
- }
-
- @Override
- public void setAddresGoToDialerAndCall(String number, String name, Uri photo) {
+ transaction.replace(R.id.fragmentContainer, newFragment);
+ }
+ transaction.commitAllowingStateLoss();
+ getFragmentManager().executePendingTransactions();
+
+ currentFragment = newFragmentType;
+ if (newFragmentType == FragmentsAvailable.DIALER
+ || newFragmentType == FragmentsAvailable.SETTINGS
+ || newFragmentType == FragmentsAvailable.CONTACTS_LIST
+ || newFragmentType == FragmentsAvailable.CHAT_LIST
+ || newFragmentType == FragmentsAvailable.HISTORY_LIST) {
+ try {
+ getFragmentManager().popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
+ } catch (java.lang.IllegalStateException e) {
+
+ }
+ }
+ fragmentsHistory.add(currentFragment);
+ }
+ }
+
+ public void displayHistoryDetail(String sipUri, CallLog log) {
+ Address lAddress = null;
+ LinphoneContact c = null;
+
+ lAddress = Factory.instance().createAddress(sipUri);
+ if (lAddress != null) {
+ c = ContactsManager.getInstance().findContactFromAddress(lAddress);
+ }
+
+ String displayName = c != null ? c.getFullName() : LinphoneUtils.getAddressDisplayName(sipUri);
+ String pictureUri = c != null && c.getPhotoUri() != null ? c.getPhotoUri().toString() : null;
+
+ String status;
+ if (log.getDir() == Call.Dir.Outgoing) {
+ status = getString(R.string.outgoing);
+ } else {
+ if (log.getStatus() == Call.Status.Missed) {
+ status = getString(R.string.missed);
+ } else {
+ status = getString(R.string.incoming);
+ }
+ }
+
+ String callTime = secondsToDisplayableString(log.getDuration());
+ String callDate = String.valueOf(log.getStartDate());
+
+ Fragment fragment2 = getFragmentManager().findFragmentById(R.id.fragmentContainer2);
+ if (fragment2 != null && fragment2.isVisible() && currentFragment == FragmentsAvailable.HISTORY_DETAIL) {
+ HistoryDetailFragment historyDetailFragment = (HistoryDetailFragment) fragment2;
+ historyDetailFragment.changeDisplayedHistory(sipUri, displayName, pictureUri, status, callTime, callDate);
+ } else {
+ Bundle extras = new Bundle();
+ extras.putString("SipUri", sipUri);
+ if (displayName != null) {
+ extras.putString("DisplayName", displayName);
+ extras.putString("PictureUri", pictureUri);
+ }
+ extras.putString("Call.Status", status);
+ extras.putString("CallTime", callTime);
+ extras.putString("CallDate", callDate);
+
+ changeCurrentFragment(FragmentsAvailable.HISTORY_DETAIL, extras);
+ }
+ }
+
+ public void displayEmptyFragment() {
+ changeCurrentFragment(FragmentsAvailable.EMPTY, new Bundle());
+ }
+
+ @SuppressLint("SimpleDateFormat")
+ private String secondsToDisplayableString(int secs) {
+ SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
+ Calendar cal = Calendar.getInstance();
+ cal.set(0, 0, 0, 0, 0, secs);
+ return dateFormat.format(cal.getTime());
+ }
+
+ public void displayContact(LinphoneContact contact, boolean chatOnly) {
+ Fragment fragment2 = getFragmentManager().findFragmentById(R.id.fragmentContainer2);
+ if (fragment2 != null && fragment2.isVisible() && currentFragment == FragmentsAvailable.CONTACT_DETAIL) {
+ ContactDetailsFragment contactFragment = (ContactDetailsFragment) fragment2;
+ contactFragment.changeDisplayedContact(contact);
+ } else {
+ Bundle extras = new Bundle();
+ extras.putSerializable("Contact", contact);
+ extras.putBoolean("ChatAddressOnly", chatOnly);
+ changeCurrentFragment(FragmentsAvailable.CONTACT_DETAIL, extras);
+ }
+ }
+
+ public void displayContacts(boolean chatOnly) {
+ Bundle extras = new Bundle();
+ extras.putBoolean("ChatAddressOnly", chatOnly);
+ changeCurrentFragment(FragmentsAvailable.CONTACTS_LIST, extras);
+ }
+
+ public void displayContactsForEdition(String sipAddress) {
+ Bundle extras = new Bundle();
+ extras.putBoolean("EditOnClick", true);
+ extras.putString("SipAddress", sipAddress);
+ changeCurrentFragment(FragmentsAvailable.CONTACTS_LIST, extras);
+ }
+
+ public void displayAbout() {
+ changeCurrentFragment(FragmentsAvailable.ABOUT, null);
+ }
+
+ public void displayContactsForEdition(String sipAddress, String displayName) {
+ Bundle extras = new Bundle();
+ extras.putBoolean("EditOnClick", true);
+ extras.putString("SipAddress", sipAddress);
+ extras.putString("DisplayName", displayName);
+ changeCurrentFragment(FragmentsAvailable.CONTACTS_LIST, extras);
+ }
+
+ public void displayAssistant() {
+ startActivity(new Intent(LinphoneActivity.this, AssistantActivity.class));
+ }
+
+
+ public void displayInapp() {
+ startActivity(new Intent(LinphoneActivity.this, InAppPurchaseActivity.class));
+ }
+
+ private void displayChat(String sipUri, String message, String fileUri, String pictureUri, String thumbnailUri, String displayName, Address lAddress) {
+ Bundle extras = new Bundle();
+ extras.putString("SipUri", sipUri);
+
+ if (message != null)
+ extras.putString("messageDraft", message);
+ if (fileUri != null)
+ extras.putString("fileSharedUri", fileUri);
+ if (sipUri != null && lAddress.getDisplayName() != null) {
+ extras.putString("DisplayName", displayName);
+ extras.putString("PictureUri", pictureUri);
+ extras.putString("ThumbnailUri", thumbnailUri);
+ }
+
+ if (sipUri == null) {
+ changeCurrentFragment(FragmentsAvailable.CREATE_CHAT, extras);
+ } else {
+ changeCurrentFragment(FragmentsAvailable.GROUP_CHAT, extras);
+ }
+ }
+
+ public void goToChatCreator(String address, ArrayList selectedContacts, String subject, boolean isGoBack, Bundle shareInfos) {
+ if (currentFragment == FragmentsAvailable.INFO_GROUP_CHAT && isGoBack) {
+ getFragmentManager().popBackStackImmediate();
+ getFragmentManager().popBackStackImmediate();
+ }
+ Bundle extras = new Bundle();
+ extras.putSerializable("selectedContacts", selectedContacts);
+ extras.putString("subject", subject);
+ extras.putString("groupChatRoomAddress", address);
+
+ if (shareInfos != null) {
+ if (shareInfos.getString("fileSharedUri") != null)
+ extras.putString("fileSharedUri", shareInfos.getString("fileSharedUri"));
+ if (shareInfos.getString("messageDraft") != null)
+ extras.putString("messageDraft", shareInfos.getString("messageDraft"));
+ }
+
+ changeCurrentFragment(FragmentsAvailable.CREATE_CHAT, extras);
+ }
+
+ public void goToChat(String sipUri, Bundle shareInfos) {
+ Bundle extras = new Bundle();
+ extras.putString("SipUri", sipUri);
+
+ if (shareInfos != null) {
+ if (shareInfos.getString("fileSharedUri") != null)
+ extras.putString("fileSharedUri", shareInfos.getString("fileSharedUri"));
+ if (shareInfos.getString("messageDraft") != null)
+ extras.putString("messageDraft", shareInfos.getString("messageDraft"));
+ }
+
+ if (isTablet()) {
+ Fragment fragment2 = getFragmentManager().findFragmentById(R.id.fragmentContainer2);
+ if (fragment2 != null && fragment2.isVisible() && currentFragment == FragmentsAvailable.GROUP_CHAT && !emptyFragment) {
+ GroupChatFragment chatFragment = (GroupChatFragment) fragment2;
+ chatFragment.changeDisplayedChat(sipUri);
+ } else {
+ changeCurrentFragment(FragmentsAvailable.GROUP_CHAT, extras);
+ }
+ } else {
+ changeCurrentFragment(FragmentsAvailable.GROUP_CHAT, extras);
+ }
+
+ LinphoneManager.getInstance().updateUnreadCountForChatRoom(sipUri, 0);
+ displayMissedChats(LinphoneManager.getInstance().getUnreadMessageCount());
+ }
+
+ public void goToChatGroupInfos(String address, ArrayList contacts, String subject, boolean isEditionEnabled, boolean isGoBack, Bundle shareInfos) {
+ if (currentFragment == FragmentsAvailable.CREATE_CHAT && isGoBack) {
+ getFragmentManager().popBackStackImmediate();
+ getFragmentManager().popBackStackImmediate();
+ }
+ Bundle extras = new Bundle();
+ extras.putString("groupChatRoomAddress", address);
+ extras.putBoolean("isEditionEnabled", isEditionEnabled);
+ extras.putSerializable("ContactAddress", contacts);
+ extras.putString("subject", subject);
+
+ if (shareInfos != null) {
+ if (shareInfos.getString("fileSharedUri") != null)
+ extras.putString("fileSharedUri", shareInfos.getString("fileSharedUri"));
+ if (shareInfos.getString("messageDraft") != null)
+ extras.putString("messageDraft", shareInfos.getString("messageDraft"));
+ }
+
+ changeCurrentFragment(FragmentsAvailable.INFO_GROUP_CHAT, extras);
+ }
+
+ public void goToChatMessageImdnInfos(String sipUri, String messageId) {
+ Bundle extras = new Bundle();
+ extras.putSerializable("SipUri", sipUri);
+ extras.putString("MessageId", messageId);
+ changeCurrentFragment(FragmentsAvailable.MESSAGE_IMDN, extras);
+ }
+
+ public void goToChatList() {
+ changeCurrentFragment(FragmentsAvailable.CHAT_LIST, null);
+ }
+
+ public void displayChat(String sipUri, String message, String fileUri) {
+ if (getResources().getBoolean(R.bool.disable_chat)) {
+ return;
+ }
+
+ String pictureUri = null;
+ String thumbnailUri = null;
+ String displayName = null;
+
+ Address lAddress = null;
+ if (sipUri != null) {
+ lAddress = LinphoneManager.getLc().interpretUrl(sipUri);
+ if (lAddress == null) return;
+ LinphoneContact contact = ContactsManager.getInstance().findContactFromAddress(lAddress);
+ displayName = contact != null ? contact.getFullName() : null;
+
+ if (contact != null && contact.getPhotoUri() != null) {
+ pictureUri = contact.getPhotoUri().toString();
+ thumbnailUri = contact.getThumbnailUri().toString();
+ }
+ }
+
+ if (currentFragment == FragmentsAvailable.CHAT_LIST || currentFragment == FragmentsAvailable.GROUP_CHAT) {
+ Fragment fragment2 = getFragmentManager().findFragmentById(R.id.fragmentContainer2);
+ if (fragment2 != null && fragment2.isVisible() && currentFragment == FragmentsAvailable.GROUP_CHAT && !emptyFragment) {
+ GroupChatFragment chatFragment = (GroupChatFragment) fragment2;
+ chatFragment.changeDisplayedChat(sipUri);
+ } else {
+ displayChat(sipUri, message, fileUri, pictureUri, thumbnailUri, displayName, lAddress);
+ }
+ } else {
+ if (isTablet()) {
+ changeCurrentFragment(FragmentsAvailable.CHAT_LIST, null);
+ } else {
+ displayChat(sipUri, message, fileUri, pictureUri, thumbnailUri, displayName, lAddress);
+ }
+ }
+
+ LinphoneManager.getInstance().updateUnreadCountForChatRoom(sipUri, 0);
+ displayMissedChats(LinphoneManager.getInstance().getUnreadMessageCount());
+ }
+
+ @Override
+ public void onClick(View v) {
+ int id = v.getId();
+ resetSelection();
+
+ if (id == R.id.history) {
+ changeCurrentFragment(FragmentsAvailable.HISTORY_LIST, null);
+ history_selected.setVisibility(View.VISIBLE);
+ LinphoneManager.getLc().resetMissedCallsCount();
+ displayMissedCalls(0);
+ } else if (id == R.id.contacts) {
+ changeCurrentFragment(FragmentsAvailable.CONTACTS_LIST, null);
+ contacts_selected.setVisibility(View.VISIBLE);
+ } else if (id == R.id.dialer) {
+ changeCurrentFragment(FragmentsAvailable.DIALER, null);
+ dialer_selected.setVisibility(View.VISIBLE);
+ } else if (id == R.id.chat) {
+ changeCurrentFragment(FragmentsAvailable.CHAT_LIST, null);
+ chat_selected.setVisibility(View.VISIBLE);
+ } else if (id == R.id.cancel) {
+ hideTopBar();
+ displayDialer();
+ }
+ }
+
+ private void resetSelection() {
+ history_selected.setVisibility(View.GONE);
+ contacts_selected.setVisibility(View.GONE);
+ dialer_selected.setVisibility(View.GONE);
+ chat_selected.setVisibility(View.GONE);
+ }
+
+ public void hideTabBar(Boolean hide) {
+ if (hide) {
+ mTabBar.setVisibility(View.GONE);
+ } else {
+ mTabBar.setVisibility(View.VISIBLE);
+ }
+ }
+
+ public void hideTopBar() {
+ mTopBar.setVisibility(View.GONE);
+ }
+
+ @SuppressWarnings("incomplete-switch")
+ public void selectMenu(FragmentsAvailable menuToSelect) {
+ currentFragment = menuToSelect;
+ resetSelection();
+
+ switch (menuToSelect) {
+ case HISTORY_LIST:
+ case HISTORY_DETAIL:
+ history_selected.setVisibility(View.VISIBLE);
+ break;
+ case CONTACTS_LIST:
+ case CONTACT_DETAIL:
+ case CONTACT_EDITOR:
+ contacts_selected.setVisibility(View.VISIBLE);
+ break;
+ case DIALER:
+ dialer_selected.setVisibility(View.VISIBLE);
+ break;
+ case SETTINGS:
+ case ACCOUNT_SETTINGS:
+ hideTabBar(true);
+ mTopBar.setVisibility(View.VISIBLE);
+ break;
+ case ABOUT:
+ hideTabBar(true);
+ break;
+ case CHAT_LIST:
+ case CREATE_CHAT:
+ case GROUP_CHAT:
+ case INFO_GROUP_CHAT:
+ case MESSAGE_IMDN:
+ case CHAT:
+ chat_selected.setVisibility(View.VISIBLE);
+ break;
+ }
+ }
+
+ public void updateDialerFragment(DialerFragment fragment) {
+ // Hack to maintain soft input flags
+ getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
+ }
+
+ public void goToDialerFragment() {
+ changeCurrentFragment(FragmentsAvailable.DIALER, null);
+ dialer_selected.setVisibility(View.VISIBLE);
+ }
+
+ public void updateStatusFragment(StatusFragment fragment) {
+ statusFragment = fragment;
+ }
+
+ public void displaySettings() {
+ changeCurrentFragment(FragmentsAvailable.SETTINGS, null);
+ }
+
+ public void displayDialer() {
+ changeCurrentFragment(FragmentsAvailable.DIALER, null);
+ }
+
+ public void displayAccountSettings(int accountNumber) {
+ Bundle bundle = new Bundle();
+ bundle.putInt("Account", accountNumber);
+ changeCurrentFragment(FragmentsAvailable.ACCOUNT_SETTINGS, bundle);
+ //settings.setSelected(true);
+ }
+
+ public StatusFragment getStatusFragment() {
+ return statusFragment;
+ }
+
+ public void refreshMissedChatCountDisplay() {
+ displayMissedChats(LinphoneManager.getInstance().getUnreadMessageCount());
+ }
+
+ public void displayMissedCalls(final int missedCallsCount) {
+ if (missedCallsCount > 0) {
+ missedCalls.setText(missedCallsCount + "");
+ missedCalls.setVisibility(View.VISIBLE);
+ } else {
+ if (LinphoneManager.isInstanciated()) LinphoneManager.getLc().resetMissedCallsCount();
+ missedCalls.clearAnimation();
+ missedCalls.setVisibility(View.GONE);
+ }
+ }
+
+ private void displayMissedChats(final int missedChatCount) {
+ if (missedChatCount > 0) {
+ missedChats.setText(missedChatCount + "");
+ missedChats.setVisibility(View.VISIBLE);
+ } else {
+ missedChats.clearAnimation();
+ missedChats.setVisibility(View.GONE);
+ }
+ }
+
+ public void displayCustomToast(final String message, final int duration) {
+ LayoutInflater inflater = getLayoutInflater();
+ View layout = inflater.inflate(R.layout.toast, (ViewGroup) findViewById(R.id.toastRoot));
+
+ TextView toastText = (TextView) layout.findViewById(R.id.toastMessage);
+ toastText.setText(message);
+
+ final Toast toast = new Toast(getApplicationContext());
+ toast.setGravity(Gravity.CENTER, 0, 0);
+ toast.setDuration(duration);
+ toast.setView(layout);
+ toast.show();
+ }
+
+ public void displayChatRoomError() {
+ final Dialog dialog = LinphoneActivity.instance().displayDialog(getString(R.string.chat_room_creation_failed));
+ Button delete = dialog.findViewById(R.id.delete_button);
+ Button cancel = dialog.findViewById(R.id.cancel);
+ delete.setVisibility(View.GONE);
+ cancel.setText(getString(R.string.ok));
+ cancel.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ dialog.dismiss();
+ }
+ });
+
+ dialog.show();
+ }
+
+ public Dialog displayDialog(String text) {
+ Dialog dialog = new Dialog(this);
+ dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
+ Drawable d = new ColorDrawable(ContextCompat.getColor(this, R.color.colorC));
+ d.setAlpha(200);
+ dialog.setContentView(R.layout.dialog);
+ dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
+ dialog.getWindow().setBackgroundDrawable(d);
+
+ TextView customText = (TextView) dialog.findViewById(R.id.customText);
+ customText.setText(text);
+ return dialog;
+ }
+
+ @Override
+ public void setAddresGoToDialerAndCall(String number, String name, Uri photo) {
// Bundle extras = new Bundle();
// extras.putString("SipUri", number);
// extras.putString("DisplayName", name);
// extras.putString("Photo", photo == null ? null : photo.toString());
// changeCurrentFragment(FragmentsAvailable.DIALER, extras);
- AddressType address = new AddressText(this, null);
- address.setDisplayedName(name);
- address.setText(number);
- LinphoneManager.getInstance().newOutgoingCall(address);
- }
-
- public void startIncallActivity(Call currentCall) {
- Intent intent = new Intent(this, CallActivity.class);
- startOrientationSensor();
- startActivityForResult(intent, CALL_ACTIVITY);
- }
-
- /**
- * Register a sensor to track phoneOrientation changes
- */
- private synchronized void startOrientationSensor() {
- if (mOrientationHelper == null) {
- mOrientationHelper = new LocalOrientationEventListener(this);
- }
- mOrientationHelper.enable();
- }
-
- private int mAlwaysChangingPhoneAngle = -1;
-
- private class LocalOrientationEventListener extends OrientationEventListener {
- public LocalOrientationEventListener(Context context) {
- super(context);
- }
-
- @Override
- public void onOrientationChanged(final int o) {
- if (o == OrientationEventListener.ORIENTATION_UNKNOWN) {
- return;
- }
-
- int degrees = 270;
- if (o < 45 || o > 315)
- degrees = 0;
- else if (o < 135)
- degrees = 90;
- else if (o < 225)
- degrees = 180;
-
- if (mAlwaysChangingPhoneAngle == degrees) {
- return;
- }
- mAlwaysChangingPhoneAngle = degrees;
-
- Log.d("Phone orientation changed to ", degrees);
- int rotation = (360 - degrees) % 360;
- Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- if (lc != null) {
- lc.setDeviceRotation(rotation);
- Call currentCall = lc.getCurrentCall();
- if (currentCall != null && currentCall.cameraEnabled() && currentCall.getCurrentParams().videoEnabled()) {
- lc.updateCall(currentCall, null);
- }
- }
- }
- }
-
- public Boolean isCallTransfer(){
- return callTransfer;
- }
-
- private void initInCallMenuLayout(final boolean callTransfer) {
- selectMenu(FragmentsAvailable.DIALER);
- DialerFragment dialerFragment = DialerFragment.instance();
- if (dialerFragment != null) {
- ((DialerFragment) dialerFragment).resetLayout(callTransfer);
- }
- }
-
- public void resetClassicMenuLayoutAndGoBackToCallIfStillRunning() {
- DialerFragment dialerFragment = DialerFragment.instance();
- if (dialerFragment != null) {
- ((DialerFragment) dialerFragment).resetLayout(true);
- }
-
- if (LinphoneManager.isInstanciated() && LinphoneManager.getLc().getCallsNb() > 0) {
- Call call = LinphoneManager.getLc().getCalls()[0];
- if (call.getState() == Call.State.IncomingReceived) {
- startActivity(new Intent(LinphoneActivity.this, CallIncomingActivity.class));
- } else {
- startIncallActivity(call);
- }
- }
- }
-
- public FragmentsAvailable getCurrentFragment() {
- return currentFragment;
- }
-
- public void addContact(String displayName, String sipUri)
- {
- Bundle extras = new Bundle();
- extras.putSerializable("NewSipAdress", sipUri);
- extras.putSerializable("NewDisplayName", displayName);
- changeCurrentFragment(FragmentsAvailable.CONTACT_EDITOR, extras);
- }
-
- public void editContact(LinphoneContact contact)
- {
- Bundle extras = new Bundle();
- extras.putSerializable("Contact", contact);
- changeCurrentFragment(FragmentsAvailable.CONTACT_EDITOR, extras);
- }
-
- public void editContact(LinphoneContact contact, String sipAddress)
- {
- Bundle extras = new Bundle();
- extras.putSerializable("Contact", contact);
- extras.putSerializable("NewSipAdress", sipAddress);
- changeCurrentFragment(FragmentsAvailable.CONTACT_EDITOR, extras);
- }
-
- public void quit() {
- finish();
- stopService(new Intent(Intent.ACTION_MAIN).setClass(this, LinphoneService.class));
- ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
- am.killBackgroundProcesses(getString(R.string.sync_account_type));
- android.os.Process.killProcess(android.os.Process.myPid());
- }
-
- @Override
- protected void onPostResume() {
- super.onPostResume();
- if (pendingFragmentTransaction != FragmentsAvailable.UNKNOW) {
- changeCurrentFragment(pendingFragmentTransaction, null, true);
- selectMenu(pendingFragmentTransaction);
- pendingFragmentTransaction = FragmentsAvailable.UNKNOW;
- }
- }
-
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- if (getIntent() != null && getIntent().getExtras() != null) {
- newProxyConfig = getIntent().getExtras().getBoolean("isNewProxyConfig");
- }
-
- if (resultCode == Activity.RESULT_FIRST_USER && requestCode == SETTINGS_ACTIVITY) {
- if (data.getExtras().getBoolean("Exit", false)) {
- quit();
- } else {
- pendingFragmentTransaction = (FragmentsAvailable) data.getExtras().getSerializable("FragmentToDisplay");
- }
- } else if (resultCode == Activity.RESULT_FIRST_USER && requestCode == CALL_ACTIVITY) {
- getIntent().putExtra("PreviousActivity", CALL_ACTIVITY);
- callTransfer = data != null && data.getBooleanExtra("Transfer", false);
- boolean chat = data != null && data.getBooleanExtra("chat", false);
- if(chat){
- pendingFragmentTransaction = FragmentsAvailable.CHAT_LIST;
- }
- if (LinphoneManager.getLc().getCallsNb() > 0) {
- initInCallMenuLayout(callTransfer);
- } else {
- resetClassicMenuLayoutAndGoBackToCallIfStillRunning();
- }
- } else if (requestCode == PERMISSIONS_REQUEST_OVERLAY) {
- if (Compatibility.canDrawOverlays(this)) {
- LinphonePreferences.instance().enableOverlay(true);
- }
- } else {
- super.onActivityResult(requestCode, resultCode, data);
- }
- }
-
- @Override
- protected void onPause() {
- getIntent().putExtra("PreviousActivity", 0);
-
- Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- if (lc != null) {
- lc.removeListener(mListener);
- }
- callTransfer = false;
- isOnBackground = true;
-
- super.onPause();
- }
-
- public boolean checkAndRequestOverlayPermission() {
- Log.i("[Permission] Draw overlays permission is " + (Compatibility.canDrawOverlays(this) ? "granted" : "denied"));
- if (!Compatibility.canDrawOverlays(this)) {
- Log.i("[Permission] Asking for overlay");
- Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
- startActivityForResult(intent, PERMISSIONS_REQUEST_OVERLAY);
- return false;
- }
- return true;
- }
-
- public void checkAndRequestExternalStoragePermission() {
- checkAndRequestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, 0);
- }
-
- public void checkAndRequestCameraPermission() {
- checkAndRequestPermission(Manifest.permission.CAMERA, 0);
- }
-
- public void checkAndRequestWriteContactsPermission() {
- checkAndRequestPermission(Manifest.permission.WRITE_CONTACTS, 0);
- }
-
- public void checkAndRequestRecordAudioPermissionForEchoCanceller() {
- checkAndRequestPermission(Manifest.permission.RECORD_AUDIO, PERMISSIONS_RECORD_AUDIO_ECHO_CANCELLER);
- }
-
- public void checkAndRequestRecordAudioPermissionsForEchoTester() {
- checkAndRequestPermission(Manifest.permission.RECORD_AUDIO, PERMISSIONS_RECORD_AUDIO_ECHO_TESTER);
- }
-
- public void checkAndRequestReadExternalStoragePermissionForDeviceRingtone() {
- checkAndRequestPermission(Manifest.permission.READ_EXTERNAL_STORAGE, PERMISSIONS_READ_EXTERNAL_STORAGE_DEVICE_RINGTONE);
- }
-
- public void checkAndRequestPermissionsToSendImage() {
- ArrayList permissionsList = new ArrayList();
-
- int readExternalStorage = getPackageManager().checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE, getPackageName());
- Log.i("[Permission] Read external storage permission is " + (readExternalStorage == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
- int camera = getPackageManager().checkPermission(Manifest.permission.CAMERA, getPackageName());
- Log.i("[Permission] Camera permission is " + (camera == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
-
- if (readExternalStorage != PackageManager.PERMISSION_GRANTED) {
- ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE);
- Log.i("[Permission] Asking for read external storage");
- permissionsList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
- }
- if (camera != PackageManager.PERMISSION_GRANTED) {
- ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA);
- Log.i("[Permission] Asking for camera");
- permissionsList.add(Manifest.permission.CAMERA);
- }
- if (permissionsList.size() > 0) {
- String[] permissions = new String[permissionsList.size()];
- permissions = permissionsList.toArray(permissions);
- ActivityCompat.requestPermissions(this, permissions, 0);
- }
- }
-
- private void checkSyncPermission() {
- checkAndRequestPermission(Manifest.permission.WRITE_SYNC_SETTINGS, PERMISSIONS_REQUEST_SYNC);
- }
-
- public void checkAndRequestPermission(String permission, int result) {
- int permissionGranted = getPackageManager().checkPermission(permission, getPackageName());
- Log.i("[Permission] " + permission + " is " + (permissionGranted == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
-
- if (permissionGranted != PackageManager.PERMISSION_GRANTED) {
- ActivityCompat.shouldShowRequestPermissionRationale(this, permission);
- Log.i("[Permission] Asking for " + permission);
- ActivityCompat.requestPermissions(this, new String[] { permission }, result);
- }
- }
-
- @Override
- public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
- if (permissions.length <= 0)
- return;
-
- int readContactsI = -1;
- for (int i = 0; i < permissions.length; i++) {
- Log.i("[Permission] " + permissions[i] + " is " + (grantResults[i] == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
- if (permissions[i].compareTo(Manifest.permission.READ_CONTACTS) == 0 ||
- permissions[i].compareTo(Manifest.permission.WRITE_CONTACTS) == 0)
- readContactsI = i;
- }
-
- switch (requestCode) {
- case PERMISSIONS_REQUEST_SYNC:
- if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
- ContactsManager.getInstance().initializeSyncAccount(getApplicationContext(), getContentResolver());
- } else {
- ContactsManager.getInstance().initializeContactManager(getApplicationContext(), getContentResolver());
- }
- break;
- case PERMISSIONS_RECORD_AUDIO_ECHO_CANCELLER:
- if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
- ((SettingsFragment) fragment).startEchoCancellerCalibration();
- } else {
- ((SettingsFragment) fragment).echoCalibrationFail();
- }
- break;
- case PERMISSIONS_READ_EXTERNAL_STORAGE_DEVICE_RINGTONE:
- if (permissions[0].compareTo(Manifest.permission.READ_EXTERNAL_STORAGE) != 0)
- break;
- boolean enableRingtone = (grantResults[0] == PackageManager.PERMISSION_GRANTED);
- LinphonePreferences.instance().enableDeviceRingtone(enableRingtone);
- LinphoneManager.getInstance().enableDeviceRingtone(enableRingtone);
- break;
- case PERMISSIONS_RECORD_AUDIO_ECHO_TESTER:
- if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
- ((SettingsFragment) fragment).startEchoTester();
- break;
- }
- if (readContactsI >= 0 && grantResults[readContactsI] == PackageManager.PERMISSION_GRANTED) {
- ContactsManager.getInstance().enableContactsAccess();
- if (!ContactsManager.getInstance().contactsFetchedOnce()) {
- ContactsManager.getInstance().enableContactsAccess();
- ContactsManager.getInstance().fetchContactsAsync();
- }
- }
- }
-
- @Override
- protected void onStart() {
- super.onStart();
- ArrayList permissionsList = new ArrayList();
-
- int contacts = getPackageManager().checkPermission(Manifest.permission.READ_CONTACTS, getPackageName());
- Log.i("[Permission] Contacts permission is " + (contacts == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
-
- int readPhone = getPackageManager().checkPermission(Manifest.permission.READ_PHONE_STATE, getPackageName());
- Log.i("[Permission] Read phone state permission is " + (readPhone == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
-
- int ringtone = getPackageManager().checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE, getPackageName());
- Log.i("[Permission] Read external storage for ring tone permission is " + (ringtone == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
-
- if (ringtone != PackageManager.PERMISSION_GRANTED) {
- if (LinphonePreferences.instance().firstTimeAskingForPermission(Manifest.permission.READ_EXTERNAL_STORAGE) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
- Log.i("[Permission] Asking for read external storage for ring tone");
- permissionsList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
- }
- }
- if (readPhone != PackageManager.PERMISSION_GRANTED) {
- if (LinphonePreferences.instance().firstTimeAskingForPermission(Manifest.permission.READ_PHONE_STATE) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_STATE)) {
- Log.i("[Permission] Asking for read phone state");
- permissionsList.add(Manifest.permission.READ_PHONE_STATE);
- }
- }
- if (contacts != PackageManager.PERMISSION_GRANTED) {
- if (LinphonePreferences.instance().firstTimeAskingForPermission(Manifest.permission.READ_CONTACTS) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_CONTACTS)) {
- Log.i("[Permission] Asking for contacts");
- permissionsList.add(Manifest.permission.READ_CONTACTS);
- }
- } else {
- if (!ContactsManager.getInstance().contactsFetchedOnce()) {
- ContactsManager.getInstance().enableContactsAccess();
- ContactsManager.getInstance().fetchContactsAsync();
- }
- }
-
- if (permissionsList.size() > 0) {
- String[] permissions = new String[permissionsList.size()];
- permissions = permissionsList.toArray(permissions);
- ActivityCompat.requestPermissions(this, permissions, PERMISSIONS_READ_EXTERNAL_STORAGE_DEVICE_RINGTONE);
- }
- }
-
- @Override
- protected void onSaveInstanceState(Bundle outState) {
- outState.putSerializable("currentFragment", currentFragment);
- super.onSaveInstanceState(outState);
- }
-
- @Override
- protected void onRestoreInstanceState(Bundle savedInstanceState) {
- super.onRestoreInstanceState(savedInstanceState);
- }
-
- public void disableGoToCall() {
- doNotGoToCallActivity = true;
- }
-
- @Override
- protected void onResume() {
- super.onResume();
- if (!LinphoneService.isReady()) {
- startService(new Intent(Intent.ACTION_MAIN).setClass(this, LinphoneService.class));
- }
-
- Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- if (lc != null) {
- lc.addListener(mListener);
- if (!LinphoneService.instance().displayServiceNotification()) {
- lc.refreshRegisters();
- }
- }
-
- if (isTablet()) {
- // Prevent fragmentContainer2 to be visible when rotating the device
- LinearLayout ll = (LinearLayout) findViewById(R.id.fragmentContainer2);
- if (currentFragment == FragmentsAvailable.DIALER
- || currentFragment == FragmentsAvailable.ABOUT
- || currentFragment == FragmentsAvailable.SETTINGS
- || currentFragment == FragmentsAvailable.ACCOUNT_SETTINGS) {
- ll.setVisibility(View.GONE);
- }
- }
-
- refreshAccounts();
-
- if(getResources().getBoolean(R.bool.enable_in_app_purchase)){
- isTrialAccount();
- }
-
- displayMissedChats(LinphoneManager.getInstance().getUnreadMessageCount());
- displayMissedCalls(LinphoneManager.getLc().getMissedCallsCount());
-
- LinphoneManager.getInstance().changeStatusToOnline();
-
- if (getIntent().getIntExtra("PreviousActivity", 0) != CALL_ACTIVITY && !doNotGoToCallActivity) {
- if (LinphoneManager.getLc().getCalls().length > 0) {
- Call call = LinphoneManager.getLc().getCalls()[0];
- Call.State onCallStateChanged = call.getState();
-
- if (onCallStateChanged == State.IncomingReceived) {
- startActivity(new Intent(this, CallIncomingActivity.class));
- } else if (onCallStateChanged == State.OutgoingInit || onCallStateChanged == State.OutgoingProgress || onCallStateChanged == State.OutgoingRinging) {
- startActivity(new Intent(this, CallOutgoingActivity.class));
- } else {
- startIncallActivity(call);
- }
- }
- }
-
- Intent intent = getIntent();
-
- if (intent.getStringExtra("msgShared") != null) {
- displayChat(null, intent.getStringExtra("msgShared"), null);
- intent.putExtra("msgShared", "");
- }
- if (intent.getStringExtra("fileShared") != null && intent.getStringExtra("fileShared") != "") {
- displayChat(null, null, intent.getStringExtra("fileShared"));
- intent.putExtra("fileShared", "");
- }
- doNotGoToCallActivity = false;
- isOnBackground = false;
-
- if (intent != null) {
- Bundle extras = intent.getExtras();
- if (extras != null && extras.containsKey("SipUriOrNumber")) {
- mAddressWaitingToBeCalled = extras.getString("SipUriOrNumber");
- intent.removeExtra("SipUriOrNumber");
- goToDialerFragment();
- }
- }
- }
-
- @Override
- protected void onDestroy() {
- if (mOrientationHelper != null) {
- mOrientationHelper.disable();
- mOrientationHelper = null;
- }
-
- instance = null;
- super.onDestroy();
-
- unbindDrawables(findViewById(R.id.topLayout));
- System.gc();
- }
-
- private void unbindDrawables(View view) {
- if (view != null && view.getBackground() != null) {
- view.getBackground().setCallback(null);
- }
- if (view instanceof ViewGroup && !(view instanceof AdapterView)) {
- for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
- unbindDrawables(((ViewGroup) view).getChildAt(i));
- }
- ((ViewGroup) view).removeAllViews();
- }
- }
-
- @Override
- protected void onNewIntent(Intent intent) {
- super.onNewIntent(intent);
- if (getCurrentFragment() == FragmentsAvailable.SETTINGS) {
- if (fragment instanceof SettingsFragment) {
- ((SettingsFragment) fragment).closePreferenceScreen();
- }
- }
- Bundle extras = intent.getExtras();
- if (extras != null && extras.getBoolean("GoToChat", false)) {
- String sipUri = extras.getString("ChatContactSipUri");
- doNotGoToCallActivity = true;
- displayChat(sipUri, null, null);
- } else if (extras != null && extras.getBoolean("GoToHistory", false)) {
- doNotGoToCallActivity = true;
- changeCurrentFragment(FragmentsAvailable.HISTORY_LIST, null);
- } else if (extras != null && extras.getBoolean("GoToInapp", false)) {
- doNotGoToCallActivity = true;
- displayInapp();
- } else if (extras != null && extras.getBoolean("Notification", false)) {
- if (LinphoneManager.getLc().getCallsNb() > 0) {
- Call call = LinphoneManager.getLc().getCalls()[0];
- startIncallActivity(call);
- }
- }else if (extras != null && extras.getBoolean("StartCall", false)) {
- boolean extraBool = extras.getBoolean("StartCall", false);
- if (CallActivity.isInstanciated()) {
- CallActivity.instance().startIncomingCallActivity();
- } else {
- mAddressWaitingToBeCalled = extras.getString("NumberToCall");
- goToDialerFragment();
- //startActivity(new Intent(this, CallIncomingActivity.class));
- }
- } else {
- DialerFragment dialerFragment = DialerFragment.instance();
- if (dialerFragment != null) {
- if (extras != null && extras.containsKey("SipUriOrNumber")) {
- if (getResources().getBoolean(R.bool.automatically_start_intercepted_outgoing_gsm_call)) {
- ((DialerFragment) dialerFragment).newOutgoingCall(extras.getString("SipUriOrNumber"));
- } else {
- ((DialerFragment) dialerFragment).displayTextInAddressBar(extras.getString("SipUriOrNumber"));
- }
- } else {
- ((DialerFragment) dialerFragment).newOutgoingCall(intent);
- }
- } else {
- if (extras != null && extras.containsKey("SipUriOrNumber")) {
- mAddressWaitingToBeCalled = extras.getString("SipUriOrNumber");
- goToDialerFragment();
- }
- }
- if (LinphoneManager.getLc().getCalls().length > 0) {
- // If a call is ringing, start incomingcallactivity
- Collection incoming = new ArrayList();
- incoming.add(Call.State.IncomingReceived);
- if (LinphoneUtils.getCallsInState(LinphoneManager.getLc(), incoming).size() > 0) {
- if (CallActivity.isInstanciated()) {
- CallActivity.instance().startIncomingCallActivity();
- } else {
- startActivity(new Intent(this, CallIncomingActivity.class));
- }
- }
- }
- }
- }
-
- public boolean isOnBackground() {
- return isOnBackground;
- }
-
- public boolean onKeyDown(int keyCode, KeyEvent event) {
- if (keyCode == KeyEvent.KEYCODE_BACK) {
- switch(currentFragment) {
- case DIALER :
- case CONTACTS_LIST:
- case HISTORY_LIST:
- case CHAT_LIST:
- boolean isBackgroundModeActive = LinphonePreferences.instance().isBackgroundModeEnabled();
- if (!isBackgroundModeActive) {
- stopService(new Intent(Intent.ACTION_MAIN).setClass(this, LinphoneService.class));
- finish();
- } else if (LinphoneUtils.onKeyBackGoHome(this, keyCode, event)) {
- return true;
- }
- break;
- case GROUP_CHAT:
- LinphoneActivity.instance().goToChatList();
- return true;
- default:
- break;
- }
- }
- return super.onKeyDown(keyCode, event);
- }
-
- //SIDE MENU
- public void openOrCloseSideMenu(boolean open) {
- if(open) {
- sideMenu.openDrawer(sideMenuContent);
- } else {
- sideMenu.closeDrawer(sideMenuContent);
- }
- }
-
- public void initSideMenu() {
- sideMenu = (DrawerLayout) findViewById(R.id.side_menu);
- sideMenuItems = new ArrayList();
- sideMenuItems.add(getResources().getString(R.string.menu_assistant));
- sideMenuItems.add(getResources().getString(R.string.menu_settings));
- if(getResources().getBoolean(R.bool.enable_in_app_purchase)){
- sideMenuItems.add(getResources().getString(R.string.inapp));
- }
- sideMenuItems.add(getResources().getString(R.string.menu_about));
- sideMenuContent = (RelativeLayout) findViewById(R.id.side_menu_content);
- sideMenuItemList = (ListView)findViewById(R.id.item_list);
- menu = (ImageView) findViewById(R.id.side_menu_button);
-
- sideMenuItemList.setAdapter(new ArrayAdapter(this, R.layout.side_menu_item_cell, sideMenuItems));
- sideMenuItemList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
- @Override
- public void onItemClick(AdapterView> adapterView, View view, int i, long l) {
- if (sideMenuItemList.getAdapter().getItem(i).toString().equals(getString(R.string.menu_settings))) {
- LinphoneActivity.instance().displaySettings();
- }
- if (sideMenuItemList.getAdapter().getItem(i).toString().equals(getString(R.string.menu_about))) {
- LinphoneActivity.instance().displayAbout();
- }
- if (sideMenuItemList.getAdapter().getItem(i).toString().equals(getString(R.string.menu_assistant))) {
- LinphoneActivity.instance().displayAssistant();
- }
- if(getResources().getBoolean(R.bool.enable_in_app_purchase)){
- if (sideMenuItemList.getAdapter().getItem(i).toString().equals(getString(R.string.inapp))) {
- LinphoneActivity.instance().displayInapp();
- }
- }
- openOrCloseSideMenu(false);
- }
- });
-
- initAccounts();
-
- menu.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View view) {
-
- if(sideMenu.isDrawerVisible(Gravity.LEFT)){
- sideMenu.closeDrawer(sideMenuContent);
- } else {
- sideMenu.openDrawer(sideMenuContent);
- }
- }
- });
-
- quitLayout = (RelativeLayout) findViewById(R.id.side_menu_quit);
- quitLayout.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View view) {
- LinphoneActivity.instance().quit();
- }
- });
- }
-
- private int getStatusIconResource(RegistrationState state) {
- try {
- if (state == RegistrationState.Ok) {
- return R.drawable.led_connected;
- } else if (state == RegistrationState.Progress) {
- return R.drawable.led_inprogress;
- } else if (state == RegistrationState.Failed) {
- return R.drawable.led_error;
- } else {
- return R.drawable.led_disconnected;
- }
- } catch (Exception e) {
- Log.e(e);
- }
-
- return R.drawable.led_disconnected;
- }
-
- private void displayMainAccount(){
- defaultAccount.setVisibility(View.VISIBLE);
- ImageView status = (ImageView) defaultAccount.findViewById(R.id.main_account_status);
- TextView address = (TextView) defaultAccount.findViewById(R.id.main_account_address);
- TextView displayName = (TextView) defaultAccount.findViewById(R.id.main_account_display_name);
-
-
- ProxyConfig proxy = LinphoneManager.getLc().getDefaultProxyConfig();
- if(proxy == null) {
- displayName.setText(getString(R.string.no_account));
- status.setVisibility(View.GONE);
- address.setText("");
- statusFragment.resetAccountStatus();
- LinphoneManager.getInstance().subscribeFriendList(false);
-
- defaultAccount.setOnClickListener(null);
- } else {
- address.setText(proxy.getIdentityAddress().asStringUriOnly());
- displayName.setText(LinphoneUtils.getAddressDisplayName(proxy.getIdentityAddress()));
- status.setImageResource(getStatusIconResource(proxy.getState()));
- status.setVisibility(View.VISIBLE);
-
- defaultAccount.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View view) {
- LinphoneActivity.instance().displayAccountSettings(LinphonePreferences.instance().getDefaultAccountIndex());
- openOrCloseSideMenu(false);
- }
- });
- }
- }
-
- public void refreshAccounts(){
- if (LinphoneManager.getLc().getProxyConfigList() != null &&
- LinphoneManager.getLc().getProxyConfigList().length > 1) {
- accountsList.setVisibility(View.VISIBLE);
- accountsList.setAdapter(new AccountsListAdapter());
- accountsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
- @Override
- public void onItemClick(AdapterView> adapterView, View view, int i, long l) {
- if(view != null && view.getTag() != null) {
- int position = Integer.parseInt(view.getTag().toString());
- LinphoneActivity.instance().displayAccountSettings(position);
- }
- openOrCloseSideMenu(false);
- }
- });
- } else {
- accountsList.setVisibility(View.GONE);
- }
- displayMainAccount();
- }
-
- private void initAccounts() {
- accountsList = (ListView) findViewById(R.id.accounts_list);
- defaultAccount = (RelativeLayout) findViewById(R.id.default_account);
- }
-
- class AccountsListAdapter extends BaseAdapter {
- List proxy_list;
-
- AccountsListAdapter() {
- proxy_list = new ArrayList();
- refresh();
- }
-
- public void refresh(){
- proxy_list = new ArrayList();
- for(ProxyConfig proxyConfig : LinphoneManager.getLc().getProxyConfigList()){
- if(proxyConfig != LinphoneManager.getLc().getDefaultProxyConfig()){
- proxy_list.add(proxyConfig);
- }
- }
- }
-
- public int getCount() {
- if (proxy_list != null) {
- return proxy_list.size();
- } else {
- return 0;
- }
- }
-
- public Object getItem(int position) {
- return proxy_list.get(position);
- }
-
- public long getItemId(int position) {
- return position;
- }
-
- public View getView(final int position, View convertView, ViewGroup parent) {
- View view = null;
- ProxyConfig lpc = (ProxyConfig) getItem(position);
- if (convertView != null) {
- view = convertView;
- } else {
- view = getLayoutInflater().inflate(R.layout.side_menu_account_cell, parent, false);
- }
-
- ImageView status = (ImageView) view.findViewById(R.id.account_status);
- TextView address = (TextView) view.findViewById(R.id.account_address);
- String sipAddress = lpc.getIdentityAddress().asStringUriOnly();
-
- address.setText(sipAddress);
-
- int nbAccounts = LinphonePreferences.instance().getAccountCount();
- int accountIndex = 0;
-
- for (int i = 0; i < nbAccounts; i++) {
- String username = LinphonePreferences.instance().getAccountUsername(i);
- String domain = LinphonePreferences.instance().getAccountDomain(i);
- String id = "sip:" + username + "@" + domain;
- if (id.equals(sipAddress)) {
- accountIndex = i;
- view.setTag(accountIndex);
- break;
- }
- }
- status.setImageResource(getStatusIconResource(lpc.getState()));
- return view;
- }
- }
-
- //Inapp Purchase
- private void isTrialAccount() {
- if(LinphoneManager.getLc().getDefaultProxyConfig() != null && LinphonePreferences.instance().getInappPopupTime() != null) {
- XmlRpcHelper helper = new XmlRpcHelper();
- helper.isTrialAccountAsync(new XmlRpcListenerBase() {
- @Override
- public void onTrialAccountFetched(boolean isTrial) {
- isTrialAccount = isTrial;
- getExpirationAccount();
- }
-
- @Override
- public void onError(String error) {
- }
- }, LinphonePreferences.instance().getAccountUsername(LinphonePreferences.instance().getDefaultAccountIndex()), LinphonePreferences.instance().getAccountHa1(LinphonePreferences.instance().getDefaultAccountIndex()));
- }
- }
-
- private void getExpirationAccount() {
- if(LinphoneManager.getLc().getDefaultProxyConfig() != null && LinphonePreferences.instance().getInappPopupTime() != null) {
- XmlRpcHelper helper = new XmlRpcHelper();
- helper.getAccountExpireAsync(new XmlRpcListenerBase() {
- @Override
- public void onAccountExpireFetched(String result) {
- if (result != null) {
- long timestamp = Long.parseLong(result);
-
- Calendar calresult = Calendar.getInstance();
- calresult.setTimeInMillis(timestamp);
-
- int diff = getDiffDays(calresult, Calendar.getInstance());
- if (diff != -1 && diff <= getResources().getInteger(R.integer.days_notification_shown)) {
- displayInappNotification(timestampToHumanDate(calresult));
- }
- }
- }
-
- @Override
- public void onError(String error) {
- }
- }, LinphonePreferences.instance().getAccountUsername(LinphonePreferences.instance().getDefaultAccountIndex()), LinphonePreferences.instance().getAccountHa1(LinphonePreferences.instance().getDefaultAccountIndex()));
- }
- }
-
- public void displayInappNotification(String date) {
- Timestamp now = new Timestamp(new Date().getTime());
- if (LinphonePreferences.instance().getInappPopupTime() != null && Long.parseLong(LinphonePreferences.instance().getInappPopupTime()) > now.getTime()) {
- return;
- } else {
- long newDate = now.getTime() + getResources().getInteger(R.integer.time_between_inapp_notification);
- LinphonePreferences.instance().setInappPopupTime(String.valueOf(newDate));
- }
- if(isTrialAccount){
- LinphoneService.instance().displayInappNotification(String.format(getString(R.string.inapp_notification_trial_expire), date));
- } else {
- LinphoneService.instance().displayInappNotification(String.format(getString(R.string.inapp_notification_account_expire), date));
- }
-
- }
-
- private String timestampToHumanDate(Calendar cal) {
- SimpleDateFormat dateFormat;
- dateFormat = new SimpleDateFormat(getResources().getString(R.string.inapp_popup_date_format));
- return dateFormat.format(cal.getTime());
- }
-
- private int getDiffDays(Calendar cal1, Calendar cal2) {
- if (cal1 == null || cal2 == null) {
- return -1;
- }
- if(cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)){
- return cal1.get(Calendar.DAY_OF_YEAR) - cal2.get(Calendar.DAY_OF_YEAR);
- }
- return -1;
- }
+ AddressType address = new AddressText(this, null);
+ address.setDisplayedName(name);
+ address.setText(number);
+ LinphoneManager.getInstance().newOutgoingCall(address);
+ }
+
+ public void startIncallActivity(Call currentCall) {
+ Intent intent = new Intent(this, CallActivity.class);
+ startOrientationSensor();
+ startActivityForResult(intent, CALL_ACTIVITY);
+ }
+
+ /**
+ * Register a sensor to track phoneOrientation changes
+ */
+ private synchronized void startOrientationSensor() {
+ if (mOrientationHelper == null) {
+ mOrientationHelper = new LocalOrientationEventListener(this);
+ }
+ mOrientationHelper.enable();
+ }
+
+ private int mAlwaysChangingPhoneAngle = -1;
+
+ private class LocalOrientationEventListener extends OrientationEventListener {
+ public LocalOrientationEventListener(Context context) {
+ super(context);
+ }
+
+ @Override
+ public void onOrientationChanged(final int o) {
+ if (o == OrientationEventListener.ORIENTATION_UNKNOWN) {
+ return;
+ }
+
+ int degrees = 270;
+ if (o < 45 || o > 315)
+ degrees = 0;
+ else if (o < 135)
+ degrees = 90;
+ else if (o < 225)
+ degrees = 180;
+
+ if (mAlwaysChangingPhoneAngle == degrees) {
+ return;
+ }
+ mAlwaysChangingPhoneAngle = degrees;
+
+ Log.d("Phone orientation changed to ", degrees);
+ int rotation = (360 - degrees) % 360;
+ Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ if (lc != null) {
+ lc.setDeviceRotation(rotation);
+ Call currentCall = lc.getCurrentCall();
+ if (currentCall != null && currentCall.cameraEnabled() && currentCall.getCurrentParams().videoEnabled()) {
+ lc.updateCall(currentCall, null);
+ }
+ }
+ }
+ }
+
+ public Boolean isCallTransfer() {
+ return callTransfer;
+ }
+
+ private void initInCallMenuLayout(final boolean callTransfer) {
+ selectMenu(FragmentsAvailable.DIALER);
+ DialerFragment dialerFragment = DialerFragment.instance();
+ if (dialerFragment != null) {
+ ((DialerFragment) dialerFragment).resetLayout(callTransfer);
+ }
+ }
+
+ public void resetClassicMenuLayoutAndGoBackToCallIfStillRunning() {
+ DialerFragment dialerFragment = DialerFragment.instance();
+ if (dialerFragment != null) {
+ ((DialerFragment) dialerFragment).resetLayout(true);
+ }
+
+ if (LinphoneManager.isInstanciated() && LinphoneManager.getLc().getCallsNb() > 0) {
+ Call call = LinphoneManager.getLc().getCalls()[0];
+ if (call.getState() == Call.State.IncomingReceived) {
+ startActivity(new Intent(LinphoneActivity.this, CallIncomingActivity.class));
+ } else {
+ startIncallActivity(call);
+ }
+ }
+ }
+
+ public FragmentsAvailable getCurrentFragment() {
+ return currentFragment;
+ }
+
+ public void addContact(String displayName, String sipUri) {
+ Bundle extras = new Bundle();
+ extras.putSerializable("NewSipAdress", sipUri);
+ extras.putSerializable("NewDisplayName", displayName);
+ changeCurrentFragment(FragmentsAvailable.CONTACT_EDITOR, extras);
+ }
+
+ public void editContact(LinphoneContact contact) {
+ Bundle extras = new Bundle();
+ extras.putSerializable("Contact", contact);
+ changeCurrentFragment(FragmentsAvailable.CONTACT_EDITOR, extras);
+ }
+
+ public void editContact(LinphoneContact contact, String sipAddress) {
+ Bundle extras = new Bundle();
+ extras.putSerializable("Contact", contact);
+ extras.putSerializable("NewSipAdress", sipAddress);
+ changeCurrentFragment(FragmentsAvailable.CONTACT_EDITOR, extras);
+ }
+
+ public void quit() {
+ finish();
+ stopService(new Intent(Intent.ACTION_MAIN).setClass(this, LinphoneService.class));
+ ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
+ am.killBackgroundProcesses(getString(R.string.sync_account_type));
+ android.os.Process.killProcess(android.os.Process.myPid());
+ }
+
+ @Override
+ protected void onPostResume() {
+ super.onPostResume();
+ if (pendingFragmentTransaction != FragmentsAvailable.UNKNOW) {
+ changeCurrentFragment(pendingFragmentTransaction, null, true);
+ selectMenu(pendingFragmentTransaction);
+ pendingFragmentTransaction = FragmentsAvailable.UNKNOW;
+ }
+ }
+
+ @Override
+ protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+ if (getIntent() != null && getIntent().getExtras() != null) {
+ newProxyConfig = getIntent().getExtras().getBoolean("isNewProxyConfig");
+ }
+
+ if (resultCode == Activity.RESULT_FIRST_USER && requestCode == SETTINGS_ACTIVITY) {
+ if (data.getExtras().getBoolean("Exit", false)) {
+ quit();
+ } else {
+ pendingFragmentTransaction = (FragmentsAvailable) data.getExtras().getSerializable("FragmentToDisplay");
+ }
+ } else if (resultCode == Activity.RESULT_FIRST_USER && requestCode == CALL_ACTIVITY) {
+ getIntent().putExtra("PreviousActivity", CALL_ACTIVITY);
+ callTransfer = data != null && data.getBooleanExtra("Transfer", false);
+ boolean chat = data != null && data.getBooleanExtra("chat", false);
+ if (chat) {
+ pendingFragmentTransaction = FragmentsAvailable.CHAT_LIST;
+ }
+ if (LinphoneManager.getLc().getCallsNb() > 0) {
+ initInCallMenuLayout(callTransfer);
+ } else {
+ resetClassicMenuLayoutAndGoBackToCallIfStillRunning();
+ }
+ } else if (requestCode == PERMISSIONS_REQUEST_OVERLAY) {
+ if (Compatibility.canDrawOverlays(this)) {
+ LinphonePreferences.instance().enableOverlay(true);
+ }
+ } else {
+ super.onActivityResult(requestCode, resultCode, data);
+ }
+ }
+
+ @Override
+ protected void onPause() {
+ getIntent().putExtra("PreviousActivity", 0);
+
+ Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ if (lc != null) {
+ lc.removeListener(mListener);
+ }
+ callTransfer = false;
+ isOnBackground = true;
+
+ super.onPause();
+ }
+
+ public boolean checkAndRequestOverlayPermission() {
+ Log.i("[Permission] Draw overlays permission is " + (Compatibility.canDrawOverlays(this) ? "granted" : "denied"));
+ if (!Compatibility.canDrawOverlays(this)) {
+ Log.i("[Permission] Asking for overlay");
+ Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
+ startActivityForResult(intent, PERMISSIONS_REQUEST_OVERLAY);
+ return false;
+ }
+ return true;
+ }
+
+ public void checkAndRequestExternalStoragePermission() {
+ checkAndRequestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, 0);
+ }
+
+ public void checkAndRequestCameraPermission() {
+ checkAndRequestPermission(Manifest.permission.CAMERA, 0);
+ }
+
+ public void checkAndRequestWriteContactsPermission() {
+ checkAndRequestPermission(Manifest.permission.WRITE_CONTACTS, 0);
+ }
+
+ public void checkAndRequestRecordAudioPermissionForEchoCanceller() {
+ checkAndRequestPermission(Manifest.permission.RECORD_AUDIO, PERMISSIONS_RECORD_AUDIO_ECHO_CANCELLER);
+ }
+
+ public void checkAndRequestRecordAudioPermissionsForEchoTester() {
+ checkAndRequestPermission(Manifest.permission.RECORD_AUDIO, PERMISSIONS_RECORD_AUDIO_ECHO_TESTER);
+ }
+
+ public void checkAndRequestReadExternalStoragePermissionForDeviceRingtone() {
+ checkAndRequestPermission(Manifest.permission.READ_EXTERNAL_STORAGE, PERMISSIONS_READ_EXTERNAL_STORAGE_DEVICE_RINGTONE);
+ }
+
+ public void checkAndRequestPermissionsToSendImage() {
+ ArrayList permissionsList = new ArrayList();
+
+ int readExternalStorage = getPackageManager().checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE, getPackageName());
+ Log.i("[Permission] Read external storage permission is " + (readExternalStorage == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
+ int camera = getPackageManager().checkPermission(Manifest.permission.CAMERA, getPackageName());
+ Log.i("[Permission] Camera permission is " + (camera == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
+
+ if (readExternalStorage != PackageManager.PERMISSION_GRANTED) {
+ ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE);
+ Log.i("[Permission] Asking for read external storage");
+ permissionsList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
+ }
+ if (camera != PackageManager.PERMISSION_GRANTED) {
+ ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA);
+ Log.i("[Permission] Asking for camera");
+ permissionsList.add(Manifest.permission.CAMERA);
+ }
+ if (permissionsList.size() > 0) {
+ String[] permissions = new String[permissionsList.size()];
+ permissions = permissionsList.toArray(permissions);
+ ActivityCompat.requestPermissions(this, permissions, 0);
+ }
+ }
+
+ private void checkSyncPermission() {
+ checkAndRequestPermission(Manifest.permission.WRITE_SYNC_SETTINGS, PERMISSIONS_REQUEST_SYNC);
+ }
+
+ public void checkAndRequestPermission(String permission, int result) {
+ int permissionGranted = getPackageManager().checkPermission(permission, getPackageName());
+ Log.i("[Permission] " + permission + " is " + (permissionGranted == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
+
+ if (permissionGranted != PackageManager.PERMISSION_GRANTED) {
+ ActivityCompat.shouldShowRequestPermissionRationale(this, permission);
+ Log.i("[Permission] Asking for " + permission);
+ ActivityCompat.requestPermissions(this, new String[]{permission}, result);
+ }
+ }
+
+ @Override
+ public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
+ if (permissions.length <= 0)
+ return;
+
+ int readContactsI = -1;
+ for (int i = 0; i < permissions.length; i++) {
+ Log.i("[Permission] " + permissions[i] + " is " + (grantResults[i] == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
+ if (permissions[i].compareTo(Manifest.permission.READ_CONTACTS) == 0 ||
+ permissions[i].compareTo(Manifest.permission.WRITE_CONTACTS) == 0)
+ readContactsI = i;
+ }
+
+ switch (requestCode) {
+ case PERMISSIONS_REQUEST_SYNC:
+ if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
+ ContactsManager.getInstance().initializeSyncAccount(getApplicationContext(), getContentResolver());
+ } else {
+ ContactsManager.getInstance().initializeContactManager(getApplicationContext(), getContentResolver());
+ }
+ break;
+ case PERMISSIONS_RECORD_AUDIO_ECHO_CANCELLER:
+ if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
+ ((SettingsFragment) fragment).startEchoCancellerCalibration();
+ } else {
+ ((SettingsFragment) fragment).echoCalibrationFail();
+ }
+ break;
+ case PERMISSIONS_READ_EXTERNAL_STORAGE_DEVICE_RINGTONE:
+ if (permissions[0].compareTo(Manifest.permission.READ_EXTERNAL_STORAGE) != 0)
+ break;
+ boolean enableRingtone = (grantResults[0] == PackageManager.PERMISSION_GRANTED);
+ LinphonePreferences.instance().enableDeviceRingtone(enableRingtone);
+ LinphoneManager.getInstance().enableDeviceRingtone(enableRingtone);
+ break;
+ case PERMISSIONS_RECORD_AUDIO_ECHO_TESTER:
+ if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
+ ((SettingsFragment) fragment).startEchoTester();
+ break;
+ }
+ if (readContactsI >= 0 && grantResults[readContactsI] == PackageManager.PERMISSION_GRANTED) {
+ ContactsManager.getInstance().enableContactsAccess();
+ if (!ContactsManager.getInstance().contactsFetchedOnce()) {
+ ContactsManager.getInstance().enableContactsAccess();
+ ContactsManager.getInstance().fetchContactsAsync();
+ }
+ }
+ }
+
+ @Override
+ protected void onStart() {
+ super.onStart();
+ ArrayList permissionsList = new ArrayList();
+
+ int contacts = getPackageManager().checkPermission(Manifest.permission.READ_CONTACTS, getPackageName());
+ Log.i("[Permission] Contacts permission is " + (contacts == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
+
+ int readPhone = getPackageManager().checkPermission(Manifest.permission.READ_PHONE_STATE, getPackageName());
+ Log.i("[Permission] Read phone state permission is " + (readPhone == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
+
+ int ringtone = getPackageManager().checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE, getPackageName());
+ Log.i("[Permission] Read external storage for ring tone permission is " + (ringtone == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
+
+ if (ringtone != PackageManager.PERMISSION_GRANTED) {
+ if (LinphonePreferences.instance().firstTimeAskingForPermission(Manifest.permission.READ_EXTERNAL_STORAGE) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
+ Log.i("[Permission] Asking for read external storage for ring tone");
+ permissionsList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
+ }
+ }
+ if (readPhone != PackageManager.PERMISSION_GRANTED) {
+ if (LinphonePreferences.instance().firstTimeAskingForPermission(Manifest.permission.READ_PHONE_STATE) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_STATE)) {
+ Log.i("[Permission] Asking for read phone state");
+ permissionsList.add(Manifest.permission.READ_PHONE_STATE);
+ }
+ }
+ if (contacts != PackageManager.PERMISSION_GRANTED) {
+ if (LinphonePreferences.instance().firstTimeAskingForPermission(Manifest.permission.READ_CONTACTS) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_CONTACTS)) {
+ Log.i("[Permission] Asking for contacts");
+ permissionsList.add(Manifest.permission.READ_CONTACTS);
+ }
+ } else {
+ if (!ContactsManager.getInstance().contactsFetchedOnce()) {
+ ContactsManager.getInstance().enableContactsAccess();
+ ContactsManager.getInstance().fetchContactsAsync();
+ }
+ }
+
+ if (permissionsList.size() > 0) {
+ String[] permissions = new String[permissionsList.size()];
+ permissions = permissionsList.toArray(permissions);
+ ActivityCompat.requestPermissions(this, permissions, PERMISSIONS_READ_EXTERNAL_STORAGE_DEVICE_RINGTONE);
+ }
+ }
+
+ @Override
+ protected void onSaveInstanceState(Bundle outState) {
+ outState.putSerializable("currentFragment", currentFragment);
+ super.onSaveInstanceState(outState);
+ }
+
+ @Override
+ protected void onRestoreInstanceState(Bundle savedInstanceState) {
+ super.onRestoreInstanceState(savedInstanceState);
+ }
+
+ public void disableGoToCall() {
+ doNotGoToCallActivity = true;
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ if (!LinphoneService.isReady()) {
+ startService(new Intent(Intent.ACTION_MAIN).setClass(this, LinphoneService.class));
+ }
+
+ Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ if (lc != null) {
+ lc.addListener(mListener);
+ if (!LinphoneService.instance().displayServiceNotification()) {
+ lc.refreshRegisters();
+ }
+ }
+
+ if (isTablet()) {
+ // Prevent fragmentContainer2 to be visible when rotating the device
+ LinearLayout ll = (LinearLayout) findViewById(R.id.fragmentContainer2);
+ if (currentFragment == FragmentsAvailable.DIALER
+ || currentFragment == FragmentsAvailable.ABOUT
+ || currentFragment == FragmentsAvailable.SETTINGS
+ || currentFragment == FragmentsAvailable.ACCOUNT_SETTINGS) {
+ ll.setVisibility(View.GONE);
+ }
+ }
+
+ refreshAccounts();
+
+ if (getResources().getBoolean(R.bool.enable_in_app_purchase)) {
+ isTrialAccount();
+ }
+
+ displayMissedChats(LinphoneManager.getInstance().getUnreadMessageCount());
+ displayMissedCalls(LinphoneManager.getLc().getMissedCallsCount());
+
+ LinphoneManager.getInstance().changeStatusToOnline();
+
+ if (getIntent().getIntExtra("PreviousActivity", 0) != CALL_ACTIVITY && !doNotGoToCallActivity) {
+ if (LinphoneManager.getLc().getCalls().length > 0) {
+ Call call = LinphoneManager.getLc().getCalls()[0];
+ Call.State onCallStateChanged = call.getState();
+
+ if (onCallStateChanged == State.IncomingReceived) {
+ startActivity(new Intent(this, CallIncomingActivity.class));
+ } else if (onCallStateChanged == State.OutgoingInit || onCallStateChanged == State.OutgoingProgress || onCallStateChanged == State.OutgoingRinging) {
+ startActivity(new Intent(this, CallOutgoingActivity.class));
+ } else {
+ startIncallActivity(call);
+ }
+ }
+ }
+
+ Intent intent = getIntent();
+
+ if (intent.getStringExtra("msgShared") != null) {
+ displayChat(null, intent.getStringExtra("msgShared"), null);
+ intent.putExtra("msgShared", "");
+ }
+ if (intent.getStringExtra("fileShared") != null && intent.getStringExtra("fileShared") != "") {
+ displayChat(null, null, intent.getStringExtra("fileShared"));
+ intent.putExtra("fileShared", "");
+ }
+ doNotGoToCallActivity = false;
+ isOnBackground = false;
+
+ if (intent != null) {
+ Bundle extras = intent.getExtras();
+ if (extras != null && extras.containsKey("SipUriOrNumber")) {
+ mAddressWaitingToBeCalled = extras.getString("SipUriOrNumber");
+ intent.removeExtra("SipUriOrNumber");
+ goToDialerFragment();
+ }
+ }
+ }
+
+ @Override
+ protected void onDestroy() {
+ if (mOrientationHelper != null) {
+ mOrientationHelper.disable();
+ mOrientationHelper = null;
+ }
+
+ instance = null;
+ super.onDestroy();
+
+ unbindDrawables(findViewById(R.id.topLayout));
+ System.gc();
+ }
+
+ private void unbindDrawables(View view) {
+ if (view != null && view.getBackground() != null) {
+ view.getBackground().setCallback(null);
+ }
+ if (view instanceof ViewGroup && !(view instanceof AdapterView)) {
+ for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
+ unbindDrawables(((ViewGroup) view).getChildAt(i));
+ }
+ ((ViewGroup) view).removeAllViews();
+ }
+ }
+
+ @Override
+ protected void onNewIntent(Intent intent) {
+ super.onNewIntent(intent);
+ if (getCurrentFragment() == FragmentsAvailable.SETTINGS) {
+ if (fragment instanceof SettingsFragment) {
+ ((SettingsFragment) fragment).closePreferenceScreen();
+ }
+ }
+ Bundle extras = intent.getExtras();
+ if (extras != null && extras.getBoolean("GoToChat", false)) {
+ String sipUri = extras.getString("ChatContactSipUri");
+ doNotGoToCallActivity = true;
+ displayChat(sipUri, null, null);
+ } else if (extras != null && extras.getBoolean("GoToHistory", false)) {
+ doNotGoToCallActivity = true;
+ changeCurrentFragment(FragmentsAvailable.HISTORY_LIST, null);
+ } else if (extras != null && extras.getBoolean("GoToInapp", false)) {
+ doNotGoToCallActivity = true;
+ displayInapp();
+ } else if (extras != null && extras.getBoolean("Notification", false)) {
+ if (LinphoneManager.getLc().getCallsNb() > 0) {
+ Call call = LinphoneManager.getLc().getCalls()[0];
+ startIncallActivity(call);
+ }
+ } else if (extras != null && extras.getBoolean("StartCall", false)) {
+ boolean extraBool = extras.getBoolean("StartCall", false);
+ if (CallActivity.isInstanciated()) {
+ CallActivity.instance().startIncomingCallActivity();
+ } else {
+ mAddressWaitingToBeCalled = extras.getString("NumberToCall");
+ goToDialerFragment();
+ //startActivity(new Intent(this, CallIncomingActivity.class));
+ }
+ } else {
+ DialerFragment dialerFragment = DialerFragment.instance();
+ if (dialerFragment != null) {
+ if (extras != null && extras.containsKey("SipUriOrNumber")) {
+ if (getResources().getBoolean(R.bool.automatically_start_intercepted_outgoing_gsm_call)) {
+ ((DialerFragment) dialerFragment).newOutgoingCall(extras.getString("SipUriOrNumber"));
+ } else {
+ ((DialerFragment) dialerFragment).displayTextInAddressBar(extras.getString("SipUriOrNumber"));
+ }
+ } else {
+ ((DialerFragment) dialerFragment).newOutgoingCall(intent);
+ }
+ } else {
+ if (extras != null && extras.containsKey("SipUriOrNumber")) {
+ mAddressWaitingToBeCalled = extras.getString("SipUriOrNumber");
+ goToDialerFragment();
+ }
+ }
+ if (LinphoneManager.getLc().getCalls().length > 0) {
+ // If a call is ringing, start incomingcallactivity
+ Collection incoming = new ArrayList();
+ incoming.add(Call.State.IncomingReceived);
+ if (LinphoneUtils.getCallsInState(LinphoneManager.getLc(), incoming).size() > 0) {
+ if (CallActivity.isInstanciated()) {
+ CallActivity.instance().startIncomingCallActivity();
+ } else {
+ startActivity(new Intent(this, CallIncomingActivity.class));
+ }
+ }
+ }
+ }
+ }
+
+ public boolean isOnBackground() {
+ return isOnBackground;
+ }
+
+ public boolean onKeyDown(int keyCode, KeyEvent event) {
+ if (keyCode == KeyEvent.KEYCODE_BACK) {
+ switch (currentFragment) {
+ case DIALER:
+ case CONTACTS_LIST:
+ case HISTORY_LIST:
+ case CHAT_LIST:
+ boolean isBackgroundModeActive = LinphonePreferences.instance().isBackgroundModeEnabled();
+ if (!isBackgroundModeActive) {
+ stopService(new Intent(Intent.ACTION_MAIN).setClass(this, LinphoneService.class));
+ finish();
+ } else if (LinphoneUtils.onKeyBackGoHome(this, keyCode, event)) {
+ return true;
+ }
+ break;
+ case GROUP_CHAT:
+ LinphoneActivity.instance().goToChatList();
+ return true;
+ default:
+ break;
+ }
+ }
+ return super.onKeyDown(keyCode, event);
+ }
+
+ //SIDE MENU
+ public void openOrCloseSideMenu(boolean open) {
+ if (open) {
+ sideMenu.openDrawer(sideMenuContent);
+ } else {
+ sideMenu.closeDrawer(sideMenuContent);
+ }
+ }
+
+ public void initSideMenu() {
+ sideMenu = (DrawerLayout) findViewById(R.id.side_menu);
+ sideMenuItems = new ArrayList();
+ sideMenuItems.add(getResources().getString(R.string.menu_assistant));
+ sideMenuItems.add(getResources().getString(R.string.menu_settings));
+ if (getResources().getBoolean(R.bool.enable_in_app_purchase)) {
+ sideMenuItems.add(getResources().getString(R.string.inapp));
+ }
+ sideMenuItems.add(getResources().getString(R.string.menu_about));
+ sideMenuContent = (RelativeLayout) findViewById(R.id.side_menu_content);
+ sideMenuItemList = (ListView) findViewById(R.id.item_list);
+ menu = (ImageView) findViewById(R.id.side_menu_button);
+
+ sideMenuItemList.setAdapter(new ArrayAdapter(this, R.layout.side_menu_item_cell, sideMenuItems));
+ sideMenuItemList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
+ @Override
+ public void onItemClick(AdapterView> adapterView, View view, int i, long l) {
+ if (sideMenuItemList.getAdapter().getItem(i).toString().equals(getString(R.string.menu_settings))) {
+ LinphoneActivity.instance().displaySettings();
+ }
+ if (sideMenuItemList.getAdapter().getItem(i).toString().equals(getString(R.string.menu_about))) {
+ LinphoneActivity.instance().displayAbout();
+ }
+ if (sideMenuItemList.getAdapter().getItem(i).toString().equals(getString(R.string.menu_assistant))) {
+ LinphoneActivity.instance().displayAssistant();
+ }
+ if (getResources().getBoolean(R.bool.enable_in_app_purchase)) {
+ if (sideMenuItemList.getAdapter().getItem(i).toString().equals(getString(R.string.inapp))) {
+ LinphoneActivity.instance().displayInapp();
+ }
+ }
+ openOrCloseSideMenu(false);
+ }
+ });
+
+ initAccounts();
+
+ menu.setOnClickListener(new OnClickListener() {
+ @Override
+ public void onClick(View view) {
+
+ if (sideMenu.isDrawerVisible(Gravity.LEFT)) {
+ sideMenu.closeDrawer(sideMenuContent);
+ } else {
+ sideMenu.openDrawer(sideMenuContent);
+ }
+ }
+ });
+
+ quitLayout = (RelativeLayout) findViewById(R.id.side_menu_quit);
+ quitLayout.setOnClickListener(new OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ LinphoneActivity.instance().quit();
+ }
+ });
+ }
+
+ private int getStatusIconResource(RegistrationState state) {
+ try {
+ if (state == RegistrationState.Ok) {
+ return R.drawable.led_connected;
+ } else if (state == RegistrationState.Progress) {
+ return R.drawable.led_inprogress;
+ } else if (state == RegistrationState.Failed) {
+ return R.drawable.led_error;
+ } else {
+ return R.drawable.led_disconnected;
+ }
+ } catch (Exception e) {
+ Log.e(e);
+ }
+
+ return R.drawable.led_disconnected;
+ }
+
+ private void displayMainAccount() {
+ defaultAccount.setVisibility(View.VISIBLE);
+ ImageView status = (ImageView) defaultAccount.findViewById(R.id.main_account_status);
+ TextView address = (TextView) defaultAccount.findViewById(R.id.main_account_address);
+ TextView displayName = (TextView) defaultAccount.findViewById(R.id.main_account_display_name);
+
+
+ ProxyConfig proxy = LinphoneManager.getLc().getDefaultProxyConfig();
+ if (proxy == null) {
+ displayName.setText(getString(R.string.no_account));
+ status.setVisibility(View.GONE);
+ address.setText("");
+ statusFragment.resetAccountStatus();
+ LinphoneManager.getInstance().subscribeFriendList(false);
+
+ defaultAccount.setOnClickListener(null);
+ } else {
+ address.setText(proxy.getIdentityAddress().asStringUriOnly());
+ displayName.setText(LinphoneUtils.getAddressDisplayName(proxy.getIdentityAddress()));
+ status.setImageResource(getStatusIconResource(proxy.getState()));
+ status.setVisibility(View.VISIBLE);
+
+ defaultAccount.setOnClickListener(new OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ LinphoneActivity.instance().displayAccountSettings(LinphonePreferences.instance().getDefaultAccountIndex());
+ openOrCloseSideMenu(false);
+ }
+ });
+ }
+ }
+
+ public void refreshAccounts() {
+ if (LinphoneManager.getLc().getProxyConfigList() != null &&
+ LinphoneManager.getLc().getProxyConfigList().length > 1) {
+ accountsList.setVisibility(View.VISIBLE);
+ accountsList.setAdapter(new AccountsListAdapter());
+ accountsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
+ @Override
+ public void onItemClick(AdapterView> adapterView, View view, int i, long l) {
+ if (view != null && view.getTag() != null) {
+ int position = Integer.parseInt(view.getTag().toString());
+ LinphoneActivity.instance().displayAccountSettings(position);
+ }
+ openOrCloseSideMenu(false);
+ }
+ });
+ } else {
+ accountsList.setVisibility(View.GONE);
+ }
+ displayMainAccount();
+ }
+
+ private void initAccounts() {
+ accountsList = (ListView) findViewById(R.id.accounts_list);
+ defaultAccount = (RelativeLayout) findViewById(R.id.default_account);
+ }
+
+ class AccountsListAdapter extends BaseAdapter {
+ List proxy_list;
+
+ AccountsListAdapter() {
+ proxy_list = new ArrayList();
+ refresh();
+ }
+
+ public void refresh() {
+ proxy_list = new ArrayList();
+ for (ProxyConfig proxyConfig : LinphoneManager.getLc().getProxyConfigList()) {
+ if (proxyConfig != LinphoneManager.getLc().getDefaultProxyConfig()) {
+ proxy_list.add(proxyConfig);
+ }
+ }
+ }
+
+ public int getCount() {
+ if (proxy_list != null) {
+ return proxy_list.size();
+ } else {
+ return 0;
+ }
+ }
+
+ public Object getItem(int position) {
+ return proxy_list.get(position);
+ }
+
+ public long getItemId(int position) {
+ return position;
+ }
+
+ public View getView(final int position, View convertView, ViewGroup parent) {
+ View view = null;
+ ProxyConfig lpc = (ProxyConfig) getItem(position);
+ if (convertView != null) {
+ view = convertView;
+ } else {
+ view = getLayoutInflater().inflate(R.layout.side_menu_account_cell, parent, false);
+ }
+
+ ImageView status = (ImageView) view.findViewById(R.id.account_status);
+ TextView address = (TextView) view.findViewById(R.id.account_address);
+ String sipAddress = lpc.getIdentityAddress().asStringUriOnly();
+
+ address.setText(sipAddress);
+
+ int nbAccounts = LinphonePreferences.instance().getAccountCount();
+ int accountIndex = 0;
+
+ for (int i = 0; i < nbAccounts; i++) {
+ String username = LinphonePreferences.instance().getAccountUsername(i);
+ String domain = LinphonePreferences.instance().getAccountDomain(i);
+ String id = "sip:" + username + "@" + domain;
+ if (id.equals(sipAddress)) {
+ accountIndex = i;
+ view.setTag(accountIndex);
+ break;
+ }
+ }
+ status.setImageResource(getStatusIconResource(lpc.getState()));
+ return view;
+ }
+ }
+
+ //Inapp Purchase
+ private void isTrialAccount() {
+ if (LinphoneManager.getLc().getDefaultProxyConfig() != null && LinphonePreferences.instance().getInappPopupTime() != null) {
+ XmlRpcHelper helper = new XmlRpcHelper();
+ helper.isTrialAccountAsync(new XmlRpcListenerBase() {
+ @Override
+ public void onTrialAccountFetched(boolean isTrial) {
+ isTrialAccount = isTrial;
+ getExpirationAccount();
+ }
+
+ @Override
+ public void onError(String error) {
+ }
+ }, LinphonePreferences.instance().getAccountUsername(LinphonePreferences.instance().getDefaultAccountIndex()), LinphonePreferences.instance().getAccountHa1(LinphonePreferences.instance().getDefaultAccountIndex()));
+ }
+ }
+
+ private void getExpirationAccount() {
+ if (LinphoneManager.getLc().getDefaultProxyConfig() != null && LinphonePreferences.instance().getInappPopupTime() != null) {
+ XmlRpcHelper helper = new XmlRpcHelper();
+ helper.getAccountExpireAsync(new XmlRpcListenerBase() {
+ @Override
+ public void onAccountExpireFetched(String result) {
+ if (result != null) {
+ long timestamp = Long.parseLong(result);
+
+ Calendar calresult = Calendar.getInstance();
+ calresult.setTimeInMillis(timestamp);
+
+ int diff = getDiffDays(calresult, Calendar.getInstance());
+ if (diff != -1 && diff <= getResources().getInteger(R.integer.days_notification_shown)) {
+ displayInappNotification(timestampToHumanDate(calresult));
+ }
+ }
+ }
+
+ @Override
+ public void onError(String error) {
+ }
+ }, LinphonePreferences.instance().getAccountUsername(LinphonePreferences.instance().getDefaultAccountIndex()), LinphonePreferences.instance().getAccountHa1(LinphonePreferences.instance().getDefaultAccountIndex()));
+ }
+ }
+
+ public void displayInappNotification(String date) {
+ Timestamp now = new Timestamp(new Date().getTime());
+ if (LinphonePreferences.instance().getInappPopupTime() != null && Long.parseLong(LinphonePreferences.instance().getInappPopupTime()) > now.getTime()) {
+ return;
+ } else {
+ long newDate = now.getTime() + getResources().getInteger(R.integer.time_between_inapp_notification);
+ LinphonePreferences.instance().setInappPopupTime(String.valueOf(newDate));
+ }
+ if (isTrialAccount) {
+ LinphoneService.instance().displayInappNotification(String.format(getString(R.string.inapp_notification_trial_expire), date));
+ } else {
+ LinphoneService.instance().displayInappNotification(String.format(getString(R.string.inapp_notification_account_expire), date));
+ }
+
+ }
+
+ private String timestampToHumanDate(Calendar cal) {
+ SimpleDateFormat dateFormat;
+ dateFormat = new SimpleDateFormat(getResources().getString(R.string.inapp_popup_date_format));
+ return dateFormat.format(cal.getTime());
+ }
+
+ private int getDiffDays(Calendar cal1, Calendar cal2) {
+ if (cal1 == null || cal2 == null) {
+ return -1;
+ }
+ if (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)) {
+ return cal1.get(Calendar.DAY_OF_YEAR) - cal2.get(Calendar.DAY_OF_YEAR);
+ }
+ return -1;
+ }
}
diff --git a/src/android/org/linphone/activities/LinphoneGenericActivity.java b/src/android/org/linphone/activities/LinphoneGenericActivity.java
index b456a831f..a059fae40 100644
--- a/src/android/org/linphone/activities/LinphoneGenericActivity.java
+++ b/src/android/org/linphone/activities/LinphoneGenericActivity.java
@@ -32,8 +32,8 @@ public class LinphoneGenericActivity extends Activity {
super.onCreate(savedInstanceState);
/*After a crash, Android restart the last Activity so we need to check
- * if all dependencies are load
- */
+ * if all dependencies are load
+ */
if (!LinphoneService.isReady()) {
finish();
startService(getIntent().setClass(this, LinphoneService.class));
diff --git a/src/android/org/linphone/activities/LinphoneLauncherActivity.java b/src/android/org/linphone/activities/LinphoneLauncherActivity.java
index 0eb500607..69ba51db6 100644
--- a/src/android/org/linphone/activities/LinphoneLauncherActivity.java
+++ b/src/android/org/linphone/activities/LinphoneLauncherActivity.java
@@ -27,8 +27,6 @@ import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
-import org.linphone.receivers.BluetoothManager;
-import org.linphone.contacts.ContactsManager;
import org.linphone.LinphoneManager;
import org.linphone.LinphonePreferences;
import org.linphone.LinphoneService;
@@ -36,7 +34,9 @@ import org.linphone.LinphoneUtils;
import org.linphone.R;
import org.linphone.assistant.RemoteProvisioningActivity;
import org.linphone.call.CallActivity;
+import org.linphone.contacts.ContactsManager;
import org.linphone.mediastream.Version;
+import org.linphone.receivers.BluetoothManager;
import static android.content.Intent.ACTION_MAIN;
@@ -45,158 +45,157 @@ import static android.content.Intent.ACTION_MAIN;
*/
public class LinphoneLauncherActivity extends Activity {
- private final String ACTION_CALL_LINPHONE = "org.linphone.intent.action.CallLaunched";
+ private final String ACTION_CALL_LINPHONE = "org.linphone.intent.action.CallLaunched";
- private Handler mHandler;
- private ServiceWaitThread mServiceThread;
- private String addressToCall;
- private Uri uriToResolve;
+ private Handler mHandler;
+ private ServiceWaitThread mServiceThread;
+ private String addressToCall;
+ private Uri uriToResolve;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- // Hack to avoid to draw twice LinphoneActivity on tablets
- if (getResources().getBoolean(R.bool.orientation_portrait_only)) {
- setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
- }
- setContentView(R.layout.launch_screen);
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ // Hack to avoid to draw twice LinphoneActivity on tablets
+ if (getResources().getBoolean(R.bool.orientation_portrait_only)) {
+ setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
+ }
+ setContentView(R.layout.launch_screen);
- mHandler = new Handler();
+ mHandler = new Handler();
- Intent intent = getIntent();
- if (intent != null) {
- String action = intent.getAction();
- if (Intent.ACTION_CALL.equals(action)) {
- if (intent.getData() != null) {
- addressToCall = intent.getData().toString();
- addressToCall = addressToCall.replace("%40", "@");
- addressToCall = addressToCall.replace("%3A", ":");
- if (addressToCall.startsWith("sip:")) {
- addressToCall = addressToCall.substring("sip:".length());
- }
- }
- } else if (Intent.ACTION_VIEW.equals(action)) {
- if (LinphoneService.isReady()) {
- addressToCall = ContactsManager.getInstance().getAddressOrNumberForAndroidContact(getContentResolver(), intent.getData());
- } else {
- uriToResolve = intent.getData();
- }
- }
- }
+ Intent intent = getIntent();
+ if (intent != null) {
+ String action = intent.getAction();
+ if (Intent.ACTION_CALL.equals(action)) {
+ if (intent.getData() != null) {
+ addressToCall = intent.getData().toString();
+ addressToCall = addressToCall.replace("%40", "@");
+ addressToCall = addressToCall.replace("%3A", ":");
+ if (addressToCall.startsWith("sip:")) {
+ addressToCall = addressToCall.substring("sip:".length());
+ }
+ }
+ } else if (Intent.ACTION_VIEW.equals(action)) {
+ if (LinphoneService.isReady()) {
+ addressToCall = ContactsManager.getInstance().getAddressOrNumberForAndroidContact(getContentResolver(), intent.getData());
+ } else {
+ uriToResolve = intent.getData();
+ }
+ }
+ }
- if (LinphoneService.isReady()) {
- onServiceReady();
- } else {
- // start linphone as background
- startService(new Intent(ACTION_MAIN).setClass(this, LinphoneService.class));
- mServiceThread = new ServiceWaitThread();
- mServiceThread.start();
- }
- }
+ if (LinphoneService.isReady()) {
+ onServiceReady();
+ } else {
+ // start linphone as background
+ startService(new Intent(ACTION_MAIN).setClass(this, LinphoneService.class));
+ mServiceThread = new ServiceWaitThread();
+ mServiceThread.start();
+ }
+ }
- @Override
- protected void onResume(){
- super.onResume();
- }
+ @Override
+ protected void onResume() {
+ super.onResume();
+ }
- @Override
- protected void onNewIntent(Intent intent) {
- super.onNewIntent(intent);
- }
+ @Override
+ protected void onNewIntent(Intent intent) {
+ super.onNewIntent(intent);
+ }
- protected void onServiceReady() {
- final Class extends Activity> classToStart;
+ protected void onServiceReady() {
+ final Class extends Activity> classToStart;
/*if (getResources().getBoolean(R.bool.show_tutorials_instead_of_app)) {
classToStart = TutorialLauncherActivity.class;
- } else */if (getResources().getBoolean(R.bool.display_sms_remote_provisioning_activity) && LinphonePreferences.instance().isFirstRemoteProvisioning()) {
- classToStart = RemoteProvisioningActivity.class;
- } else {
- classToStart = LinphoneActivity.class;
- }
+ } else */
+ if (getResources().getBoolean(R.bool.display_sms_remote_provisioning_activity) && LinphonePreferences.instance().isFirstRemoteProvisioning()) {
+ classToStart = RemoteProvisioningActivity.class;
+ } else {
+ classToStart = LinphoneActivity.class;
+ }
- // We need LinphoneService to start bluetoothManager
- if (Version.sdkAboveOrEqual(Version.API11_HONEYCOMB_30)) {
- BluetoothManager.getInstance().initBluetooth();
- }
+ // We need LinphoneService to start bluetoothManager
+ if (Version.sdkAboveOrEqual(Version.API11_HONEYCOMB_30)) {
+ BluetoothManager.getInstance().initBluetooth();
+ }
- mHandler.postDelayed(new Runnable() {
- @Override
- public void run() {
- Intent newIntent = new Intent(LinphoneLauncherActivity.this, classToStart);
- Intent intent = getIntent();
+ mHandler.postDelayed(new Runnable() {
+ @Override
+ public void run() {
+ Intent newIntent = new Intent(LinphoneLauncherActivity.this, classToStart);
+ Intent intent = getIntent();
String stringFileShared = null;
- String stringUriFileShared = null;
- Uri fileUri = null;
- if (intent != null) {
- String action = intent.getAction();
- String type = intent.getType();
- newIntent.setData(intent.getData());
- if (Intent.ACTION_SEND.equals(action) && type != null) {
- if(("text/plain").equals(type) && (String)intent.getStringExtra(Intent.EXTRA_TEXT)!= null) {
- stringFileShared = intent.getStringExtra(Intent.EXTRA_TEXT);
- newIntent.putExtra("msgShared", stringFileShared);
- } else {
- fileUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
- stringUriFileShared = LinphoneUtils.getFilePath(getBaseContext(), fileUri);
- newIntent.putExtra("fileShared", stringUriFileShared);
- }
- }else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) {
- if (type.startsWith("image/")) {
- //TODO : Manage multiple files sharing
- }
- }else if( ACTION_CALL_LINPHONE.equals(action) && (intent.getStringExtra("NumberToCall") != null)) {
- String numberToCall = intent.getStringExtra("NumberToCall");
- if (CallActivity.isInstanciated()) {
- CallActivity.instance().startIncomingCallActivity();
- } else {
- LinphoneManager.getInstance().newOutgoingCall(numberToCall, null);
- }
- }
- }
- if (uriToResolve != null) {
- addressToCall = ContactsManager.getInstance().getAddressOrNumberForAndroidContact(getContentResolver(), uriToResolve);
- Log.i("LinphoneLauncher", "Intent has uri to resolve : " + uriToResolve.toString());
- uriToResolve = null;
- }
- if (addressToCall != null) {
- newIntent.putExtra("SipUriOrNumber", addressToCall);
- Log.i("LinphoneLauncher", "Intent has address to call : " + addressToCall);
- addressToCall = null;
- }
- startActivity(newIntent);
- if (classToStart == LinphoneActivity.class && LinphoneActivity.isInstanciated() && (stringFileShared != null || fileUri != null)) {
- if(stringFileShared != null) {
- LinphoneActivity.instance().displayChat(null, stringFileShared, null);
- }
- else if(fileUri != null) {
- LinphoneActivity.instance().displayChat(null, null, stringUriFileShared);
- }
+ String stringUriFileShared = null;
+ Uri fileUri = null;
+ if (intent != null) {
+ String action = intent.getAction();
+ String type = intent.getType();
+ newIntent.setData(intent.getData());
+ if (Intent.ACTION_SEND.equals(action) && type != null) {
+ if (("text/plain").equals(type) && (String) intent.getStringExtra(Intent.EXTRA_TEXT) != null) {
+ stringFileShared = intent.getStringExtra(Intent.EXTRA_TEXT);
+ newIntent.putExtra("msgShared", stringFileShared);
+ } else {
+ fileUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
+ stringUriFileShared = LinphoneUtils.getFilePath(getBaseContext(), fileUri);
+ newIntent.putExtra("fileShared", stringUriFileShared);
+ }
+ } else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) {
+ if (type.startsWith("image/")) {
+ //TODO : Manage multiple files sharing
+ }
+ } else if (ACTION_CALL_LINPHONE.equals(action) && (intent.getStringExtra("NumberToCall") != null)) {
+ String numberToCall = intent.getStringExtra("NumberToCall");
+ if (CallActivity.isInstanciated()) {
+ CallActivity.instance().startIncomingCallActivity();
+ } else {
+ LinphoneManager.getInstance().newOutgoingCall(numberToCall, null);
+ }
+ }
}
- finish();
- }
- }, 1000);
- }
+ if (uriToResolve != null) {
+ addressToCall = ContactsManager.getInstance().getAddressOrNumberForAndroidContact(getContentResolver(), uriToResolve);
+ Log.i("LinphoneLauncher", "Intent has uri to resolve : " + uriToResolve.toString());
+ uriToResolve = null;
+ }
+ if (addressToCall != null) {
+ newIntent.putExtra("SipUriOrNumber", addressToCall);
+ Log.i("LinphoneLauncher", "Intent has address to call : " + addressToCall);
+ addressToCall = null;
+ }
+ startActivity(newIntent);
+ if (classToStart == LinphoneActivity.class && LinphoneActivity.isInstanciated() && (stringFileShared != null || fileUri != null)) {
+ if (stringFileShared != null) {
+ LinphoneActivity.instance().displayChat(null, stringFileShared, null);
+ } else if (fileUri != null) {
+ LinphoneActivity.instance().displayChat(null, null, stringUriFileShared);
+ }
+ }
+ finish();
+ }
+ }, 1000);
+ }
-
- private class ServiceWaitThread extends Thread {
- public void run() {
- while (!LinphoneService.isReady()) {
- try {
- sleep(30);
- } catch (InterruptedException e) {
- throw new RuntimeException("waiting thread sleep() has been interrupted");
- }
- }
- mHandler.post(new Runnable() {
- @Override
- public void run() {
- onServiceReady();
- }
- });
- mServiceThread = null;
- }
- }
+ private class ServiceWaitThread extends Thread {
+ public void run() {
+ while (!LinphoneService.isReady()) {
+ try {
+ sleep(30);
+ } catch (InterruptedException e) {
+ throw new RuntimeException("waiting thread sleep() has been interrupted");
+ }
+ }
+ mHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ onServiceReady();
+ }
+ });
+ mServiceThread = null;
+ }
+ }
}
diff --git a/src/android/org/linphone/assistant/AssistantActivity.java b/src/android/org/linphone/assistant/AssistantActivity.java
index c95d8a9c2..8355a9105 100644
--- a/src/android/org/linphone/assistant/AssistantActivity.java
+++ b/src/android/org/linphone/assistant/AssistantActivity.java
@@ -18,37 +18,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.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.linphone.contacts.ContactsManager;
-import org.linphone.activities.LinphoneActivity;
-import org.linphone.activities.LinphoneLauncherActivity;
-import org.linphone.LinphoneManager;
-import org.linphone.LinphonePreferences;
-import org.linphone.LinphonePreferences.AccountBuilder;
-import org.linphone.LinphoneService;
-import org.linphone.LinphoneUtils;
-import org.linphone.R;
-import org.linphone.fragments.StatusFragment;
-import org.linphone.core.AccountCreatorListener;
-import org.linphone.core.DialPlan;
-import org.linphone.core.AccountCreator;
-import org.linphone.core.Address;
-import org.linphone.core.TransportType;
-import org.linphone.core.AuthInfo;
-import org.linphone.core.ConfiguringState;
-import org.linphone.core.Core;
-import org.linphone.core.RegistrationState;
-import org.linphone.core.CoreException;
-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.core.tools.OpenH264DownloadHelper;
-
import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
@@ -83,781 +52,812 @@ import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
+import org.linphone.LinphoneManager;
+import org.linphone.LinphonePreferences;
+import org.linphone.LinphonePreferences.AccountBuilder;
+import org.linphone.LinphoneService;
+import org.linphone.LinphoneUtils;
+import org.linphone.R;
+import org.linphone.activities.LinphoneActivity;
+import org.linphone.activities.LinphoneLauncherActivity;
+import org.linphone.contacts.ContactsManager;
+import org.linphone.core.AccountCreator;
+import org.linphone.core.AccountCreatorListener;
+import org.linphone.core.Address;
+import org.linphone.core.AuthInfo;
+import org.linphone.core.ConfiguringState;
+import org.linphone.core.Core;
+import org.linphone.core.CoreException;
+import org.linphone.core.CoreListenerStub;
+import org.linphone.core.DialPlan;
+import org.linphone.core.Factory;
+import org.linphone.core.ProxyConfig;
+import org.linphone.core.RegistrationState;
+import org.linphone.core.TransportType;
+import org.linphone.core.tools.OpenH264DownloadHelper;
+import org.linphone.fragments.StatusFragment;
+import org.linphone.mediastream.Log;
+import org.linphone.mediastream.Version;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
public class AssistantActivity extends Activity implements OnClickListener, ActivityCompat.OnRequestPermissionsResultCallback, AccountCreatorListener {
-private static AssistantActivity instance;
- private ImageView back, cancel;
- private AssistantFragmentsEnum currentFragment;
- private AssistantFragmentsEnum lastFragment;
- private AssistantFragmentsEnum firstFragment;
- private Fragment fragment;
- private LinphonePreferences mPrefs;
- private boolean accountCreated = false, newAccount = false, isLink = false, fromPref = false;
- private CoreListenerStub mListener;
- private Address address;
- private StatusFragment status;
- private ProgressDialog progress;
- private Dialog dialog;
- private boolean remoteProvisioningInProgress;
- private boolean echoCancellerAlreadyDone;
- private static final int PERMISSIONS_REQUEST_RECORD_AUDIO = 201;
- private AccountCreator mAccountCreator;
- private CountryListAdapter countryListAdapter;
+ private static AssistantActivity instance;
+ private ImageView back, cancel;
+ private AssistantFragmentsEnum currentFragment;
+ private AssistantFragmentsEnum lastFragment;
+ private AssistantFragmentsEnum firstFragment;
+ private Fragment fragment;
+ private LinphonePreferences mPrefs;
+ private boolean accountCreated = false, newAccount = false, isLink = false, fromPref = false;
+ private CoreListenerStub mListener;
+ private Address address;
+ private StatusFragment status;
+ private ProgressDialog progress;
+ private Dialog dialog;
+ private boolean remoteProvisioningInProgress;
+ private boolean echoCancellerAlreadyDone;
+ private static final int PERMISSIONS_REQUEST_RECORD_AUDIO = 201;
+ private AccountCreator mAccountCreator;
+ private CountryListAdapter countryListAdapter;
- public DialPlan country;
- public String phone_number;
- public String email;
+ public DialPlan country;
+ public String phone_number;
+ public String email;
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
- if (getResources().getBoolean(R.bool.orientation_portrait_only)) {
- setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
- }
+ if (getResources().getBoolean(R.bool.orientation_portrait_only)) {
+ setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
+ }
- setContentView(R.layout.assistant);
- initUI();
+ setContentView(R.layout.assistant);
+ initUI();
- if (getIntent().getBooleanExtra("LinkPhoneNumber",false)) {
- isLink = true;
- if (getIntent().getBooleanExtra("FromPref",false))
- fromPref = true;
- displayCreateAccount();
- } else {
- firstFragment = getResources().getBoolean(R.bool.assistant_use_linphone_login_as_first_fragment) ? AssistantFragmentsEnum.LINPHONE_LOGIN : AssistantFragmentsEnum.WELCOME;
- if (findViewById(R.id.fragment_container) != null) {
- if (savedInstanceState == null) {
- display(firstFragment);
- } else {
- currentFragment = (AssistantFragmentsEnum) savedInstanceState.getSerializable("CurrentFragment");
- }
- }
- }
- if (savedInstanceState != null && savedInstanceState.containsKey("echoCanceller")) {
- echoCancellerAlreadyDone = savedInstanceState.getBoolean("echoCanceller");
- } else {
- echoCancellerAlreadyDone = false;
- }
+ if (getIntent().getBooleanExtra("LinkPhoneNumber", false)) {
+ isLink = true;
+ if (getIntent().getBooleanExtra("FromPref", false))
+ fromPref = true;
+ displayCreateAccount();
+ } else {
+ firstFragment = getResources().getBoolean(R.bool.assistant_use_linphone_login_as_first_fragment) ? AssistantFragmentsEnum.LINPHONE_LOGIN : AssistantFragmentsEnum.WELCOME;
+ if (findViewById(R.id.fragment_container) != null) {
+ if (savedInstanceState == null) {
+ display(firstFragment);
+ } else {
+ currentFragment = (AssistantFragmentsEnum) savedInstanceState.getSerializable("CurrentFragment");
+ }
+ }
+ }
+ if (savedInstanceState != null && savedInstanceState.containsKey("echoCanceller")) {
+ echoCancellerAlreadyDone = savedInstanceState.getBoolean("echoCanceller");
+ } else {
+ echoCancellerAlreadyDone = false;
+ }
mPrefs = LinphonePreferences.instance();
- status.enableSideMenu(false);
+ status.enableSideMenu(false);
- if (LinphoneManager.getLcIfManagerNotDestroyedOrNull() != null) {
- mAccountCreator = LinphoneManager.getLc().createAccountCreator(LinphonePreferences.instance().getXmlrpcUrl());
- mAccountCreator.setListener(this);
- }
+ if (LinphoneManager.getLcIfManagerNotDestroyedOrNull() != null) {
+ mAccountCreator = LinphoneManager.getLc().createAccountCreator(LinphonePreferences.instance().getXmlrpcUrl());
+ mAccountCreator.setListener(this);
+ }
- countryListAdapter = new CountryListAdapter(getApplicationContext());
+ countryListAdapter = new CountryListAdapter(getApplicationContext());
mListener = new CoreListenerStub() {
- @Override
- public void onConfiguringStatus(Core lc, final ConfiguringState state, String message) {
- if (progress != null) progress.dismiss();
- if (state == ConfiguringState.Successful) {
- goToLinphoneActivity();
- } else if (state == ConfiguringState.Failed) {
- Toast.makeText(AssistantActivity.instance(), getString(R.string.remote_provisioning_failure), Toast.LENGTH_LONG).show();
- }
- }
+ @Override
+ public void onConfiguringStatus(Core lc, final ConfiguringState state, String message) {
+ if (progress != null) progress.dismiss();
+ if (state == ConfiguringState.Successful) {
+ goToLinphoneActivity();
+ } else if (state == ConfiguringState.Failed) {
+ Toast.makeText(AssistantActivity.instance(), getString(R.string.remote_provisioning_failure), Toast.LENGTH_LONG).show();
+ }
+ }
- @Override
- public void onRegistrationStateChanged(Core lc, ProxyConfig cfg, RegistrationState state, String smessage) {
- if (remoteProvisioningInProgress) {
- if (progress != null) progress.dismiss();
- if (state == RegistrationState.Ok) {
- remoteProvisioningInProgress = false;
- success();
- }
- } else if (accountCreated && !newAccount){
- if (address != null && address.asString().equals(cfg.getIdentityAddress().asString()) ) {
- if (state == RegistrationState.Ok) {
- if (progress != null) progress.dismiss();
- if (getResources().getBoolean(R.bool.use_phone_number_validation)
- && cfg.getDomain().equals(getString(R.string.default_domain))
- && LinphoneManager.getLc().getDefaultProxyConfig() != null) {
- loadAccountCreator(cfg).isAccountExist();
- } else {
- success();
- }
- } else if (state == RegistrationState.Failed) {
- if (progress != null) progress.dismiss();
- if (dialog == null || !dialog.isShowing()) {
- dialog = createErrorDialog(cfg, smessage);
- dialog.setCancelable(false);
- dialog.show();
- }
- } else if(!(state == RegistrationState.Progress)) {
- if (progress != null) progress.dismiss();
- }
- }
- }
- }
+ @Override
+ public void onRegistrationStateChanged(Core lc, ProxyConfig cfg, RegistrationState state, String smessage) {
+ if (remoteProvisioningInProgress) {
+ if (progress != null) progress.dismiss();
+ if (state == RegistrationState.Ok) {
+ remoteProvisioningInProgress = false;
+ success();
+ }
+ } else if (accountCreated && !newAccount) {
+ if (address != null && address.asString().equals(cfg.getIdentityAddress().asString())) {
+ if (state == RegistrationState.Ok) {
+ if (progress != null) progress.dismiss();
+ if (getResources().getBoolean(R.bool.use_phone_number_validation)
+ && cfg.getDomain().equals(getString(R.string.default_domain))
+ && LinphoneManager.getLc().getDefaultProxyConfig() != null) {
+ loadAccountCreator(cfg).isAccountExist();
+ } else {
+ success();
+ }
+ } else if (state == RegistrationState.Failed) {
+ if (progress != null) progress.dismiss();
+ if (dialog == null || !dialog.isShowing()) {
+ dialog = createErrorDialog(cfg, smessage);
+ dialog.setCancelable(false);
+ dialog.show();
+ }
+ } else if (!(state == RegistrationState.Progress)) {
+ if (progress != null) progress.dismiss();
+ }
+ }
+ }
+ }
};
instance = this;
- }
-
- @Override
- protected void onResume() {
- super.onResume();
-
- Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- if (lc != null) {
- lc.addListener(mListener);
- }
- }
-
- @Override
- protected void onPause() {
- Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- if (lc != null) {
- lc.removeListener(mListener);
- }
-
- super.onPause();
- }
-
- @Override
- protected void onSaveInstanceState(Bundle outState) {
- outState.putSerializable("CurrentFragment", currentFragment);
- outState.putBoolean("echoCanceller", echoCancellerAlreadyDone);
- super.onSaveInstanceState(outState);
- }
-
- public static AssistantActivity instance() {
- return instance;
- }
-
- public void updateStatusFragment(StatusFragment fragment) {
- status = fragment;
- }
-
- private AccountCreator loadAccountCreator(ProxyConfig cfg) {
- ProxyConfig cfgTab[] = LinphoneManager.getLc().getProxyConfigList();
- int n = -1;
- for (int i = 0 ; i < cfgTab.length ; i++) {
- if (cfgTab[i].equals(cfg)) {
- n = i;
- break;
- }
- }
- if (n >= 0) {
- mAccountCreator.setDomain(mPrefs.getAccountDomain(n));
- mAccountCreator.setUsername(mPrefs.getAccountUsername(n));
- }
- return mAccountCreator;
- }
-
- private void initUI() {
- back = findViewById(R.id.back);
- back.setOnClickListener(this);
- cancel = findViewById(R.id.assistant_cancel);
- cancel.setOnClickListener(this);
- }
-
- private void changeFragment(Fragment newFragment) {
- hideKeyboard();
- FragmentTransaction transaction = getFragmentManager().beginTransaction();
- transaction.replace(R.id.fragment_container, newFragment);
- transaction.commitAllowingStateLoss();
- }
-
- @Override
- public void onClick(View v) {
- int id = v.getId();
- boolean firstLaunch = LinphonePreferences.instance().isFirstLaunch();
-
- if (id == R.id.assistant_cancel) {
- hideKeyboard();
- LinphonePreferences.instance().firstLaunchSuccessful();
- if (getResources().getBoolean(R.bool.assistant_cancel_move_to_back)) {
- moveTaskToBack(true);
- } else {
- if (firstLaunch) startActivity(new Intent().setClass(this, LinphoneActivity.class));
- finish();
- }
- } else if (id == R.id.back) {
- hideKeyboard();
- onBackPressed();
- }
- }
-
- @Override
- public void onBackPressed() {
- if (isLink) {
- return;
- }
- boolean firstLaunch = LinphonePreferences.instance().isFirstLaunch();
- if (currentFragment == firstFragment) {
- LinphonePreferences.instance().firstLaunchSuccessful();
- if (getResources().getBoolean(R.bool.assistant_cancel_move_to_back)) {
- moveTaskToBack(true);
- } else {
- LinphonePreferences.instance().firstLaunchSuccessful();
- if (firstLaunch) startActivity(new Intent().setClass(this, LinphoneActivity.class));
- finish();
- }
- } else if (currentFragment == AssistantFragmentsEnum.LOGIN
- || currentFragment == AssistantFragmentsEnum.LINPHONE_LOGIN
- || currentFragment == AssistantFragmentsEnum.CREATE_ACCOUNT
- || currentFragment == AssistantFragmentsEnum.REMOTE_PROVISIONING) {
- displayMenu();
- } else if (currentFragment == AssistantFragmentsEnum.WELCOME) {
- if (firstLaunch) startActivity(new Intent().setClass(this, LinphoneActivity.class));
- finish();
- } else if (currentFragment == AssistantFragmentsEnum.COUNTRY_CHOOSER){
- if(lastFragment.equals(AssistantFragmentsEnum.LINPHONE_LOGIN)){
- displayLoginLinphone(null, null);
- } else {
- displayCreateAccount();
- }
- }
- }
-
- public void hideKeyboard(){
- InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
- View view = this.getCurrentFocus();
- if (imm != null && view != null) {
- imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
- }
- }
-
- public void checkAndRequestAudioPermission() {
- checkAndRequestPermission(Manifest.permission.RECORD_AUDIO, 0);
- }
-
- public void checkAndRequestPermission(String permission, int result) {
- int permissionGranted = getPackageManager().checkPermission(permission, getPackageName());
- Log.i("[Permission] " + permission + " is " + (permissionGranted == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
-
- if (permissionGranted != PackageManager.PERMISSION_GRANTED) {
- if (LinphonePreferences.instance().firstTimeAskingForPermission(permission) || ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
- Log.i("[Permission] Asking for " + permission);
- ActivityCompat.requestPermissions(this, new String[]{permission}, result);
- }
- }
- }
-
- @Override
- public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
- for (int i = 0; i < permissions.length; i++) {
- Log.i("[Permission] " + permissions[i] + " is " + (grantResults[i] == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
- }
-
- if (requestCode == PERMISSIONS_REQUEST_RECORD_AUDIO) {
- if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
- launchEchoCancellerCalibration(true);
- } else {
- isEchoCalibrationFinished();
- }
- }
- }
-
- private void launchEchoCancellerCalibration(boolean sendEcCalibrationResult) {
- int recordAudio = getPackageManager().checkPermission(Manifest.permission.RECORD_AUDIO, getPackageName());
- Log.i("[Permission] Record audio permission is " + (recordAudio == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
-
- if (recordAudio == PackageManager.PERMISSION_GRANTED) {
- EchoCancellerCalibrationFragment fragment = new EchoCancellerCalibrationFragment();
- fragment.enableEcCalibrationResultSending(sendEcCalibrationResult);
- changeFragment(fragment);
- currentFragment = AssistantFragmentsEnum.ECHO_CANCELLER_CALIBRATION;
- back.setVisibility(View.VISIBLE);
- cancel.setEnabled(false);
- } else {
- checkAndRequestAudioPermission();
- }
- }
-
- public void configureProxyConfig(AccountCreator accountCreator) {
- Core lc = LinphoneManager.getLc();
- ProxyConfig proxyConfig = lc.createProxyConfig();
- AuthInfo authInfo;
-
- String identity = proxyConfig.getIdentityAddress().asStringUriOnly();
- if (identity == null || accountCreator.getUsername() == null) {
- LinphoneUtils.displayErrorAlert(getString(R.string.error), this);
- return;
- }
- identity = identity.replace("?", accountCreator.getUsername());
- Address addr = Factory.instance().createAddress(identity);
- addr.setDisplayName(accountCreator.getUsername());
- address = addr;
- proxyConfig.edit();
-
-
- proxyConfig.setIdentityAddress(addr);
-
- if (accountCreator.getPhoneNumber() != null && accountCreator.getPhoneNumber().length() > 0)
- proxyConfig.setDialPrefix(org.linphone.core.Utils.getPrefixFromE164(accountCreator.getPhoneNumber()));
-
- proxyConfig.done();
-
- authInfo = Factory.instance().createAuthInfo(
- accountCreator.getUsername(),
- null,
- accountCreator.getPassword(),
- accountCreator.getHa1(),
- proxyConfig.getRealm(),
- proxyConfig.getDomain());
-
-
- lc.addProxyConfig(proxyConfig);
-
- lc.addAuthInfo(authInfo);
-
- lc.setDefaultProxyConfig(proxyConfig);
-
- if (LinphonePreferences.instance() != null)
- LinphonePreferences.instance().setPushNotificationEnabled(true);
-
- if (ContactsManager.getInstance() != null)
- ContactsManager.getInstance().fetchContactsAsync();
-
- if (LinphonePreferences.instance() != null)
- mPrefs.enabledFriendlistSubscription(getResources().getBoolean(R.bool.use_friendlist_subscription));
-
- LinphoneManager.getInstance().subscribeFriendList(getResources().getBoolean(R.bool.use_friendlist_subscription));
-
- if (!newAccount) {
- displayRegistrationInProgressDialog();
- }
- accountCreated = true;
- }
-
- public void linphoneLogIn(AccountCreator accountCreator) {
- LinphoneManager.getLc().getConfig().loadFromXmlFile(LinphoneManager.getInstance().getmDynamicConfigFile());
- configureProxyConfig(accountCreator);
- }
-
- public void genericLogIn(String username, String userid, String password, String displayname, String prefix, String domain, TransportType transport) {
- saveCreatedAccount(username, userid, password, displayname, null, prefix, domain, transport);
- }
-
- private void display(AssistantFragmentsEnum fragment) {
- switch (fragment) {
- case WELCOME:
- displayMenu();
- break;
- case LINPHONE_LOGIN:
- displayLoginLinphone(null, null);
- break;
- default:
- throw new IllegalStateException("Can't handle " + fragment);
- }
- }
-
- public void displayMenu() {
- fragment = new WelcomeFragment();
- changeFragment(fragment);
- country = null;
- currentFragment = AssistantFragmentsEnum.WELCOME;
- back.setVisibility(View.INVISIBLE);
- }
-
- public void displayLoginGeneric() {
- fragment = new LoginFragment();
- changeFragment(fragment);
- currentFragment = AssistantFragmentsEnum.LOGIN;
- back.setVisibility(View.VISIBLE);
- }
-
- public void displayLoginLinphone(String username, String password) {
- fragment = new LinphoneLoginFragment();
- Bundle extras = new Bundle();
- extras.putString("Phone", null);
- extras.putString("Dialcode", null);
- extras.putString("Username", username);
- extras.putString("Password", password);
- fragment.setArguments(extras);
- changeFragment(fragment);
- currentFragment = AssistantFragmentsEnum.LINPHONE_LOGIN;
- back.setVisibility(View.VISIBLE);
- }
-
- public void displayCreateAccount() {
- fragment = new CreateAccountFragment();
- Bundle extra = new Bundle();
- extra.putBoolean("LinkPhoneNumber", isLink);
- extra.putBoolean("LinkFromPref", fromPref);
- fragment.setArguments(extra);
- changeFragment(fragment);
- currentFragment = AssistantFragmentsEnum.CREATE_ACCOUNT;
- back.setVisibility(View.VISIBLE);
- }
-
- public void displayRemoteProvisioning() {
- fragment = new RemoteProvisioningFragment();
- changeFragment(fragment);
- currentFragment = AssistantFragmentsEnum.REMOTE_PROVISIONING;
- back.setVisibility(View.VISIBLE);
- }
-
- public void displayCountryChooser() {
- fragment = new CountryListFragment();
- changeFragment(fragment);
- lastFragment = currentFragment;
- currentFragment = AssistantFragmentsEnum.COUNTRY_CHOOSER;
- back.setVisibility(View.VISIBLE);
- }
-
- private void launchDownloadCodec() {
- if (OpenH264DownloadHelper.isOpenH264DownloadEnabled()) {
- OpenH264DownloadHelper downloadHelper = Factory.instance().createOpenH264DownloadHelper(this);
- if (Version.getCpuAbis().contains("armeabi-v7a") && !Version.getCpuAbis().contains("x86") && !downloadHelper.isCodecFound()) {
- CodecDownloaderFragment codecFragment = new CodecDownloaderFragment();
- changeFragment(codecFragment);
- currentFragment = AssistantFragmentsEnum.DOWNLOAD_CODEC;
- back.setVisibility(View.VISIBLE);
- cancel.setEnabled(false);
- } else
- goToLinphoneActivity();
- } else {
- goToLinphoneActivity();
- }
- }
-
- public void endDownloadCodec() {
- goToLinphoneActivity();
- }
-
- public String getPhoneWithCountry() {
- if(country == null || phone_number == null) return "";
- String phoneNumberWithCountry = country.getCountryCallingCode() + phone_number.replace("\\D", "");
- return phoneNumberWithCountry;
- }
-
- public void saveCreatedAccount(String username, String userid, String password, String displayname, String ha1, String prefix, String domain, TransportType transport) {
-
- username = LinphoneUtils.getDisplayableUsernameFromAddress(username);
- domain = LinphoneUtils.getDisplayableUsernameFromAddress(domain);
-
- String identity = "sip:" + username + "@" + domain;
- address = Factory.instance().createAddress(identity);
-
- AccountBuilder builder = new AccountBuilder(LinphoneManager.getLc())
- .setUsername(username)
- .setDomain(domain)
- .setHa1(ha1)
- .setUserid(userid)
- .setDisplayName(displayname)
- .setPassword(password);
-
- if (prefix != null) {
- builder.setPrefix(prefix);
- }
-
- String forcedProxy = "";
- if (!TextUtils.isEmpty(forcedProxy)) {
- builder.setServerAddr(forcedProxy)
- .setOutboundProxyEnabled(true)
- .setAvpfRrInterval(5);
- }
- if (transport != null) {
- builder.setTransport(transport);
- }
-
- try {
- builder.saveNewAccount();
- if (!newAccount) {
- displayRegistrationInProgressDialog();
- }
- accountCreated = true;
- } catch (CoreException e) {
- Log.e(e);
- }
- }
-
- public void displayRegistrationInProgressDialog() {
- if(LinphoneManager.getLc().isNetworkReachable()) {
- progress = ProgressDialog.show(this, null, null);
- Drawable d = new ColorDrawable(ContextCompat.getColor(this, R.color.colorE));
- d.setAlpha(200);
- progress.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
- progress.getWindow().setBackgroundDrawable(d);
- progress.setContentView(R.layout.progress_dialog);
- progress.show();
- }
- }
-
- public void displayRemoteProvisioningInProgressDialog() {
- remoteProvisioningInProgress = true;
-
- progress = ProgressDialog.show(this, null, null);
- Drawable d = new ColorDrawable(ContextCompat.getColor(this, R.color.colorE));
- d.setAlpha(200);
- progress.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
- progress.getWindow().setBackgroundDrawable(d);
- progress.setContentView(R.layout.progress_dialog);
- progress.show();
- }
-
- public void displayAssistantConfirm(String username, String password, String email) {
- CreateAccountActivationFragment fragment = new CreateAccountActivationFragment();
- newAccount = true;
- Bundle extras = new Bundle();
- extras.putString("Username", username);
- extras.putString("Password", password);
- extras.putString("Email", email);
- fragment.setArguments(extras);
- changeFragment(fragment);
-
- currentFragment = AssistantFragmentsEnum.CREATE_ACCOUNT_ACTIVATION;
- back.setVisibility(View.INVISIBLE);
- }
-
- public void displayAssistantCodeConfirm(String username, String phone, String dialcode, boolean recoverAccount) {
- CreateAccountCodeActivationFragment fragment = new CreateAccountCodeActivationFragment();
- newAccount = true;
- Bundle extras = new Bundle();
- extras.putString("Username", username);
- extras.putString("Phone", phone);
- extras.putString("Dialcode", dialcode);
- extras.putBoolean("RecoverAccount", recoverAccount);
- extras.putBoolean("LinkAccount", isLink);
- fragment.setArguments(extras);
- changeFragment(fragment);
-
- currentFragment = AssistantFragmentsEnum.CREATE_ACCOUNT_CODE_ACTIVATION;
- back.setVisibility(View.INVISIBLE);
- }
-
- public void displayAssistantLinphoneLogin( String phone, String dialcode) {
- LinphoneLoginFragment fragment = new LinphoneLoginFragment();
- newAccount = true;
- Bundle extras = new Bundle();
- extras.putString("Phone", phone);
- extras.putString("Dialcode", dialcode);
- fragment.setArguments(extras);
- changeFragment(fragment);
-
- currentFragment = AssistantFragmentsEnum.LINPHONE_LOGIN;
- back.setVisibility(View.VISIBLE);
- }
-
- public void isAccountVerified(String username) {
- Toast.makeText(this, getString(R.string.assistant_account_validated), Toast.LENGTH_LONG).show();
- hideKeyboard();
- success();
- }
-
- public void isEchoCalibrationFinished() {
- launchDownloadCodec();
- }
-
- public Dialog createErrorDialog(ProxyConfig proxy, String message){
- AlertDialog.Builder builder = new AlertDialog.Builder(this);
- if(message.equals("Forbidden")) {
- message = getString(R.string.assistant_error_bad_credentials);
- }
- builder.setMessage(message)
- .setTitle(proxy.getState().toString())
- .setPositiveButton(getString(R.string.continue_text), new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int id) {
- success();
- }
- })
- .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int id) {
- LinphoneManager.getLc().removeProxyConfig(LinphoneManager.getLc().getDefaultProxyConfig());
- LinphonePreferences.instance().resetDefaultProxyConfig();
- LinphoneManager.getLc().refreshRegisters();
- dialog.dismiss();
- }
- });
- return builder.show();
- }
-
- public void success() {
- boolean needsEchoCalibration = LinphoneManager.getLc().isEchoCancellerCalibrationRequired();
- if (needsEchoCalibration && mPrefs.isFirstLaunch()) {
- launchEchoCancellerCalibration(true);
- } else {
- launchDownloadCodec();
- }
- }
-
- private void goToLinphoneActivity() {
- mPrefs.firstLaunchSuccessful();
- startActivity(new Intent().setClass(this, LinphoneActivity.class).putExtra("isNewProxyConfig", true));
- finish();
- }
-
- public void setCoreListener() {
- Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- if (lc != null) {
- lc.addListener(mListener);
- }
- if (status != null) {
- status.setCoreListener();
- }
- }
-
- public void restartApplication() {
- mPrefs.firstLaunchSuccessful();
-
- Intent mStartActivity = new Intent(this, LinphoneLauncherActivity.class);
- PendingIntent mPendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
- AlarmManager mgr = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
- mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 500, mPendingIntent);
-
- finish();
- stopService(new Intent(Intent.ACTION_MAIN).setClass(this, LinphoneService.class));
- ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
- am.killBackgroundProcesses(getString(R.string.sync_account_type));
- android.os.Process.killProcess(android.os.Process.myPid());
- }
-
- @Override
- public void onIsAccountExist(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
- if(status.equals(AccountCreator.Status.AccountExistWithAlias)){
- success();
- } else {
- isLink = true;
- displayCreateAccount();
- }
- if (mAccountCreator != null) mAccountCreator.setListener(null);
- }
-
- @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) {
-
- }
-
- @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) {
-
- }
-
- @Override
- public void onIsAliasUsed(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
-
- }
-
- @Override
- public void onUpdateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
-
- }
-
- public CountryListAdapter getCountryListAdapter() {
- return countryListAdapter;
- }
-
- /**
- * This class reads a JSON file containing Country-specific phone number description,
- * and allows to present them into a ListView
- */
- public class CountryListAdapter extends BaseAdapter implements Filterable {
-
- private LayoutInflater mInflater;
- private DialPlan[] allCountries;
- private List filteredCountries;
- private Context context;
-
- public CountryListAdapter(Context ctx) {
- context = ctx;
- allCountries = Factory.instance().getDialPlans();
- filteredCountries = new ArrayList(Arrays.asList(allCountries));
- }
-
- public void setInflater(LayoutInflater inf) {
- mInflater = inf;
- }
-
-
- public DialPlan getCountryFromCountryCode(String countryCode) {
- countryCode = (countryCode.startsWith("+")) ? countryCode.substring(1) : countryCode;
- for (DialPlan c : allCountries) {
- if (c.getCountryCallingCode().compareTo(countryCode) == 0)
- return c;
- }
- return null;
- }
-
- @Override
- public int getCount() {
- return filteredCountries.size();
- }
-
- @Override
- public DialPlan getItem(int position) {
- return filteredCountries.get(position);
- }
-
- @Override
- public long getItemId(int position) {
- return position;
- }
-
- @Override
- public View getView(int position, View convertView, ViewGroup parent){
- View view;
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+
+ Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ if (lc != null) {
+ lc.addListener(mListener);
+ }
+ }
+
+ @Override
+ protected void onPause() {
+ Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ if (lc != null) {
+ lc.removeListener(mListener);
+ }
+
+ super.onPause();
+ }
+
+ @Override
+ protected void onSaveInstanceState(Bundle outState) {
+ outState.putSerializable("CurrentFragment", currentFragment);
+ outState.putBoolean("echoCanceller", echoCancellerAlreadyDone);
+ super.onSaveInstanceState(outState);
+ }
+
+ public static AssistantActivity instance() {
+ return instance;
+ }
+
+ public void updateStatusFragment(StatusFragment fragment) {
+ status = fragment;
+ }
+
+ private AccountCreator loadAccountCreator(ProxyConfig cfg) {
+ ProxyConfig cfgTab[] = LinphoneManager.getLc().getProxyConfigList();
+ int n = -1;
+ for (int i = 0; i < cfgTab.length; i++) {
+ if (cfgTab[i].equals(cfg)) {
+ n = i;
+ break;
+ }
+ }
+ if (n >= 0) {
+ mAccountCreator.setDomain(mPrefs.getAccountDomain(n));
+ mAccountCreator.setUsername(mPrefs.getAccountUsername(n));
+ }
+ return mAccountCreator;
+ }
+
+ private void initUI() {
+ back = findViewById(R.id.back);
+ back.setOnClickListener(this);
+ cancel = findViewById(R.id.assistant_cancel);
+ cancel.setOnClickListener(this);
+ }
+
+ private void changeFragment(Fragment newFragment) {
+ hideKeyboard();
+ FragmentTransaction transaction = getFragmentManager().beginTransaction();
+ transaction.replace(R.id.fragment_container, newFragment);
+ transaction.commitAllowingStateLoss();
+ }
+
+ @Override
+ public void onClick(View v) {
+ int id = v.getId();
+ boolean firstLaunch = LinphonePreferences.instance().isFirstLaunch();
+
+ if (id == R.id.assistant_cancel) {
+ hideKeyboard();
+ LinphonePreferences.instance().firstLaunchSuccessful();
+ if (getResources().getBoolean(R.bool.assistant_cancel_move_to_back)) {
+ moveTaskToBack(true);
+ } else {
+ if (firstLaunch) startActivity(new Intent().setClass(this, LinphoneActivity.class));
+ finish();
+ }
+ } else if (id == R.id.back) {
+ hideKeyboard();
+ onBackPressed();
+ }
+ }
+
+ @Override
+ public void onBackPressed() {
+ if (isLink) {
+ return;
+ }
+ boolean firstLaunch = LinphonePreferences.instance().isFirstLaunch();
+ if (currentFragment == firstFragment) {
+ LinphonePreferences.instance().firstLaunchSuccessful();
+ if (getResources().getBoolean(R.bool.assistant_cancel_move_to_back)) {
+ moveTaskToBack(true);
+ } else {
+ LinphonePreferences.instance().firstLaunchSuccessful();
+ if (firstLaunch) startActivity(new Intent().setClass(this, LinphoneActivity.class));
+ finish();
+ }
+ } else if (currentFragment == AssistantFragmentsEnum.LOGIN
+ || currentFragment == AssistantFragmentsEnum.LINPHONE_LOGIN
+ || currentFragment == AssistantFragmentsEnum.CREATE_ACCOUNT
+ || currentFragment == AssistantFragmentsEnum.REMOTE_PROVISIONING) {
+ displayMenu();
+ } else if (currentFragment == AssistantFragmentsEnum.WELCOME) {
+ if (firstLaunch) startActivity(new Intent().setClass(this, LinphoneActivity.class));
+ finish();
+ } else if (currentFragment == AssistantFragmentsEnum.COUNTRY_CHOOSER) {
+ if (lastFragment.equals(AssistantFragmentsEnum.LINPHONE_LOGIN)) {
+ displayLoginLinphone(null, null);
+ } else {
+ displayCreateAccount();
+ }
+ }
+ }
+
+ public void hideKeyboard() {
+ InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
+ View view = this.getCurrentFocus();
+ if (imm != null && view != null) {
+ imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
+ }
+ }
+
+ public void checkAndRequestAudioPermission() {
+ checkAndRequestPermission(Manifest.permission.RECORD_AUDIO, 0);
+ }
+
+ public void checkAndRequestPermission(String permission, int result) {
+ int permissionGranted = getPackageManager().checkPermission(permission, getPackageName());
+ Log.i("[Permission] " + permission + " is " + (permissionGranted == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
+
+ if (permissionGranted != PackageManager.PERMISSION_GRANTED) {
+ if (LinphonePreferences.instance().firstTimeAskingForPermission(permission) || ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
+ Log.i("[Permission] Asking for " + permission);
+ ActivityCompat.requestPermissions(this, new String[]{permission}, result);
+ }
+ }
+ }
+
+ @Override
+ public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
+ for (int i = 0; i < permissions.length; i++) {
+ Log.i("[Permission] " + permissions[i] + " is " + (grantResults[i] == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
+ }
+
+ if (requestCode == PERMISSIONS_REQUEST_RECORD_AUDIO) {
+ if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
+ launchEchoCancellerCalibration(true);
+ } else {
+ isEchoCalibrationFinished();
+ }
+ }
+ }
+
+ private void launchEchoCancellerCalibration(boolean sendEcCalibrationResult) {
+ int recordAudio = getPackageManager().checkPermission(Manifest.permission.RECORD_AUDIO, getPackageName());
+ Log.i("[Permission] Record audio permission is " + (recordAudio == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
+
+ if (recordAudio == PackageManager.PERMISSION_GRANTED) {
+ EchoCancellerCalibrationFragment fragment = new EchoCancellerCalibrationFragment();
+ fragment.enableEcCalibrationResultSending(sendEcCalibrationResult);
+ changeFragment(fragment);
+ currentFragment = AssistantFragmentsEnum.ECHO_CANCELLER_CALIBRATION;
+ back.setVisibility(View.VISIBLE);
+ cancel.setEnabled(false);
+ } else {
+ checkAndRequestAudioPermission();
+ }
+ }
+
+ public void configureProxyConfig(AccountCreator accountCreator) {
+ Core lc = LinphoneManager.getLc();
+ ProxyConfig proxyConfig = lc.createProxyConfig();
+ AuthInfo authInfo;
+
+ String identity = proxyConfig.getIdentityAddress().asStringUriOnly();
+ if (identity == null || accountCreator.getUsername() == null) {
+ LinphoneUtils.displayErrorAlert(getString(R.string.error), this);
+ return;
+ }
+ identity = identity.replace("?", accountCreator.getUsername());
+ Address addr = Factory.instance().createAddress(identity);
+ addr.setDisplayName(accountCreator.getUsername());
+ address = addr;
+ proxyConfig.edit();
+
+
+ proxyConfig.setIdentityAddress(addr);
+
+ if (accountCreator.getPhoneNumber() != null && accountCreator.getPhoneNumber().length() > 0)
+ proxyConfig.setDialPrefix(org.linphone.core.Utils.getPrefixFromE164(accountCreator.getPhoneNumber()));
+
+ proxyConfig.done();
+
+ authInfo = Factory.instance().createAuthInfo(
+ accountCreator.getUsername(),
+ null,
+ accountCreator.getPassword(),
+ accountCreator.getHa1(),
+ proxyConfig.getRealm(),
+ proxyConfig.getDomain());
+
+
+ lc.addProxyConfig(proxyConfig);
+
+ lc.addAuthInfo(authInfo);
+
+ lc.setDefaultProxyConfig(proxyConfig);
+
+ if (LinphonePreferences.instance() != null)
+ LinphonePreferences.instance().setPushNotificationEnabled(true);
+
+ if (ContactsManager.getInstance() != null)
+ ContactsManager.getInstance().fetchContactsAsync();
+
+ if (LinphonePreferences.instance() != null)
+ mPrefs.enabledFriendlistSubscription(getResources().getBoolean(R.bool.use_friendlist_subscription));
+
+ LinphoneManager.getInstance().subscribeFriendList(getResources().getBoolean(R.bool.use_friendlist_subscription));
+
+ if (!newAccount) {
+ displayRegistrationInProgressDialog();
+ }
+ accountCreated = true;
+ }
+
+ public void linphoneLogIn(AccountCreator accountCreator) {
+ LinphoneManager.getLc().getConfig().loadFromXmlFile(LinphoneManager.getInstance().getmDynamicConfigFile());
+ configureProxyConfig(accountCreator);
+ }
+
+ public void genericLogIn(String username, String userid, String password, String displayname, String prefix, String domain, TransportType transport) {
+ saveCreatedAccount(username, userid, password, displayname, null, prefix, domain, transport);
+ }
+
+ private void display(AssistantFragmentsEnum fragment) {
+ switch (fragment) {
+ case WELCOME:
+ displayMenu();
+ break;
+ case LINPHONE_LOGIN:
+ displayLoginLinphone(null, null);
+ break;
+ default:
+ throw new IllegalStateException("Can't handle " + fragment);
+ }
+ }
+
+ public void displayMenu() {
+ fragment = new WelcomeFragment();
+ changeFragment(fragment);
+ country = null;
+ currentFragment = AssistantFragmentsEnum.WELCOME;
+ back.setVisibility(View.INVISIBLE);
+ }
+
+ public void displayLoginGeneric() {
+ fragment = new LoginFragment();
+ changeFragment(fragment);
+ currentFragment = AssistantFragmentsEnum.LOGIN;
+ back.setVisibility(View.VISIBLE);
+ }
+
+ public void displayLoginLinphone(String username, String password) {
+ fragment = new LinphoneLoginFragment();
+ Bundle extras = new Bundle();
+ extras.putString("Phone", null);
+ extras.putString("Dialcode", null);
+ extras.putString("Username", username);
+ extras.putString("Password", password);
+ fragment.setArguments(extras);
+ changeFragment(fragment);
+ currentFragment = AssistantFragmentsEnum.LINPHONE_LOGIN;
+ back.setVisibility(View.VISIBLE);
+ }
+
+ public void displayCreateAccount() {
+ fragment = new CreateAccountFragment();
+ Bundle extra = new Bundle();
+ extra.putBoolean("LinkPhoneNumber", isLink);
+ extra.putBoolean("LinkFromPref", fromPref);
+ fragment.setArguments(extra);
+ changeFragment(fragment);
+ currentFragment = AssistantFragmentsEnum.CREATE_ACCOUNT;
+ back.setVisibility(View.VISIBLE);
+ }
+
+ public void displayRemoteProvisioning() {
+ fragment = new RemoteProvisioningFragment();
+ changeFragment(fragment);
+ currentFragment = AssistantFragmentsEnum.REMOTE_PROVISIONING;
+ back.setVisibility(View.VISIBLE);
+ }
+
+ public void displayCountryChooser() {
+ fragment = new CountryListFragment();
+ changeFragment(fragment);
+ lastFragment = currentFragment;
+ currentFragment = AssistantFragmentsEnum.COUNTRY_CHOOSER;
+ back.setVisibility(View.VISIBLE);
+ }
+
+ private void launchDownloadCodec() {
+ if (OpenH264DownloadHelper.isOpenH264DownloadEnabled()) {
+ OpenH264DownloadHelper downloadHelper = Factory.instance().createOpenH264DownloadHelper(this);
+ if (Version.getCpuAbis().contains("armeabi-v7a") && !Version.getCpuAbis().contains("x86") && !downloadHelper.isCodecFound()) {
+ CodecDownloaderFragment codecFragment = new CodecDownloaderFragment();
+ changeFragment(codecFragment);
+ currentFragment = AssistantFragmentsEnum.DOWNLOAD_CODEC;
+ back.setVisibility(View.VISIBLE);
+ cancel.setEnabled(false);
+ } else
+ goToLinphoneActivity();
+ } else {
+ goToLinphoneActivity();
+ }
+ }
+
+ public void endDownloadCodec() {
+ goToLinphoneActivity();
+ }
+
+ public String getPhoneWithCountry() {
+ if (country == null || phone_number == null) return "";
+ String phoneNumberWithCountry = country.getCountryCallingCode() + phone_number.replace("\\D", "");
+ return phoneNumberWithCountry;
+ }
+
+ public void saveCreatedAccount(String username, String userid, String password, String displayname, String ha1, String prefix, String domain, TransportType transport) {
+
+ username = LinphoneUtils.getDisplayableUsernameFromAddress(username);
+ domain = LinphoneUtils.getDisplayableUsernameFromAddress(domain);
+
+ String identity = "sip:" + username + "@" + domain;
+ address = Factory.instance().createAddress(identity);
+
+ AccountBuilder builder = new AccountBuilder(LinphoneManager.getLc())
+ .setUsername(username)
+ .setDomain(domain)
+ .setHa1(ha1)
+ .setUserid(userid)
+ .setDisplayName(displayname)
+ .setPassword(password);
+
+ if (prefix != null) {
+ builder.setPrefix(prefix);
+ }
+
+ String forcedProxy = "";
+ if (!TextUtils.isEmpty(forcedProxy)) {
+ builder.setServerAddr(forcedProxy)
+ .setOutboundProxyEnabled(true)
+ .setAvpfRrInterval(5);
+ }
+ if (transport != null) {
+ builder.setTransport(transport);
+ }
+
+ try {
+ builder.saveNewAccount();
+ if (!newAccount) {
+ displayRegistrationInProgressDialog();
+ }
+ accountCreated = true;
+ } catch (CoreException e) {
+ Log.e(e);
+ }
+ }
+
+ public void displayRegistrationInProgressDialog() {
+ if (LinphoneManager.getLc().isNetworkReachable()) {
+ progress = ProgressDialog.show(this, null, null);
+ Drawable d = new ColorDrawable(ContextCompat.getColor(this, R.color.colorE));
+ d.setAlpha(200);
+ progress.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
+ progress.getWindow().setBackgroundDrawable(d);
+ progress.setContentView(R.layout.progress_dialog);
+ progress.show();
+ }
+ }
+
+ public void displayRemoteProvisioningInProgressDialog() {
+ remoteProvisioningInProgress = true;
+
+ progress = ProgressDialog.show(this, null, null);
+ Drawable d = new ColorDrawable(ContextCompat.getColor(this, R.color.colorE));
+ d.setAlpha(200);
+ progress.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
+ progress.getWindow().setBackgroundDrawable(d);
+ progress.setContentView(R.layout.progress_dialog);
+ progress.show();
+ }
+
+ public void displayAssistantConfirm(String username, String password, String email) {
+ CreateAccountActivationFragment fragment = new CreateAccountActivationFragment();
+ newAccount = true;
+ Bundle extras = new Bundle();
+ extras.putString("Username", username);
+ extras.putString("Password", password);
+ extras.putString("Email", email);
+ fragment.setArguments(extras);
+ changeFragment(fragment);
+
+ currentFragment = AssistantFragmentsEnum.CREATE_ACCOUNT_ACTIVATION;
+ back.setVisibility(View.INVISIBLE);
+ }
+
+ public void displayAssistantCodeConfirm(String username, String phone, String dialcode, boolean recoverAccount) {
+ CreateAccountCodeActivationFragment fragment = new CreateAccountCodeActivationFragment();
+ newAccount = true;
+ Bundle extras = new Bundle();
+ extras.putString("Username", username);
+ extras.putString("Phone", phone);
+ extras.putString("Dialcode", dialcode);
+ extras.putBoolean("RecoverAccount", recoverAccount);
+ extras.putBoolean("LinkAccount", isLink);
+ fragment.setArguments(extras);
+ changeFragment(fragment);
+
+ currentFragment = AssistantFragmentsEnum.CREATE_ACCOUNT_CODE_ACTIVATION;
+ back.setVisibility(View.INVISIBLE);
+ }
+
+ public void displayAssistantLinphoneLogin(String phone, String dialcode) {
+ LinphoneLoginFragment fragment = new LinphoneLoginFragment();
+ newAccount = true;
+ Bundle extras = new Bundle();
+ extras.putString("Phone", phone);
+ extras.putString("Dialcode", dialcode);
+ fragment.setArguments(extras);
+ changeFragment(fragment);
+
+ currentFragment = AssistantFragmentsEnum.LINPHONE_LOGIN;
+ back.setVisibility(View.VISIBLE);
+ }
+
+ public void isAccountVerified(String username) {
+ Toast.makeText(this, getString(R.string.assistant_account_validated), Toast.LENGTH_LONG).show();
+ hideKeyboard();
+ success();
+ }
+
+ public void isEchoCalibrationFinished() {
+ launchDownloadCodec();
+ }
+
+ public Dialog createErrorDialog(ProxyConfig proxy, String message) {
+ AlertDialog.Builder builder = new AlertDialog.Builder(this);
+ if (message.equals("Forbidden")) {
+ message = getString(R.string.assistant_error_bad_credentials);
+ }
+ builder.setMessage(message)
+ .setTitle(proxy.getState().toString())
+ .setPositiveButton(getString(R.string.continue_text), new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int id) {
+ success();
+ }
+ })
+ .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int id) {
+ LinphoneManager.getLc().removeProxyConfig(LinphoneManager.getLc().getDefaultProxyConfig());
+ LinphonePreferences.instance().resetDefaultProxyConfig();
+ LinphoneManager.getLc().refreshRegisters();
+ dialog.dismiss();
+ }
+ });
+ return builder.show();
+ }
+
+ public void success() {
+ boolean needsEchoCalibration = LinphoneManager.getLc().isEchoCancellerCalibrationRequired();
+ if (needsEchoCalibration && mPrefs.isFirstLaunch()) {
+ launchEchoCancellerCalibration(true);
+ } else {
+ launchDownloadCodec();
+ }
+ }
+
+ private void goToLinphoneActivity() {
+ mPrefs.firstLaunchSuccessful();
+ startActivity(new Intent().setClass(this, LinphoneActivity.class).putExtra("isNewProxyConfig", true));
+ finish();
+ }
+
+ public void setCoreListener() {
+ Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ if (lc != null) {
+ lc.addListener(mListener);
+ }
+ if (status != null) {
+ status.setCoreListener();
+ }
+ }
+
+ public void restartApplication() {
+ mPrefs.firstLaunchSuccessful();
+
+ Intent mStartActivity = new Intent(this, LinphoneLauncherActivity.class);
+ PendingIntent mPendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
+ AlarmManager mgr = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
+ mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 500, mPendingIntent);
+
+ finish();
+ stopService(new Intent(Intent.ACTION_MAIN).setClass(this, LinphoneService.class));
+ ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
+ am.killBackgroundProcesses(getString(R.string.sync_account_type));
+ android.os.Process.killProcess(android.os.Process.myPid());
+ }
+
+ @Override
+ public void onIsAccountExist(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
+ if (status.equals(AccountCreator.Status.AccountExistWithAlias)) {
+ success();
+ } else {
+ isLink = true;
+ displayCreateAccount();
+ }
+ if (mAccountCreator != null) mAccountCreator.setListener(null);
+ }
+
+ @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) {
+
+ }
+
+ @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) {
+
+ }
+
+ @Override
+ public void onIsAliasUsed(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
+
+ }
+
+ @Override
+ public void onUpdateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
+
+ }
+
+ public CountryListAdapter getCountryListAdapter() {
+ return countryListAdapter;
+ }
+
+ /**
+ * This class reads a JSON file containing Country-specific phone number description,
+ * and allows to present them into a ListView
+ */
+ public class CountryListAdapter extends BaseAdapter implements Filterable {
+
+ private LayoutInflater mInflater;
+ private DialPlan[] allCountries;
+ private List filteredCountries;
+ private Context context;
+
+ public CountryListAdapter(Context ctx) {
+ context = ctx;
+ allCountries = Factory.instance().getDialPlans();
+ filteredCountries = new ArrayList(Arrays.asList(allCountries));
+ }
+
+ public void setInflater(LayoutInflater inf) {
+ mInflater = inf;
+ }
+
+
+ public DialPlan getCountryFromCountryCode(String countryCode) {
+ countryCode = (countryCode.startsWith("+")) ? countryCode.substring(1) : countryCode;
+ for (DialPlan c : allCountries) {
+ if (c.getCountryCallingCode().compareTo(countryCode) == 0)
+ return c;
+ }
+ return null;
+ }
+
+ @Override
+ public int getCount() {
+ return filteredCountries.size();
+ }
+
+ @Override
+ public DialPlan getItem(int position) {
+ return filteredCountries.get(position);
+ }
+
+ @Override
+ public long getItemId(int position) {
+ return position;
+ }
+
+ @Override
+ public View getView(int position, View convertView, ViewGroup parent) {
+ View view;
- if (convertView != null) {
- view = convertView;
- } else {
- view = mInflater.inflate(R.layout.country_cell, parent, false);
- }
-
- DialPlan c = filteredCountries.get(position);
-
- TextView name = (TextView) view.findViewById(R.id.country_name);
- name.setText(c.getCountry());
-
- TextView dial_code = (TextView) view.findViewById(R.id.country_prefix);
- if (context != null)
- dial_code.setText(String.format(context.getString(R.string.country_code),c.getCountryCallingCode()));
-
- view.setTag(c);
- return view;
- }
-
- @Override
- public Filter getFilter() {
- return new Filter() {
- @Override
- protected FilterResults performFiltering(CharSequence constraint) {
- ArrayList filteredCountries = new ArrayList();
- for (DialPlan c : allCountries) {
- if (c.getCountry().toLowerCase().contains(constraint)
- || c.getCountryCallingCode().contains(constraint)) {
- filteredCountries.add(c);
- }
- }
- FilterResults filterResults = new FilterResults();
- filterResults.values = filteredCountries;
- return filterResults;
- }
-
- @Override
- @SuppressWarnings("unchecked")
- protected void publishResults(CharSequence constraint, FilterResults results) {
- filteredCountries = (List) results.values;
- CountryListAdapter.this.notifyDataSetChanged();
- }
- };
- }
- }
+ if (convertView != null) {
+ view = convertView;
+ } else {
+ view = mInflater.inflate(R.layout.country_cell, parent, false);
+ }
+
+ DialPlan c = filteredCountries.get(position);
+
+ TextView name = (TextView) view.findViewById(R.id.country_name);
+ name.setText(c.getCountry());
+
+ TextView dial_code = (TextView) view.findViewById(R.id.country_prefix);
+ if (context != null)
+ dial_code.setText(String.format(context.getString(R.string.country_code), c.getCountryCallingCode()));
+
+ view.setTag(c);
+ return view;
+ }
+
+ @Override
+ public Filter getFilter() {
+ return new Filter() {
+ @Override
+ protected FilterResults performFiltering(CharSequence constraint) {
+ ArrayList filteredCountries = new ArrayList();
+ for (DialPlan c : allCountries) {
+ if (c.getCountry().toLowerCase().contains(constraint)
+ || c.getCountryCallingCode().contains(constraint)) {
+ filteredCountries.add(c);
+ }
+ }
+ FilterResults filterResults = new FilterResults();
+ filterResults.values = filteredCountries;
+ return filterResults;
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ protected void publishResults(CharSequence constraint, FilterResults results) {
+ filteredCountries = (List) results.values;
+ CountryListAdapter.this.notifyDataSetChanged();
+ }
+ };
+ }
+ }
}
diff --git a/src/android/org/linphone/assistant/AssistantFragmentsEnum.java b/src/android/org/linphone/assistant/AssistantFragmentsEnum.java
index 52fcdd38a..4b8cf250a 100644
--- a/src/android/org/linphone/assistant/AssistantFragmentsEnum.java
+++ b/src/android/org/linphone/assistant/AssistantFragmentsEnum.java
@@ -19,14 +19,14 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
public enum AssistantFragmentsEnum {
- WELCOME,
- CREATE_ACCOUNT,
- CREATE_ACCOUNT_ACTIVATION,
- CREATE_ACCOUNT_CODE_ACTIVATION,
- LINPHONE_LOGIN,
- COUNTRY_CHOOSER,
- LOGIN,
- REMOTE_PROVISIONING,
- ECHO_CANCELLER_CALIBRATION,
- DOWNLOAD_CODEC;
+ WELCOME,
+ CREATE_ACCOUNT,
+ CREATE_ACCOUNT_ACTIVATION,
+ CREATE_ACCOUNT_CODE_ACTIVATION,
+ LINPHONE_LOGIN,
+ COUNTRY_CHOOSER,
+ LOGIN,
+ REMOTE_PROVISIONING,
+ ECHO_CANCELLER_CALIBRATION,
+ DOWNLOAD_CODEC;
}
diff --git a/src/android/org/linphone/assistant/CodecDownloaderFragment.java b/src/android/org/linphone/assistant/CodecDownloaderFragment.java
index 7fb595619..fb32833a7 100644
--- a/src/android/org/linphone/assistant/CodecDownloaderFragment.java
+++ b/src/android/org/linphone/assistant/CodecDownloaderFragment.java
@@ -19,12 +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 org.linphone.LinphoneManager;
-import org.linphone.R;
-import org.linphone.core.tools.OpenH264DownloadHelperListener;
-import org.linphone.core.PayloadType;
-import org.linphone.core.tools.OpenH264DownloadHelper;
-
import android.app.Fragment;
import android.os.Build;
import android.os.Bundle;
@@ -36,170 +30,178 @@ import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
+import org.linphone.LinphoneManager;
+import org.linphone.R;
+import org.linphone.core.PayloadType;
+import org.linphone.core.tools.OpenH264DownloadHelper;
+import org.linphone.core.tools.OpenH264DownloadHelperListener;
+
public class CodecDownloaderFragment extends Fragment {
- private Handler mHandler = new Handler();
- private TextView question;
- private TextView downloading;
- private TextView downloaded;
- private Button yes;
- private Button no;
- private Button ok;
- private ProgressBar bar;
- private TextView downloadingInfo;
+ private Handler mHandler = new Handler();
+ private TextView question;
+ private TextView downloading;
+ private TextView downloaded;
+ private Button yes;
+ private Button no;
+ private Button ok;
+ private ProgressBar bar;
+ private TextView downloadingInfo;
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- final View view = inflater.inflate(R.layout.assistant_codec_downloader, container, false);
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container,
+ Bundle savedInstanceState) {
+ final View view = inflater.inflate(R.layout.assistant_codec_downloader, container, false);
- question = view.findViewById(R.id.question);
- downloading = view.findViewById(R.id.downloading);
- downloaded = view.findViewById(R.id.downloaded);
- yes = view.findViewById(R.id.answerYes);
- no = view.findViewById(R.id.answerNo);
- ok = view.findViewById(R.id.answerOk);
- bar = view.findViewById(R.id.progressBar);
- downloadingInfo = view.findViewById(R.id.downloadingInfo);
+ question = view.findViewById(R.id.question);
+ downloading = view.findViewById(R.id.downloading);
+ downloaded = view.findViewById(R.id.downloaded);
+ yes = view.findViewById(R.id.answerYes);
+ no = view.findViewById(R.id.answerNo);
+ ok = view.findViewById(R.id.answerOk);
+ bar = view.findViewById(R.id.progressBar);
+ downloadingInfo = view.findViewById(R.id.downloadingInfo);
- final OpenH264DownloadHelper codecDownloader = LinphoneManager.getInstance().getOpenH264DownloadHelper();
- final OpenH264DownloadHelperListener codecListener = new OpenH264DownloadHelperListener() {
+ final OpenH264DownloadHelper codecDownloader = LinphoneManager.getInstance().getOpenH264DownloadHelper();
+ final OpenH264DownloadHelperListener codecListener = new OpenH264DownloadHelperListener() {
- @Override
- public void OnProgress(final int current, final int max) {
- mHandler.post(new Runnable() {
- @Override
- public void run() {
- if (current <= max) {
- hideAllItems();
- downloadingInfo.setText(current + " / " + max);
- downloadingInfo.setVisibility(View.VISIBLE);
- downloading.setVisibility(View.VISIBLE);
- bar.setMax(max);
- bar.setProgress(current);
- bar.setVisibility(View.VISIBLE);
- } else {
- hideAllItems();
- downloaded.setVisibility(View.VISIBLE);
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
- enabledH264(true);
- 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() {
+ if (current <= max) {
+ hideAllItems();
+ downloadingInfo.setText(current + " / " + max);
+ downloadingInfo.setVisibility(View.VISIBLE);
+ downloading.setVisibility(View.VISIBLE);
+ bar.setMax(max);
+ bar.setProgress(current);
+ bar.setVisibility(View.VISIBLE);
+ } else {
+ hideAllItems();
+ downloaded.setVisibility(View.VISIBLE);
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
+ enabledH264(true);
+ 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() {
- hideAllItems();
- downloaded.setText("Sorry an error has occurred.");
- downloaded.setVisibility(View.VISIBLE);
- ok.setVisibility(View.VISIBLE);
- enabledH264(false);
- AssistantActivity.instance().endDownloadCodec();
- }
- });
- }
- };
+ @Override
+ public void OnError(final String error) {
+ mHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ hideAllItems();
+ downloaded.setText("Sorry an error has occurred.");
+ downloaded.setVisibility(View.VISIBLE);
+ ok.setVisibility(View.VISIBLE);
+ enabledH264(false);
+ AssistantActivity.instance().endDownloadCodec();
+ }
+ });
+ }
+ };
- codecDownloader.setOpenH264HelperListener(codecListener);
+ codecDownloader.setOpenH264HelperListener(codecListener);
- yes.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- hideAllItems();
- bar.setVisibility(View.VISIBLE);
- codecDownloader.downloadCodec();
- }
- });
+ yes.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ hideAllItems();
+ bar.setVisibility(View.VISIBLE);
+ codecDownloader.downloadCodec();
+ }
+ });
- no.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- enabledH264(false);
- AssistantActivity.instance().endDownloadCodec();
- }
- });
- hideAllItems();
+ no.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ enabledH264(false);
+ AssistantActivity.instance().endDownloadCodec();
+ }
+ });
+ hideAllItems();
- if (savedInstanceState != null) {
- if (savedInstanceState.containsKey("question"))
- question.setVisibility((Integer) savedInstanceState.getSerializable("question"));
- else
- question.setVisibility(View.VISIBLE);
+ if (savedInstanceState != null) {
+ if (savedInstanceState.containsKey("question"))
+ question.setVisibility((Integer) savedInstanceState.getSerializable("question"));
+ else
+ question.setVisibility(View.VISIBLE);
- if (savedInstanceState.containsKey("yes"))
- yes.setVisibility((Integer) savedInstanceState.getSerializable("yes"));
- else
- yes.setVisibility(View.VISIBLE);
+ if (savedInstanceState.containsKey("yes"))
+ yes.setVisibility((Integer) savedInstanceState.getSerializable("yes"));
+ else
+ yes.setVisibility(View.VISIBLE);
- if (savedInstanceState.containsKey("no"))
- no.setVisibility((Integer) savedInstanceState.getSerializable("no"));
- else
- no.setVisibility(View.VISIBLE);
+ if (savedInstanceState.containsKey("no"))
+ no.setVisibility((Integer) savedInstanceState.getSerializable("no"));
+ else
+ no.setVisibility(View.VISIBLE);
- if (savedInstanceState.containsKey("downloading"))
- downloading.setVisibility((Integer) savedInstanceState.getSerializable("downloading"));
+ if (savedInstanceState.containsKey("downloading"))
+ downloading.setVisibility((Integer) savedInstanceState.getSerializable("downloading"));
- if (savedInstanceState.containsKey("downloaded"))
- downloaded.setVisibility((Integer) savedInstanceState.getSerializable("downloaded"));
+ if (savedInstanceState.containsKey("downloaded"))
+ downloaded.setVisibility((Integer) savedInstanceState.getSerializable("downloaded"));
- if (savedInstanceState.containsKey("context_bar"))
- bar.setVisibility((Integer) savedInstanceState.getSerializable("context_bar"));
+ if (savedInstanceState.containsKey("context_bar"))
+ bar.setVisibility((Integer) savedInstanceState.getSerializable("context_bar"));
- if (savedInstanceState.containsKey("downloadingInfo"))
- downloadingInfo.setVisibility((Integer) savedInstanceState.getSerializable("downloadingInfo"));
+ if (savedInstanceState.containsKey("downloadingInfo"))
+ downloadingInfo.setVisibility((Integer) savedInstanceState.getSerializable("downloadingInfo"));
- if (savedInstanceState.containsKey("ok"))
- ok.setVisibility((Integer) savedInstanceState.getSerializable("ok"));
- } else {
- yes.setVisibility(View.VISIBLE);
- question.setVisibility(View.VISIBLE);
- no.setVisibility(View.VISIBLE);
- }
+ if (savedInstanceState.containsKey("ok"))
+ ok.setVisibility((Integer) savedInstanceState.getSerializable("ok"));
+ } else {
+ yes.setVisibility(View.VISIBLE);
+ question.setVisibility(View.VISIBLE);
+ no.setVisibility(View.VISIBLE);
+ }
- return view;
- }
+ return view;
+ }
- @Override
- public void onSaveInstanceState(Bundle outState) {
- if (question != null) outState.putSerializable("question", question.getVisibility());
- if (downloading != null) outState.putSerializable("downloading", downloading.getVisibility());
- if (downloaded != null) outState.putSerializable("downloaded", downloaded.getVisibility());
- if (yes != null) outState.putSerializable("yes", yes.getVisibility());
- if (no != null) outState.putSerializable("no", no.getVisibility());
- if (ok != null) outState.putSerializable("ok", ok.getVisibility());
- if (bar != null) outState.putSerializable("context_bar", bar.getVisibility());
- if (downloadingInfo != null) outState.putSerializable("downloadingInfo", downloadingInfo.getVisibility());
- super.onSaveInstanceState(outState);
- }
+ @Override
+ public void onSaveInstanceState(Bundle outState) {
+ if (question != null) outState.putSerializable("question", question.getVisibility());
+ if (downloading != null)
+ outState.putSerializable("downloading", downloading.getVisibility());
+ if (downloaded != null) outState.putSerializable("downloaded", downloaded.getVisibility());
+ if (yes != null) outState.putSerializable("yes", yes.getVisibility());
+ if (no != null) outState.putSerializable("no", no.getVisibility());
+ if (ok != null) outState.putSerializable("ok", ok.getVisibility());
+ if (bar != null) outState.putSerializable("context_bar", bar.getVisibility());
+ if (downloadingInfo != null)
+ outState.putSerializable("downloadingInfo", downloadingInfo.getVisibility());
+ super.onSaveInstanceState(outState);
+ }
- private void hideAllItems() {
- if (question != null) question.setVisibility(View.INVISIBLE);
- if (downloading != null) downloading.setVisibility(View.INVISIBLE);
- if (downloaded != null) downloaded.setVisibility(View.INVISIBLE);
- if (yes != null) yes.setVisibility(View.INVISIBLE);
- if (no != null) no.setVisibility(View.INVISIBLE);
- if (ok != null) ok.setVisibility(View.INVISIBLE);
- if (bar != null) bar.setVisibility(View.INVISIBLE);
- if (downloadingInfo != null) downloadingInfo.setVisibility(View.INVISIBLE);
- }
+ private void hideAllItems() {
+ if (question != null) question.setVisibility(View.INVISIBLE);
+ if (downloading != null) downloading.setVisibility(View.INVISIBLE);
+ if (downloaded != null) downloaded.setVisibility(View.INVISIBLE);
+ if (yes != null) yes.setVisibility(View.INVISIBLE);
+ if (no != null) no.setVisibility(View.INVISIBLE);
+ if (ok != null) ok.setVisibility(View.INVISIBLE);
+ if (bar != null) bar.setVisibility(View.INVISIBLE);
+ if (downloadingInfo != null) downloadingInfo.setVisibility(View.INVISIBLE);
+ }
- private void enabledH264(boolean enable) {
- PayloadType h264 = null;
- for (PayloadType pt : LinphoneManager.getLc().getVideoPayloadTypes()) {
- if (pt.getMimeType().equals("H264")) h264 = pt;
- }
+ private void enabledH264(boolean enable) {
+ PayloadType h264 = null;
+ for (PayloadType pt : LinphoneManager.getLc().getVideoPayloadTypes()) {
+ if (pt.getMimeType().equals("H264")) h264 = pt;
+ }
- if (h264 != null) {
- h264.enable(enable);
- }
- }
+ if (h264 != null) {
+ h264.enable(enable);
+ }
+ }
}
diff --git a/src/android/org/linphone/assistant/CountryListFragment.java b/src/android/org/linphone/assistant/CountryListFragment.java
index b1c813370..93a1a2eff 100644
--- a/src/android/org/linphone/assistant/CountryListFragment.java
+++ b/src/android/org/linphone/assistant/CountryListFragment.java
@@ -19,9 +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 org.linphone.R;
-import org.linphone.core.DialPlan;
-
import android.app.Fragment;
import android.os.Bundle;
import android.text.Editable;
@@ -34,59 +31,62 @@ import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
+import org.linphone.R;
+import org.linphone.core.DialPlan;
+
public class CountryListFragment extends Fragment implements AdapterView.OnItemClickListener, View.OnClickListener {
- private ListView list;
- private EditText search;
- private ImageView clearSearchField;
- private AssistantActivity.CountryListAdapter adapter;
+ private ListView list;
+ private EditText search;
+ private ImageView clearSearchField;
+ private AssistantActivity.CountryListAdapter adapter;
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container,
+ Bundle savedInstanceState) {
- View view = inflater.inflate(R.layout.assistant_country_list, container, false);
- adapter = AssistantActivity.instance().getCountryListAdapter();
- adapter.setInflater(inflater);
+ View view = inflater.inflate(R.layout.assistant_country_list, container, false);
+ adapter = AssistantActivity.instance().getCountryListAdapter();
+ adapter.setInflater(inflater);
- search = view.findViewById(R.id.search_country);
- clearSearchField = view.findViewById(R.id.clearSearchField);
- clearSearchField.setOnClickListener(this);
+ search = view.findViewById(R.id.search_country);
+ clearSearchField = view.findViewById(R.id.clearSearchField);
+ clearSearchField.setOnClickListener(this);
- list = view.findViewById(R.id.countryList);
- list.setAdapter(adapter);
- list.setOnItemClickListener(this);
+ list = view.findViewById(R.id.countryList);
+ list.setAdapter(adapter);
+ list.setOnItemClickListener(this);
- search.addTextChangedListener(new TextWatcher() {
- @Override
- public void beforeTextChanged(CharSequence s, int start, int count, int after) {
- }
+ search.addTextChangedListener(new TextWatcher() {
+ @Override
+ public void beforeTextChanged(CharSequence s, int start, int count, int after) {
+ }
- @Override
- public void onTextChanged(CharSequence s, int start, int before, int count) {
- adapter.getFilter().filter(s);
- }
+ @Override
+ public void onTextChanged(CharSequence s, int start, int before, int count) {
+ adapter.getFilter().filter(s);
+ }
- @Override
- public void afterTextChanged(Editable s) {
+ @Override
+ public void afterTextChanged(Editable s) {
- }
- });
- search.setText("");
+ }
+ });
+ search.setText("");
- return view;
- }
+ return view;
+ }
- @Override
- public void onItemClick(AdapterView> parent, View view, int position, long id) {
- DialPlan c = (DialPlan) view.getTag();
- AssistantActivity.instance().country = c;
- AssistantActivity.instance().onBackPressed();
- }
+ @Override
+ public void onItemClick(AdapterView> parent, View view, int position, long id) {
+ DialPlan c = (DialPlan) view.getTag();
+ AssistantActivity.instance().country = c;
+ AssistantActivity.instance().onBackPressed();
+ }
- @Override
- public void onClick(View v) {
- if(v.getId() == R.id.clearSearchField) {
- search.setText("");
- }
- }
+ @Override
+ public void onClick(View v) {
+ if (v.getId() == R.id.clearSearchField) {
+ search.setText("");
+ }
+ }
}
diff --git a/src/android/org/linphone/assistant/CreateAccountActivationFragment.java b/src/android/org/linphone/assistant/CreateAccountActivationFragment.java
index 5fbcac97a..bd0a15b06 100644
--- a/src/android/org/linphone/assistant/CreateAccountActivationFragment.java
+++ b/src/android/org/linphone/assistant/CreateAccountActivationFragment.java
@@ -17,6 +17,7 @@ You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
+
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
@@ -34,92 +35,92 @@ import org.linphone.core.AccountCreator;
import org.linphone.core.AccountCreatorListener;
public class CreateAccountActivationFragment extends Fragment implements OnClickListener, AccountCreatorListener {
- private String username, password;
- private Button checkAccount;
- private TextView email;
- private AccountCreator accountCreator;
+ private String username, password;
+ private Button checkAccount;
+ private TextView email;
+ private AccountCreator accountCreator;
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- View view = inflater.inflate(R.layout.assistant_account_creation_email_activation, container, false);
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container,
+ Bundle savedInstanceState) {
+ View view = inflater.inflate(R.layout.assistant_account_creation_email_activation, container, false);
- accountCreator = LinphoneManager.getLc().createAccountCreator(LinphonePreferences.instance().getXmlrpcUrl());
- accountCreator.setListener(this);
+ accountCreator = LinphoneManager.getLc().createAccountCreator(LinphonePreferences.instance().getXmlrpcUrl());
+ accountCreator.setListener(this);
- username = getArguments().getString("Username");
- password = getArguments().getString("Password");
+ username = getArguments().getString("Username");
+ password = getArguments().getString("Password");
- accountCreator.setUsername(username);
- accountCreator.setPassword(password);
+ accountCreator.setUsername(username);
+ accountCreator.setPassword(password);
- email = view.findViewById(R.id.send_email);
- email.setText(getArguments().getString("Email"));
+ email = view.findViewById(R.id.send_email);
+ email.setText(getArguments().getString("Email"));
- checkAccount = view.findViewById(R.id.assistant_check);
- checkAccount.setOnClickListener(this);
- return view;
- }
+ checkAccount = view.findViewById(R.id.assistant_check);
+ checkAccount.setOnClickListener(this);
+ return view;
+ }
- @Override
- public void onClick(View v) {
- int id = v.getId();
- if(id == R.id.assistant_check) {
- checkAccount.setEnabled(false);
- accountCreator.isAccountActivated();
- }
- }
+ @Override
+ public void onClick(View v) {
+ int id = v.getId();
+ if (id == R.id.assistant_check) {
+ checkAccount.setEnabled(false);
+ accountCreator.isAccountActivated();
+ }
+ }
- @Override
- public void onIsAccountExist(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
- }
+ @Override
+ public void onIsAccountExist(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
+ }
- @Override
- public void onCreateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
- }
+ @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 onActivateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
+ }
- @Override
- public void onLinkAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
- }
+ @Override
+ public void onLinkAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
+ }
- @Override
- public void onActivateAlias(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
- }
+ @Override
+ public void onActivateAlias(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
+ }
- @Override
- public void onIsAccountActivated(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
- if (AssistantActivity.instance() == null) {
- return;
- }
- if (status.equals(AccountCreator.Status.AccountNotActivated)) {
- Toast.makeText(getActivity(), getString(R.string.assistant_account_not_validated), Toast.LENGTH_LONG).show();
- } else if (status.equals(AccountCreator.Status.AccountActivated)) {
- AssistantActivity.instance().linphoneLogIn(accountCreator);
- AssistantActivity.instance().isAccountVerified(username);
- } else {
- Toast.makeText(getActivity(), getString(R.string.wizard_server_unavailable), Toast.LENGTH_LONG).show();
- }
- checkAccount.setEnabled(true);
- }
+ @Override
+ public void onIsAccountActivated(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
+ if (AssistantActivity.instance() == null) {
+ return;
+ }
+ if (status.equals(AccountCreator.Status.AccountNotActivated)) {
+ Toast.makeText(getActivity(), getString(R.string.assistant_account_not_validated), Toast.LENGTH_LONG).show();
+ } else if (status.equals(AccountCreator.Status.AccountActivated)) {
+ AssistantActivity.instance().linphoneLogIn(accountCreator);
+ AssistantActivity.instance().isAccountVerified(username);
+ } else {
+ Toast.makeText(getActivity(), getString(R.string.wizard_server_unavailable), Toast.LENGTH_LONG).show();
+ }
+ checkAccount.setEnabled(true);
+ }
- @Override
- public void onRecoverAccount(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) {
- }
+ @Override
+ public void onIsAccountLinked(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
+ }
- @Override
- public void onIsAliasUsed(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
- }
+ @Override
+ public void onIsAliasUsed(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
+ }
- @Override
- public void onUpdateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
+ @Override
+ public void onUpdateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
- }
+ }
}
diff --git a/src/android/org/linphone/assistant/CreateAccountCodeActivationFragment.java b/src/android/org/linphone/assistant/CreateAccountCodeActivationFragment.java
index ae806beca..d327d3679 100644
--- a/src/android/org/linphone/assistant/CreateAccountCodeActivationFragment.java
+++ b/src/android/org/linphone/assistant/CreateAccountCodeActivationFragment.java
@@ -18,12 +18,6 @@ along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
-import org.linphone.LinphoneManager;
-import org.linphone.LinphonePreferences;
-import org.linphone.R;
-import org.linphone.core.AccountCreator;
-import org.linphone.core.AccountCreatorListener;
-
import android.app.Fragment;
import android.os.Bundle;
import android.text.Editable;
@@ -38,175 +32,183 @@ import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
+import org.linphone.LinphoneManager;
+import org.linphone.LinphonePreferences;
+import org.linphone.R;
+import org.linphone.core.AccountCreator;
+import org.linphone.core.AccountCreatorListener;
+
public class CreateAccountCodeActivationFragment extends Fragment implements AccountCreatorListener {
- private String username, phone, dialcode;
- private TextView title, phonenumber;
- private EditText code;
- private boolean recoverAccount = false, linkAccount = false;
- private int code_length, accountNumber;
- private ImageView back;
- private Button checkAccount;
- private AccountCreator accountCreator;
+ private String username, phone, dialcode;
+ private TextView title, phonenumber;
+ private EditText code;
+ private boolean recoverAccount = false, linkAccount = false;
+ private int code_length, accountNumber;
+ private ImageView back;
+ private Button checkAccount;
+ private AccountCreator accountCreator;
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- View view = inflater.inflate(R.layout.assistant_account_creation_code_activation, container, false);
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container,
+ Bundle savedInstanceState) {
+ View view = inflater.inflate(R.layout.assistant_account_creation_code_activation, container, false);
- username = getArguments().getString("Username");
- phone = getArguments().getString("Phone");
- dialcode = getArguments().getString("Dialcode");
- recoverAccount = getArguments().getBoolean("RecoverAccount");
- linkAccount = getArguments().getBoolean("LinkAccount");
- accountNumber = getArguments().getInt("AccountNumber");
+ username = getArguments().getString("Username");
+ phone = getArguments().getString("Phone");
+ dialcode = getArguments().getString("Dialcode");
+ recoverAccount = getArguments().getBoolean("RecoverAccount");
+ linkAccount = getArguments().getBoolean("LinkAccount");
+ accountNumber = getArguments().getInt("AccountNumber");
- code_length = LinphonePreferences.instance().getCodeLength();
- accountCreator = LinphoneManager.getLc().createAccountCreator(LinphonePreferences.instance().getXmlrpcUrl());
- accountCreator.setListener(this);
- accountCreator.setUsername(username);
- accountCreator.setPhoneNumber(phone, dialcode);
+ code_length = LinphonePreferences.instance().getCodeLength();
+ accountCreator = LinphoneManager.getLc().createAccountCreator(LinphonePreferences.instance().getXmlrpcUrl());
+ accountCreator.setListener(this);
+ accountCreator.setUsername(username);
+ accountCreator.setPhoneNumber(phone, dialcode);
- back = view.findViewById(R.id.back);
- if (back != null)
- back.setVisibility(Button.INVISIBLE);
+ back = view.findViewById(R.id.back);
+ if (back != null)
+ back.setVisibility(Button.INVISIBLE);
- title = view.findViewById(R.id.title_account_activation);
- if (linkAccount) {
- title.setText(getString(R.string.assistant_link_account));
- } else if (recoverAccount) {
- title.setText(getString(R.string.assistant_linphone_account));
- }
+ title = view.findViewById(R.id.title_account_activation);
+ if (linkAccount) {
+ title.setText(getString(R.string.assistant_link_account));
+ } else if (recoverAccount) {
+ title.setText(getString(R.string.assistant_linphone_account));
+ }
- phonenumber = view.findViewById(R.id.send_phone_number);
- phonenumber.setText(accountCreator.getPhoneNumber());
+ phonenumber = view.findViewById(R.id.send_phone_number);
+ phonenumber.setText(accountCreator.getPhoneNumber());
- code = view.findViewById(R.id.assistant_code);
- code.addTextChangedListener(new TextWatcher() {
- @Override
- public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
+ code = view.findViewById(R.id.assistant_code);
+ code.addTextChangedListener(new TextWatcher() {
+ @Override
+ public void beforeTextChanged(CharSequence s, int start, int count, int after) {
+ }
- @Override
- public void onTextChanged(CharSequence s, int start, int before, int count) {}
+ @Override
+ public void onTextChanged(CharSequence s, int start, int before, int count) {
+ }
- @Override
- public void afterTextChanged(Editable s) {
- if(s.length() == code_length){
- checkAccount.setEnabled(true);
- } else {
- checkAccount.setEnabled(false);
- }
- }
- });
+ @Override
+ public void afterTextChanged(Editable s) {
+ if (s.length() == code_length) {
+ checkAccount.setEnabled(true);
+ } else {
+ checkAccount.setEnabled(false);
+ }
+ }
+ });
- checkAccount = view.findViewById(R.id.assistant_check);
- checkAccount.setEnabled(false);
- checkAccount.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- checkAccount.setEnabled(false);
- accountCreator.setActivationCode(code.getText().toString());
- if(linkAccount){
- linkAccount();
- } else {
- activateAccount();
- }
- }
- });
+ checkAccount = view.findViewById(R.id.assistant_check);
+ checkAccount.setEnabled(false);
+ checkAccount.setOnClickListener(new OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ checkAccount.setEnabled(false);
+ accountCreator.setActivationCode(code.getText().toString());
+ if (linkAccount) {
+ linkAccount();
+ } else {
+ activateAccount();
+ }
+ }
+ });
- return view;
- }
+ return view;
+ }
- private void linkAccount(){
- accountCreator.setUsername(LinphonePreferences.instance().getAccountUsername(accountNumber));
- accountCreator.setHa1(LinphonePreferences.instance().getAccountHa1(accountNumber));
- accountCreator.activateAlias();
- }
+ private void linkAccount() {
+ accountCreator.setUsername(LinphonePreferences.instance().getAccountUsername(accountNumber));
+ accountCreator.setHa1(LinphonePreferences.instance().getAccountHa1(accountNumber));
+ accountCreator.activateAlias();
+ }
- private void activateAccount() {
- if(accountCreator.getUsername() == null){
- accountCreator.setUsername(accountCreator.getPhoneNumber());
- }
- accountCreator.activateAccount();
- }
+ private void activateAccount() {
+ if (accountCreator.getUsername() == null) {
+ accountCreator.setUsername(accountCreator.getPhoneNumber());
+ }
+ accountCreator.activateAccount();
+ }
- @Override
- public void onIsAccountExist(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
- }
+ @Override
+ public void onIsAccountExist(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
+ }
- @Override
- public void onCreateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
- }
+ @Override
+ public void onCreateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
+ }
- @Override
- public void onActivateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
- if (AssistantActivity.instance() == null) {
- return;
- }
- if (status.equals(AccountCreator.Status.AccountActivated)) {
- checkAccount.setEnabled(true);
- if (accountCreator.getUsername() != null) {
- AssistantActivity.instance().linphoneLogIn(accountCreator);
- if(!recoverAccount){
- AssistantActivity.instance().isAccountVerified(accountCreator.getUsername());
- } else {
- AssistantActivity.instance().success();
- }
- } else {
- AssistantActivity.instance().linphoneLogIn(accountCreator);
- if(!recoverAccount) {
- AssistantActivity.instance().isAccountVerified(accountCreator.getPhoneNumber());
- } else {
- AssistantActivity.instance().success();
- }
- }
- } else if (status.equals(AccountCreator.Status.RequestFailed)) {
- Toast.makeText(getActivity(), getString(R.string.wizard_server_unavailable), Toast.LENGTH_LONG).show();
- } else {
- Toast.makeText(getActivity(), getString(R.string.assistant_error_confirmation_code), Toast.LENGTH_LONG).show();
- AssistantActivity.instance().displayAssistantLinphoneLogin(phone, dialcode);
- }
- }
+ @Override
+ public void onActivateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
+ if (AssistantActivity.instance() == null) {
+ return;
+ }
+ if (status.equals(AccountCreator.Status.AccountActivated)) {
+ checkAccount.setEnabled(true);
+ if (accountCreator.getUsername() != null) {
+ AssistantActivity.instance().linphoneLogIn(accountCreator);
+ if (!recoverAccount) {
+ AssistantActivity.instance().isAccountVerified(accountCreator.getUsername());
+ } else {
+ AssistantActivity.instance().success();
+ }
+ } else {
+ AssistantActivity.instance().linphoneLogIn(accountCreator);
+ if (!recoverAccount) {
+ AssistantActivity.instance().isAccountVerified(accountCreator.getPhoneNumber());
+ } else {
+ AssistantActivity.instance().success();
+ }
+ }
+ } else if (status.equals(AccountCreator.Status.RequestFailed)) {
+ Toast.makeText(getActivity(), getString(R.string.wizard_server_unavailable), Toast.LENGTH_LONG).show();
+ } else {
+ Toast.makeText(getActivity(), getString(R.string.assistant_error_confirmation_code), Toast.LENGTH_LONG).show();
+ AssistantActivity.instance().displayAssistantLinphoneLogin(phone, dialcode);
+ }
+ }
- @Override
- public void onLinkAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
+ @Override
+ public void onLinkAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
- }
+ }
- @Override
- public void onActivateAlias(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
- if (AssistantActivity.instance() == null) {
- return;
- }
- if(status.equals(AccountCreator.Status.AccountActivated)){
- LinphonePreferences.instance().setPrefix(accountNumber, org.linphone.core.Utils.getPrefixFromE164(accountCreator.getPhoneNumber()));
- LinphonePreferences.instance().setLinkPopupTime("");
- AssistantActivity.instance().hideKeyboard();
- AssistantActivity.instance().success();
- }
- }
+ @Override
+ public void onActivateAlias(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
+ if (AssistantActivity.instance() == null) {
+ return;
+ }
+ if (status.equals(AccountCreator.Status.AccountActivated)) {
+ LinphonePreferences.instance().setPrefix(accountNumber, org.linphone.core.Utils.getPrefixFromE164(accountCreator.getPhoneNumber()));
+ LinphonePreferences.instance().setLinkPopupTime("");
+ AssistantActivity.instance().hideKeyboard();
+ AssistantActivity.instance().success();
+ }
+ }
- @Override
- public void onIsAccountActivated(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 onRecoverAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
+ }
- @Override
- public void onIsAccountLinked(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
+ @Override
+ public void onIsAccountLinked(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
- }
+ }
- @Override
- public void onIsAliasUsed(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
+ @Override
+ public void onIsAliasUsed(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
- }
+ }
- @Override
- public void onUpdateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
+ @Override
+ public void onUpdateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
- }
+ }
}
diff --git a/src/android/org/linphone/assistant/CreateAccountFragment.java b/src/android/org/linphone/assistant/CreateAccountFragment.java
index b571a7143..80ce6dd08 100644
--- a/src/android/org/linphone/assistant/CreateAccountFragment.java
+++ b/src/android/org/linphone/assistant/CreateAccountFragment.java
@@ -18,20 +18,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.util.Locale;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.linphone.LinphoneManager;
-import org.linphone.LinphonePreferences;
-import org.linphone.LinphoneUtils;
-import org.linphone.R;
-import org.linphone.core.DialPlan;
-import org.linphone.core.AccountCreator;
-import org.linphone.core.AccountCreatorListener;
-import org.linphone.core.AccountCreator.Status;
-import org.linphone.core.ProxyConfig;
-
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.AlertDialog;
@@ -55,651 +41,660 @@ import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
+import org.linphone.LinphoneManager;
+import org.linphone.LinphonePreferences;
+import org.linphone.LinphoneUtils;
+import org.linphone.R;
+import org.linphone.core.AccountCreator;
+import org.linphone.core.AccountCreator.Status;
+import org.linphone.core.AccountCreatorListener;
+import org.linphone.core.DialPlan;
+
+import java.util.Locale;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
public class CreateAccountFragment extends Fragment implements CompoundButton.OnCheckedChangeListener
- , OnClickListener, AccountCreatorListener {
- private EditText phoneNumberEdit, usernameEdit, passwordEdit, passwordConfirmEdit
- , emailEdit, dialCode;
- private TextView phoneNumberError, passwordError, passwordConfirmError
- , emailError, assisstantTitle, sipUri, skip, instruction;
- private ImageView phoneNumberInfo;
-
- private boolean passwordOk = false;
- private boolean emailOk = false;
- private boolean confirmPasswordOk = false;
- private boolean linkAccount = false;
- private Button createAccount, selectCountry;
- private CheckBox useUsername, useEmail;
- private String addressSip = "";
- private int countryCode;
- private LinearLayout phoneNumberLayout, usernameLayout, emailLayout, passwordLayout, passwordConfirmLayout;
- private final Pattern UPPER_CASE_REGEX = Pattern.compile("[A-Z]");
- private AccountCreator accountCreator;
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
- View view = inflater.inflate(R.layout.assistant_account_creation, container, false);
-
- //Initialize accountCreator
- accountCreator = LinphoneManager.getLc().createAccountCreator(LinphonePreferences.instance().getXmlrpcUrl());
- accountCreator.setListener(this);
-
- instruction = view.findViewById(R.id.message_create_account);
-
- createAccount = view.findViewById(R.id.assistant_create);
-
- phoneNumberLayout = view.findViewById(R.id.phone_number_layout);
- usernameLayout = view.findViewById(R.id.username_layout);
- emailLayout = view.findViewById(R.id.email_layout);
- passwordLayout = view.findViewById(R.id.password_layout);
- passwordConfirmLayout = view.findViewById(R.id.password_confirm_layout);
-
- useUsername = view.findViewById(R.id.use_username);
- useEmail = view.findViewById(R.id.use_email);
-
- usernameEdit = view.findViewById(R.id.username);
-
- phoneNumberError = view.findViewById(R.id.phone_number_error);
- phoneNumberEdit = view.findViewById(R.id.phone_number);
- sipUri = view.findViewById(R.id.sip_uri);
-
- phoneNumberInfo = view.findViewById(R.id.info_phone_number);
-
- selectCountry = view.findViewById(R.id.select_country);
- dialCode = view.findViewById(R.id.dial_code);
- assisstantTitle = view.findViewById(R.id.assistant_title);
-
- passwordError = view.findViewById(R.id.password_error);
- passwordEdit = view.findViewById(R.id.password);
-
- passwordConfirmError = view.findViewById(R.id.confirm_password_error);
- passwordConfirmEdit = view.findViewById(R.id.confirm_password);
-
- emailError = view.findViewById(R.id.email_error);
- emailEdit = view.findViewById(R.id.email);
-
- skip = view.findViewById(R.id.assistant_skip);
-
- //Phone number
- if (getResources().getBoolean(R.bool.use_phone_number_validation)) {
- getActivity().getApplicationContext();
- //Automatically get the country code from the phone
- TelephonyManager tm =
- (TelephonyManager) getActivity().getApplicationContext().getSystemService(
- Context.TELEPHONY_SERVICE);
- String countryIso = tm.getNetworkCountryIso();
- countryCode = org.linphone.core.Utils.getCccFromIso(countryIso.toUpperCase());
-
- phoneNumberLayout.setVisibility(View.VISIBLE);
-
- phoneNumberInfo.setOnClickListener(this);
- selectCountry.setOnClickListener(this);
-
- String previousPhone = AssistantActivity.instance().phone_number;
- if (previousPhone != null ) {
- phoneNumberEdit.setText(previousPhone);
- }
- DialPlan c = AssistantActivity.instance().country;
- if (c != null) {
- selectCountry.setText(c.getCountry());
- dialCode.setText(c.getCountryCallingCode().contains("+") ?
- c.getCountryCallingCode() : "+" + c.getCountryCallingCode());
- } else {
- c = AssistantActivity.instance().getCountryListAdapter()
- .getCountryFromCountryCode(String.valueOf(countryCode));
- if (c != null) {
- selectCountry.setText(c.getCountry());
- dialCode.setText(c.getCountryCallingCode().contains("+") ?
- c.getCountryCallingCode() : "+" + c.getCountryCallingCode());
- }
- }
-
- //Allow user to enter a username instead use the phone number as username
- if (getResources().getBoolean(R.bool.assistant_allow_username)) {
- useUsername.setVisibility(View.VISIBLE);
- useUsername.setOnCheckedChangeListener(this);
- }
- addPhoneNumberHandler(phoneNumberEdit, null);
- addPhoneNumberHandler(dialCode, null);
- }
-
- //Password & email address
- if (getResources().getBoolean(R.bool.isTablet)
- || !getResources().getBoolean(R.bool.use_phone_number_validation)) {
- useEmail.setVisibility(View.VISIBLE);
- useEmail.setOnCheckedChangeListener(this);
-
- if (getResources().getBoolean(R.bool.pre_fill_email_in_assistant)) {
- Account[] accounts = AccountManager.get(getActivity()).getAccountsByType("com.google");
-
- for (Account account: accounts) {
- if (isEmailCorrect(account.name)) {
- String possibleEmail = account.name;
- emailEdit.setText(possibleEmail);
- accountCreator.setEmail(possibleEmail);
- emailOk = true;
- break;
- }
- }
- }
-
- addPasswordHandler(passwordEdit, null);
- addConfirmPasswordHandler(passwordEdit, passwordConfirmEdit, null);
- addEmailHandler(emailEdit, null);
- }
-
- //Hide phone number and display username/email/password
- if (!getResources().getBoolean(R.bool.use_phone_number_validation)) {
- useEmail.setVisibility(View.GONE);
- useUsername.setVisibility(View.GONE);
-
- usernameLayout.setVisibility(View.VISIBLE);
- passwordLayout.setVisibility(View.VISIBLE);
- passwordConfirmLayout.setVisibility(View.VISIBLE);
- emailLayout.setVisibility(View.VISIBLE);
- }
-
- //Link account with phone number
- if (getArguments().getBoolean("LinkPhoneNumber")) {
- linkAccount = true;
- useEmail.setVisibility(View.GONE);
- useUsername.setVisibility(View.GONE);
-
- usernameLayout.setVisibility(View.GONE);
- passwordLayout.setVisibility(View.GONE);
- passwordConfirmLayout.setVisibility(View.GONE);
- emailLayout.setVisibility(View.GONE);
-
- skip.setVisibility(View.VISIBLE);
- skip.setOnClickListener(this);
-
- createAccount.setText(getResources().getString(R.string.link_account));
- assisstantTitle.setText(getResources().getString(R.string.link_account));
- }
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
- accountCreator.setLanguage(Locale.getDefault().toLanguageTag());
- }
-
- addUsernameHandler(usernameEdit, null);
-
- createAccount.setEnabled(true);
- createAccount.setOnClickListener(this);
-
- return view;
- }
-
- @Override
- public void onPause() {
- super.onPause();
- accountCreator.setListener(null);
- }
-
- private String getUsername() {
- if(usernameEdit != null) {
- String username = usernameEdit.getText().toString();
- return username.toLowerCase(Locale.getDefault());
- }
- return null;
- }
-
- @Override
- public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
- if (buttonView.getId() == R.id.use_username) {
- if (isChecked) {
- usernameLayout.setVisibility(View.VISIBLE);
- onTextChanged2();
- } else {
- usernameLayout.setVisibility(View.GONE);
- accountCreator.setUsername(null);
- onTextChanged2();
- }
- } else if (buttonView.getId() == R.id.use_email) {
- if (isChecked) {
- dialCode.setBackgroundResource(R.drawable.resizable_textfield);
- phoneNumberEdit.setBackgroundResource(R.drawable.resizable_textfield);
- useUsername.setEnabled(false);
- dialCode.setEnabled(false);
- selectCountry.setEnabled(false);
- phoneNumberEdit.setEnabled(false);
- emailLayout.setVisibility(View.VISIBLE);
- passwordLayout.setVisibility(View.VISIBLE);
- passwordConfirmLayout.setVisibility(View.VISIBLE);
- usernameLayout.setVisibility(View.VISIBLE);
- useUsername.setVisibility(CheckBox.GONE);
- phoneNumberLayout.setVisibility(LinearLayout.GONE);
- instruction.setText(getString(R.string.assistant_create_account_part_email));
- } else {
- if (!useUsername.isChecked()) {
- usernameLayout.setVisibility(View.GONE);
- }
- useUsername.setEnabled(true);
- dialCode.setEnabled(true);
- selectCountry.setEnabled(true);
- phoneNumberEdit.setEnabled(true);
- emailLayout.setVisibility(View.GONE);
- passwordLayout.setVisibility(View.GONE);
- passwordConfirmLayout.setVisibility(View.GONE);
- useUsername.setVisibility(CheckBox.VISIBLE);
- phoneNumberLayout.setVisibility(LinearLayout.VISIBLE);
- instruction.setText(getString(R.string.assistant_create_account_part_1));
- }
- }
- }
-
- @Override
- public void onClick(View v) {
- int id = v.getId();
- if(id == R.id.select_country){
- AssistantActivity.instance().displayCountryChooser();
- }
- else if (id == R.id.assistant_skip){
- if (getArguments().getBoolean("LinkFromPref")) {
- AssistantActivity.instance().finish();
- } else {
- AssistantActivity.instance().success();
- }
- }
- else if(id == R.id.info_phone_number){
- if (linkAccount) {
- new AlertDialog.Builder(getActivity())
- .setTitle(getString(R.string.phone_number_info_title))
- .setMessage(getString(R.string.phone_number_link_info_content) + "\n"
- + getString(R.string.phone_number_link_info_content_already_account))
- .show();
- } else {
- new AlertDialog.Builder(getActivity())
- .setTitle(getString(R.string.phone_number_info_title))
- .setMessage(getString(R.string.phone_number_info_content))
- .show();
- }
- }
- else if(id == R.id.assistant_create){
- createAccount.setEnabled(false);
- if (linkAccount) {
- addAlias();
- } else {
- if (useEmail.isChecked()) accountCreator.setPhoneNumber(null, null);
- if (!getResources().getBoolean(R.bool.isTablet) || getUsername().length() > 0) {
- LinphoneManager.getLc().getConfig().loadFromXmlFile(LinphoneManager.getInstance().getmDynamicConfigFile());
- accountCreator.isAccountExist();
- } else {
- LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForUsernameStatus(AccountCreator.UsernameStatus.TooShort)
- , AssistantActivity.instance());
- createAccount.setEnabled(true);
- }
- }
- }
- }
-
- private boolean isEmailCorrect(String email) {
- Pattern emailPattern = Patterns.EMAIL_ADDRESS;
- return emailPattern.matcher(email).matches();
- }
-
- private boolean isPasswordCorrect(String password) {
- return password.length() >= 1;
- }
-
- private void addAlias() {
- accountCreator.setUsername(LinphonePreferences.instance().getAccountUsername(
- LinphonePreferences.instance().getDefaultAccountIndex())
- );
- int status = accountCreator.setPhoneNumber(
- phoneNumberEdit.getText().toString(), LinphoneUtils.getCountryCode(dialCode));
- boolean isOk = status == AccountCreator.PhoneNumberStatus.Ok.toInt();
- if (isOk) {
- accountCreator.linkAccount();
- } else {
- createAccount.setEnabled(true);
- LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForPhoneNumberStatus(status), AssistantActivity.instance());
- LinphoneUtils.displayError(isOk, phoneNumberError, LinphoneUtils.errorForPhoneNumberStatus(status));
- }
- }
-
- private void createAccount() {
- if ((getResources().getBoolean(R.bool.isTablet) || !getResources().getBoolean(R.bool.use_phone_number_validation))
- && useEmail.isChecked()) {
- AccountCreator.EmailStatus emailStatus;
- AccountCreator.PasswordStatus passwordStatus;
-
- passwordStatus = accountCreator.setPassword(passwordEdit.getText().toString());
- emailStatus = accountCreator.setEmail(emailEdit.getText().toString());
-
- if (!emailOk) {
- LinphoneUtils.displayError(false, emailError, LinphoneUtils.errorForEmailStatus(emailStatus));
- LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForEmailStatus(emailStatus)
- , AssistantActivity.instance());
- } else if (!passwordOk) {
- LinphoneUtils.displayError(false, passwordError, LinphoneUtils.errorForPasswordStatus(passwordStatus));
- LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForPasswordStatus(passwordStatus)
- , AssistantActivity.instance());
- } else if (!confirmPasswordOk) {
- String msg;
- if (passwordConfirmEdit.getText().toString().equals(passwordEdit.getText().toString())) {
- msg = getString(R.string.wizard_password_incorrect);
- } else {
- msg = getString(R.string.wizard_passwords_unmatched);
- }
- LinphoneUtils.displayError(false, passwordError, msg);
- LinphoneUtils.displayErrorAlert(msg, AssistantActivity.instance());
- } else {
- accountCreator.createAccount();
- }
- } else {
- if (phoneNumberEdit.length() > 0 || dialCode.length() > 1) {
- int phoneStatus;
- boolean isOk;
- phoneStatus = accountCreator.setPhoneNumber(
- phoneNumberEdit.getText().toString(), LinphoneUtils.getCountryCode(dialCode));
- isOk = phoneStatus == AccountCreator.PhoneNumberStatus.Ok.toInt();
- if (!useUsername.isChecked() && accountCreator.getUsername() == null) {
- accountCreator.setUsername(accountCreator.getPhoneNumber());
- } else {
- accountCreator.setUsername(usernameEdit.getText().toString());
- accountCreator.setPhoneNumber(
- phoneNumberEdit.getText().toString(), dialCode.getText().toString());
- }
- if (isOk) {
- accountCreator.createAccount();
- } else {
- LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForPhoneNumberStatus(phoneStatus)
- , AssistantActivity.instance());
- LinphoneUtils.displayError(isOk, phoneNumberError
- , LinphoneUtils.errorForPhoneNumberStatus(phoneStatus));
- }
- } else {
- LinphoneUtils.displayErrorAlert(getString(R.string.assistant_create_account_part_1)
- , AssistantActivity.instance());
- }
- }
- createAccount.setEnabled(true);
- }
-
- private int getPhoneNumberStatus() {
- int status = accountCreator.setPhoneNumber(
- phoneNumberEdit.getText().toString(), LinphoneUtils.getCountryCode(dialCode));
- addressSip = accountCreator.getPhoneNumber();
- return status;
- }
-
- public void onTextChanged2() {
- String msg = "";
- accountCreator.setUsername(getUsername());
-
- if (!useEmail.isChecked() && getResources().getBoolean(R.bool.use_phone_number_validation)) {
- int status = getPhoneNumberStatus();
- boolean isOk = (status == AccountCreator.PhoneNumberStatus.Ok.toInt());
- LinphoneUtils.displayError(isOk, phoneNumberError, LinphoneUtils.errorForPhoneNumberStatus(status));
-
- // Username or phone number
- if (getResources().getBoolean(R.bool.assistant_allow_username) && useUsername.isChecked()) {
- addressSip = getUsername();
- }
-
- if (!isOk) {
- if (status == AccountCreator.PhoneNumberStatus.InvalidCountryCode.toInt()) {
- dialCode.setBackgroundResource(R.drawable.resizable_textfield_error);
- phoneNumberEdit.setBackgroundResource(R.drawable.resizable_textfield);
- } else {
- dialCode.setBackgroundResource(R.drawable.resizable_textfield);
- phoneNumberEdit.setBackgroundResource(R.drawable.resizable_textfield_error);
- }
-
- } else {
- dialCode.setBackgroundResource(R.drawable.resizable_textfield);
- phoneNumberEdit.setBackgroundResource(R.drawable.resizable_textfield);
- if (!linkAccount && addressSip.length() > 0) {
- msg = getResources().getString(R.string.assistant_create_account_phone_number_address)
- + " <" + addressSip + "@" + getResources().getString(R.string.default_domain) + ">";
- }
- }
- } else {
- addressSip = getUsername();
- if (addressSip.length() > 0) {
- msg = getResources().getString(R.string.assistant_create_account_phone_number_address)
- + " ";
- }
- }
- sipUri.setText(msg);
- }
-
- private void addPhoneNumberHandler(final EditText field, final ImageView icon) {
- field.addTextChangedListener(new TextWatcher() {
- public void afterTextChanged(Editable s) {
- if (field.equals(dialCode)) {
- DialPlan c = AssistantActivity.instance().getCountryListAdapter()
- .getCountryFromCountryCode(dialCode.getText().toString());
- if (c != null) {
- AssistantActivity.instance().country = c;
- selectCountry.setText(c.getCountry());
- } else {
- selectCountry.setText(R.string.select_your_country);
- }
- }
- }
-
- public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
-
- public void onTextChanged(CharSequence s, int start, int count, int after) {
- onTextChanged2();
- }
- });
- }
-
- private void addUsernameHandler(final EditText field, final ImageView icon) {
- field.addTextChangedListener(new TextWatcher() {
- public void afterTextChanged(Editable s) {
- Matcher matcher = UPPER_CASE_REGEX.matcher(s);
- while (matcher.find()) {
- CharSequence upperCaseRegion = s.subSequence(matcher.start(), matcher.end());
- s.replace(matcher.start(), matcher.end(), upperCaseRegion.toString().toLowerCase());
- }
- }
-
- public void beforeTextChanged(CharSequence s, int start, int count, int after) {
- }
-
- public void onTextChanged(CharSequence s, int start, int count, int after) {
- onTextChanged2();
- }
- });
- }
-
- private void addEmailHandler(final EditText field, final ImageView icon) {
- field.addTextChangedListener(new TextWatcher() {
- public void afterTextChanged(Editable s) {
- emailOk = false;
- AccountCreator.EmailStatus status = accountCreator.setEmail(field.getText().toString());
- if (status.equals(AccountCreator.EmailStatus.Ok)) {
- emailOk = true;
- LinphoneUtils.displayError(emailOk, emailError, "");
- }
- else {
- LinphoneUtils.displayError(emailOk
- , emailError, LinphoneUtils.errorForEmailStatus(status));
- }
- }
-
- public void beforeTextChanged(CharSequence s, int start, int count, int after) {
- }
-
- public void onTextChanged(CharSequence s, int start, int count, int after) {
- }
- });
- }
-
- private void addPasswordHandler(final EditText field1, final ImageView icon) {
- TextWatcher passwordListener = new TextWatcher() {
- public void afterTextChanged(Editable s) {
- passwordOk = false;
- AccountCreator.PasswordStatus status = accountCreator.setPassword(field1.getText().toString());
- if (isPasswordCorrect(field1.getText().toString())) {
- passwordOk = true;
- LinphoneUtils.displayError(passwordOk, passwordError, "");
- } else {
- LinphoneUtils.displayError(passwordOk
- , passwordError, LinphoneUtils.errorForPasswordStatus(status));
- }
- }
-
- public void beforeTextChanged(CharSequence s, int start, int count, int after) {
- }
-
- public void onTextChanged(CharSequence s, int start, int count, int after) {
- }
- };
-
- field1.addTextChangedListener(passwordListener);
- }
-
- private void addConfirmPasswordHandler(final EditText field1, final EditText field2, final ImageView icon) {
- TextWatcher passwordListener = new TextWatcher() {
- public void afterTextChanged(Editable s) {
- confirmPasswordOk = false;
- if (field1.getText().toString().equals(field2.getText().toString())) {
- confirmPasswordOk = true;
- if (!isPasswordCorrect(field1.getText().toString())) {
- LinphoneUtils.displayError(passwordOk
- , passwordError, getString(R.string.wizard_password_incorrect));
- } else {
- LinphoneUtils.displayError(confirmPasswordOk, passwordConfirmError, "");
- }
- } else {
- LinphoneUtils.displayError(confirmPasswordOk
- , passwordConfirmError, getString(R.string.wizard_passwords_unmatched));
- }
- }
-
- public void beforeTextChanged(CharSequence s, int start, int count, int after) {
- }
-
- public void onTextChanged(CharSequence s, int start, int count, int after) {}
- };
- field1.addTextChangedListener(passwordListener);
- field2.addTextChangedListener(passwordListener);
- }
-
- @Override
- public void onIsAccountExist(AccountCreator accountCreator, final Status status, String resp) {
- if (status.equals(Status.AccountExist) || status.equals(Status.AccountExistWithAlias)) {
- if (useEmail.isChecked()) {
- createAccount.setEnabled(true);
- LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForStatus(status)
- , AssistantActivity.instance());
- } else {
- LinphoneManager.getLc().getConfig().loadFromXmlFile(LinphoneManager.getInstance().getmDynamicConfigFile());
- accountCreator.isAliasUsed();
- }
- } else {
- createAccount();
- }
- }
-
- @Override
- public void onCreateAccount(AccountCreator accountCreator, Status status, String resp) {
- if (status.equals(Status.AccountCreated)) {
- if (useEmail.isChecked() || !getResources().getBoolean(R.bool.use_phone_number_validation)) {
- AssistantActivity.instance().displayAssistantConfirm(getUsername()
- , passwordEdit.getText().toString(), emailEdit.getText().toString());
- } else {
- AssistantActivity.instance().displayAssistantCodeConfirm(getUsername()
- , phoneNumberEdit.getText().toString()
- , LinphoneUtils.getCountryCode(dialCode), false);
- }
- } else {
- createAccount.setEnabled(true);
- LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForStatus(status)
- , AssistantActivity.instance());
- }
- }
-
- @Override
- public void onActivateAccount(AccountCreator accountCreator, Status status, String resp) {
- }
-
- @Override
- public void onLinkAccount(AccountCreator accountCreator, Status status, String resp) {
- if (AssistantActivity.instance() == null) {
- return;
- }
- if (status.equals(Status.RequestOk)) {
- AssistantActivity.instance().displayAssistantCodeConfirm(getUsername()
- , phoneNumberEdit.getText().toString()
- , LinphoneUtils.getCountryCode(dialCode), false);
- }
- }
-
- @Override
- public void onActivateAlias(AccountCreator accountCreator, Status status, String resp) {
- if (AssistantActivity.instance() == null) {
- return;
- }
- if (status.equals(Status.RequestOk)) {
- AssistantActivity.instance().displayAssistantCodeConfirm(getUsername()
- , phoneNumberEdit.getText().toString()
- , LinphoneUtils.getCountryCode(dialCode), false);
- }
- }
-
- @Override
- public void onIsAccountActivated(AccountCreator accountCreator, Status status, String resp) {
- if (AssistantActivity.instance() == null) {
- return;
- }
- if (status.equals(Status.AccountNotActivated)) {
- if (getResources().getBoolean(R.bool.isTablet)
- || !getResources().getBoolean(R.bool.use_phone_number_validation)) {
- //accountCreator.activateAccount(); // Resend email TODO
- } else {
- accountCreator.recoverAccount(); // Resend SMS
- }
- } else {
- createAccount.setEnabled(true);
- LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForStatus(status)
- , AssistantActivity.instance());
- }
- }
-
- @Override
- public void onRecoverAccount(AccountCreator accountCreator, Status status, String resp) {
- if (AssistantActivity.instance() == null) {
- return;
- }
- if (status.equals(Status.RequestOk)) {
- AssistantActivity.instance().displayAssistantCodeConfirm(getUsername()
- , phoneNumberEdit.getText().toString(), dialCode.getText().toString(), false);
- } else {
- createAccount.setEnabled(true);
- //SMS error
- LinphoneUtils.displayErrorAlert(getString(R.string.request_failed)
- , AssistantActivity.instance());
- }
- }
-
- @Override
- public void onIsAccountLinked(AccountCreator accountCreator, Status status, String resp) {
- }
-
- @Override
- public void onIsAliasUsed(AccountCreator ac, Status status, String resp) {
- if (AssistantActivity.instance() == null) {
- return;
- }
- if (status.equals(Status.AliasIsAccount) || status.equals(Status.AliasExist)) {
- if (accountCreator.getPhoneNumber() != null && accountCreator.getUsername() != null
- && accountCreator.getPhoneNumber().compareTo(accountCreator.getUsername()) == 0) {
- accountCreator.isAccountActivated();
- } else {
- createAccount.setEnabled(true);
- LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForStatus(status)
- , AssistantActivity.instance());
- }
- } else {
- accountCreator.isAccountActivated();
- }
- }
-
- @Override
- public void onUpdateAccount(AccountCreator accountCreator, Status status, String resp) {
-
- }
+ , OnClickListener, AccountCreatorListener {
+ private EditText phoneNumberEdit, usernameEdit, passwordEdit, passwordConfirmEdit, emailEdit, dialCode;
+ private TextView phoneNumberError, passwordError, passwordConfirmError, emailError, assisstantTitle, sipUri, skip, instruction;
+ private ImageView phoneNumberInfo;
+
+ private boolean passwordOk = false;
+ private boolean emailOk = false;
+ private boolean confirmPasswordOk = false;
+ private boolean linkAccount = false;
+ private Button createAccount, selectCountry;
+ private CheckBox useUsername, useEmail;
+ private String addressSip = "";
+ private int countryCode;
+ private LinearLayout phoneNumberLayout, usernameLayout, emailLayout, passwordLayout, passwordConfirmLayout;
+ private final Pattern UPPER_CASE_REGEX = Pattern.compile("[A-Z]");
+ private AccountCreator accountCreator;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ View view = inflater.inflate(R.layout.assistant_account_creation, container, false);
+
+ //Initialize accountCreator
+ accountCreator = LinphoneManager.getLc().createAccountCreator(LinphonePreferences.instance().getXmlrpcUrl());
+ accountCreator.setListener(this);
+
+ instruction = view.findViewById(R.id.message_create_account);
+
+ createAccount = view.findViewById(R.id.assistant_create);
+
+ phoneNumberLayout = view.findViewById(R.id.phone_number_layout);
+ usernameLayout = view.findViewById(R.id.username_layout);
+ emailLayout = view.findViewById(R.id.email_layout);
+ passwordLayout = view.findViewById(R.id.password_layout);
+ passwordConfirmLayout = view.findViewById(R.id.password_confirm_layout);
+
+ useUsername = view.findViewById(R.id.use_username);
+ useEmail = view.findViewById(R.id.use_email);
+
+ usernameEdit = view.findViewById(R.id.username);
+
+ phoneNumberError = view.findViewById(R.id.phone_number_error);
+ phoneNumberEdit = view.findViewById(R.id.phone_number);
+ sipUri = view.findViewById(R.id.sip_uri);
+
+ phoneNumberInfo = view.findViewById(R.id.info_phone_number);
+
+ selectCountry = view.findViewById(R.id.select_country);
+ dialCode = view.findViewById(R.id.dial_code);
+ assisstantTitle = view.findViewById(R.id.assistant_title);
+
+ passwordError = view.findViewById(R.id.password_error);
+ passwordEdit = view.findViewById(R.id.password);
+
+ passwordConfirmError = view.findViewById(R.id.confirm_password_error);
+ passwordConfirmEdit = view.findViewById(R.id.confirm_password);
+
+ emailError = view.findViewById(R.id.email_error);
+ emailEdit = view.findViewById(R.id.email);
+
+ skip = view.findViewById(R.id.assistant_skip);
+
+ //Phone number
+ if (getResources().getBoolean(R.bool.use_phone_number_validation)) {
+ getActivity().getApplicationContext();
+ //Automatically get the country code from the phone
+ TelephonyManager tm =
+ (TelephonyManager) getActivity().getApplicationContext().getSystemService(
+ Context.TELEPHONY_SERVICE);
+ String countryIso = tm.getNetworkCountryIso();
+ countryCode = org.linphone.core.Utils.getCccFromIso(countryIso.toUpperCase());
+
+ phoneNumberLayout.setVisibility(View.VISIBLE);
+
+ phoneNumberInfo.setOnClickListener(this);
+ selectCountry.setOnClickListener(this);
+
+ String previousPhone = AssistantActivity.instance().phone_number;
+ if (previousPhone != null) {
+ phoneNumberEdit.setText(previousPhone);
+ }
+ DialPlan c = AssistantActivity.instance().country;
+ if (c != null) {
+ selectCountry.setText(c.getCountry());
+ dialCode.setText(c.getCountryCallingCode().contains("+") ?
+ c.getCountryCallingCode() : "+" + c.getCountryCallingCode());
+ } else {
+ c = AssistantActivity.instance().getCountryListAdapter()
+ .getCountryFromCountryCode(String.valueOf(countryCode));
+ if (c != null) {
+ selectCountry.setText(c.getCountry());
+ dialCode.setText(c.getCountryCallingCode().contains("+") ?
+ c.getCountryCallingCode() : "+" + c.getCountryCallingCode());
+ }
+ }
+
+ //Allow user to enter a username instead use the phone number as username
+ if (getResources().getBoolean(R.bool.assistant_allow_username)) {
+ useUsername.setVisibility(View.VISIBLE);
+ useUsername.setOnCheckedChangeListener(this);
+ }
+ addPhoneNumberHandler(phoneNumberEdit, null);
+ addPhoneNumberHandler(dialCode, null);
+ }
+
+ //Password & email address
+ if (getResources().getBoolean(R.bool.isTablet)
+ || !getResources().getBoolean(R.bool.use_phone_number_validation)) {
+ useEmail.setVisibility(View.VISIBLE);
+ useEmail.setOnCheckedChangeListener(this);
+
+ if (getResources().getBoolean(R.bool.pre_fill_email_in_assistant)) {
+ Account[] accounts = AccountManager.get(getActivity()).getAccountsByType("com.google");
+
+ for (Account account : accounts) {
+ if (isEmailCorrect(account.name)) {
+ String possibleEmail = account.name;
+ emailEdit.setText(possibleEmail);
+ accountCreator.setEmail(possibleEmail);
+ emailOk = true;
+ break;
+ }
+ }
+ }
+
+ addPasswordHandler(passwordEdit, null);
+ addConfirmPasswordHandler(passwordEdit, passwordConfirmEdit, null);
+ addEmailHandler(emailEdit, null);
+ }
+
+ //Hide phone number and display username/email/password
+ if (!getResources().getBoolean(R.bool.use_phone_number_validation)) {
+ useEmail.setVisibility(View.GONE);
+ useUsername.setVisibility(View.GONE);
+
+ usernameLayout.setVisibility(View.VISIBLE);
+ passwordLayout.setVisibility(View.VISIBLE);
+ passwordConfirmLayout.setVisibility(View.VISIBLE);
+ emailLayout.setVisibility(View.VISIBLE);
+ }
+
+ //Link account with phone number
+ if (getArguments().getBoolean("LinkPhoneNumber")) {
+ linkAccount = true;
+ useEmail.setVisibility(View.GONE);
+ useUsername.setVisibility(View.GONE);
+
+ usernameLayout.setVisibility(View.GONE);
+ passwordLayout.setVisibility(View.GONE);
+ passwordConfirmLayout.setVisibility(View.GONE);
+ emailLayout.setVisibility(View.GONE);
+
+ skip.setVisibility(View.VISIBLE);
+ skip.setOnClickListener(this);
+
+ createAccount.setText(getResources().getString(R.string.link_account));
+ assisstantTitle.setText(getResources().getString(R.string.link_account));
+ }
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+ accountCreator.setLanguage(Locale.getDefault().toLanguageTag());
+ }
+
+ addUsernameHandler(usernameEdit, null);
+
+ createAccount.setEnabled(true);
+ createAccount.setOnClickListener(this);
+
+ return view;
+ }
+
+ @Override
+ public void onPause() {
+ super.onPause();
+ accountCreator.setListener(null);
+ }
+
+ private String getUsername() {
+ if (usernameEdit != null) {
+ String username = usernameEdit.getText().toString();
+ return username.toLowerCase(Locale.getDefault());
+ }
+ return null;
+ }
+
+ @Override
+ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
+ if (buttonView.getId() == R.id.use_username) {
+ if (isChecked) {
+ usernameLayout.setVisibility(View.VISIBLE);
+ onTextChanged2();
+ } else {
+ usernameLayout.setVisibility(View.GONE);
+ accountCreator.setUsername(null);
+ onTextChanged2();
+ }
+ } else if (buttonView.getId() == R.id.use_email) {
+ if (isChecked) {
+ dialCode.setBackgroundResource(R.drawable.resizable_textfield);
+ phoneNumberEdit.setBackgroundResource(R.drawable.resizable_textfield);
+ useUsername.setEnabled(false);
+ dialCode.setEnabled(false);
+ selectCountry.setEnabled(false);
+ phoneNumberEdit.setEnabled(false);
+ emailLayout.setVisibility(View.VISIBLE);
+ passwordLayout.setVisibility(View.VISIBLE);
+ passwordConfirmLayout.setVisibility(View.VISIBLE);
+ usernameLayout.setVisibility(View.VISIBLE);
+ useUsername.setVisibility(CheckBox.GONE);
+ phoneNumberLayout.setVisibility(LinearLayout.GONE);
+ instruction.setText(getString(R.string.assistant_create_account_part_email));
+ } else {
+ if (!useUsername.isChecked()) {
+ usernameLayout.setVisibility(View.GONE);
+ }
+ useUsername.setEnabled(true);
+ dialCode.setEnabled(true);
+ selectCountry.setEnabled(true);
+ phoneNumberEdit.setEnabled(true);
+ emailLayout.setVisibility(View.GONE);
+ passwordLayout.setVisibility(View.GONE);
+ passwordConfirmLayout.setVisibility(View.GONE);
+ useUsername.setVisibility(CheckBox.VISIBLE);
+ phoneNumberLayout.setVisibility(LinearLayout.VISIBLE);
+ instruction.setText(getString(R.string.assistant_create_account_part_1));
+ }
+ }
+ }
+
+ @Override
+ public void onClick(View v) {
+ int id = v.getId();
+ if (id == R.id.select_country) {
+ AssistantActivity.instance().displayCountryChooser();
+ } else if (id == R.id.assistant_skip) {
+ if (getArguments().getBoolean("LinkFromPref")) {
+ AssistantActivity.instance().finish();
+ } else {
+ AssistantActivity.instance().success();
+ }
+ } else if (id == R.id.info_phone_number) {
+ if (linkAccount) {
+ new AlertDialog.Builder(getActivity())
+ .setTitle(getString(R.string.phone_number_info_title))
+ .setMessage(getString(R.string.phone_number_link_info_content) + "\n"
+ + getString(R.string.phone_number_link_info_content_already_account))
+ .show();
+ } else {
+ new AlertDialog.Builder(getActivity())
+ .setTitle(getString(R.string.phone_number_info_title))
+ .setMessage(getString(R.string.phone_number_info_content))
+ .show();
+ }
+ } else if (id == R.id.assistant_create) {
+ createAccount.setEnabled(false);
+ if (linkAccount) {
+ addAlias();
+ } else {
+ if (useEmail.isChecked()) accountCreator.setPhoneNumber(null, null);
+ if (!getResources().getBoolean(R.bool.isTablet) || getUsername().length() > 0) {
+ LinphoneManager.getLc().getConfig().loadFromXmlFile(LinphoneManager.getInstance().getmDynamicConfigFile());
+ accountCreator.isAccountExist();
+ } else {
+ LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForUsernameStatus(AccountCreator.UsernameStatus.TooShort)
+ , AssistantActivity.instance());
+ createAccount.setEnabled(true);
+ }
+ }
+ }
+ }
+
+ private boolean isEmailCorrect(String email) {
+ Pattern emailPattern = Patterns.EMAIL_ADDRESS;
+ return emailPattern.matcher(email).matches();
+ }
+
+ private boolean isPasswordCorrect(String password) {
+ return password.length() >= 1;
+ }
+
+ private void addAlias() {
+ accountCreator.setUsername(LinphonePreferences.instance().getAccountUsername(
+ LinphonePreferences.instance().getDefaultAccountIndex())
+ );
+ int status = accountCreator.setPhoneNumber(
+ phoneNumberEdit.getText().toString(), LinphoneUtils.getCountryCode(dialCode));
+ boolean isOk = status == AccountCreator.PhoneNumberStatus.Ok.toInt();
+ if (isOk) {
+ accountCreator.linkAccount();
+ } else {
+ createAccount.setEnabled(true);
+ LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForPhoneNumberStatus(status), AssistantActivity.instance());
+ LinphoneUtils.displayError(isOk, phoneNumberError, LinphoneUtils.errorForPhoneNumberStatus(status));
+ }
+ }
+
+ private void createAccount() {
+ if ((getResources().getBoolean(R.bool.isTablet) || !getResources().getBoolean(R.bool.use_phone_number_validation))
+ && useEmail.isChecked()) {
+ AccountCreator.EmailStatus emailStatus;
+ AccountCreator.PasswordStatus passwordStatus;
+
+ passwordStatus = accountCreator.setPassword(passwordEdit.getText().toString());
+ emailStatus = accountCreator.setEmail(emailEdit.getText().toString());
+
+ if (!emailOk) {
+ LinphoneUtils.displayError(false, emailError, LinphoneUtils.errorForEmailStatus(emailStatus));
+ LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForEmailStatus(emailStatus)
+ , AssistantActivity.instance());
+ } else if (!passwordOk) {
+ LinphoneUtils.displayError(false, passwordError, LinphoneUtils.errorForPasswordStatus(passwordStatus));
+ LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForPasswordStatus(passwordStatus)
+ , AssistantActivity.instance());
+ } else if (!confirmPasswordOk) {
+ String msg;
+ if (passwordConfirmEdit.getText().toString().equals(passwordEdit.getText().toString())) {
+ msg = getString(R.string.wizard_password_incorrect);
+ } else {
+ msg = getString(R.string.wizard_passwords_unmatched);
+ }
+ LinphoneUtils.displayError(false, passwordError, msg);
+ LinphoneUtils.displayErrorAlert(msg, AssistantActivity.instance());
+ } else {
+ accountCreator.createAccount();
+ }
+ } else {
+ if (phoneNumberEdit.length() > 0 || dialCode.length() > 1) {
+ int phoneStatus;
+ boolean isOk;
+ phoneStatus = accountCreator.setPhoneNumber(
+ phoneNumberEdit.getText().toString(), LinphoneUtils.getCountryCode(dialCode));
+ isOk = phoneStatus == AccountCreator.PhoneNumberStatus.Ok.toInt();
+ if (!useUsername.isChecked() && accountCreator.getUsername() == null) {
+ accountCreator.setUsername(accountCreator.getPhoneNumber());
+ } else {
+ accountCreator.setUsername(usernameEdit.getText().toString());
+ accountCreator.setPhoneNumber(
+ phoneNumberEdit.getText().toString(), dialCode.getText().toString());
+ }
+ if (isOk) {
+ accountCreator.createAccount();
+ } else {
+ LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForPhoneNumberStatus(phoneStatus)
+ , AssistantActivity.instance());
+ LinphoneUtils.displayError(isOk, phoneNumberError
+ , LinphoneUtils.errorForPhoneNumberStatus(phoneStatus));
+ }
+ } else {
+ LinphoneUtils.displayErrorAlert(getString(R.string.assistant_create_account_part_1)
+ , AssistantActivity.instance());
+ }
+ }
+ createAccount.setEnabled(true);
+ }
+
+ private int getPhoneNumberStatus() {
+ int status = accountCreator.setPhoneNumber(
+ phoneNumberEdit.getText().toString(), LinphoneUtils.getCountryCode(dialCode));
+ addressSip = accountCreator.getPhoneNumber();
+ return status;
+ }
+
+ public void onTextChanged2() {
+ String msg = "";
+ accountCreator.setUsername(getUsername());
+
+ if (!useEmail.isChecked() && getResources().getBoolean(R.bool.use_phone_number_validation)) {
+ int status = getPhoneNumberStatus();
+ boolean isOk = (status == AccountCreator.PhoneNumberStatus.Ok.toInt());
+ LinphoneUtils.displayError(isOk, phoneNumberError, LinphoneUtils.errorForPhoneNumberStatus(status));
+
+ // Username or phone number
+ if (getResources().getBoolean(R.bool.assistant_allow_username) && useUsername.isChecked()) {
+ addressSip = getUsername();
+ }
+
+ if (!isOk) {
+ if (status == AccountCreator.PhoneNumberStatus.InvalidCountryCode.toInt()) {
+ dialCode.setBackgroundResource(R.drawable.resizable_textfield_error);
+ phoneNumberEdit.setBackgroundResource(R.drawable.resizable_textfield);
+ } else {
+ dialCode.setBackgroundResource(R.drawable.resizable_textfield);
+ phoneNumberEdit.setBackgroundResource(R.drawable.resizable_textfield_error);
+ }
+
+ } else {
+ dialCode.setBackgroundResource(R.drawable.resizable_textfield);
+ phoneNumberEdit.setBackgroundResource(R.drawable.resizable_textfield);
+ if (!linkAccount && addressSip.length() > 0) {
+ msg = getResources().getString(R.string.assistant_create_account_phone_number_address)
+ + " <" + addressSip + "@" + getResources().getString(R.string.default_domain) + ">";
+ }
+ }
+ } else {
+ addressSip = getUsername();
+ if (addressSip.length() > 0) {
+ msg = getResources().getString(R.string.assistant_create_account_phone_number_address)
+ + " ";
+ }
+ }
+ sipUri.setText(msg);
+ }
+
+ private void addPhoneNumberHandler(final EditText field, final ImageView icon) {
+ field.addTextChangedListener(new TextWatcher() {
+ public void afterTextChanged(Editable s) {
+ if (field.equals(dialCode)) {
+ DialPlan c = AssistantActivity.instance().getCountryListAdapter()
+ .getCountryFromCountryCode(dialCode.getText().toString());
+ if (c != null) {
+ AssistantActivity.instance().country = c;
+ selectCountry.setText(c.getCountry());
+ } else {
+ selectCountry.setText(R.string.select_your_country);
+ }
+ }
+ }
+
+ public void beforeTextChanged(CharSequence s, int start, int count, int after) {
+ }
+
+ public void onTextChanged(CharSequence s, int start, int count, int after) {
+ onTextChanged2();
+ }
+ });
+ }
+
+ private void addUsernameHandler(final EditText field, final ImageView icon) {
+ field.addTextChangedListener(new TextWatcher() {
+ public void afterTextChanged(Editable s) {
+ Matcher matcher = UPPER_CASE_REGEX.matcher(s);
+ while (matcher.find()) {
+ CharSequence upperCaseRegion = s.subSequence(matcher.start(), matcher.end());
+ s.replace(matcher.start(), matcher.end(), upperCaseRegion.toString().toLowerCase());
+ }
+ }
+
+ public void beforeTextChanged(CharSequence s, int start, int count, int after) {
+ }
+
+ public void onTextChanged(CharSequence s, int start, int count, int after) {
+ onTextChanged2();
+ }
+ });
+ }
+
+ private void addEmailHandler(final EditText field, final ImageView icon) {
+ field.addTextChangedListener(new TextWatcher() {
+ public void afterTextChanged(Editable s) {
+ emailOk = false;
+ AccountCreator.EmailStatus status = accountCreator.setEmail(field.getText().toString());
+ if (status.equals(AccountCreator.EmailStatus.Ok)) {
+ emailOk = true;
+ LinphoneUtils.displayError(emailOk, emailError, "");
+ } else {
+ LinphoneUtils.displayError(emailOk
+ , emailError, LinphoneUtils.errorForEmailStatus(status));
+ }
+ }
+
+ public void beforeTextChanged(CharSequence s, int start, int count, int after) {
+ }
+
+ public void onTextChanged(CharSequence s, int start, int count, int after) {
+ }
+ });
+ }
+
+ private void addPasswordHandler(final EditText field1, final ImageView icon) {
+ TextWatcher passwordListener = new TextWatcher() {
+ public void afterTextChanged(Editable s) {
+ passwordOk = false;
+ AccountCreator.PasswordStatus status = accountCreator.setPassword(field1.getText().toString());
+ if (isPasswordCorrect(field1.getText().toString())) {
+ passwordOk = true;
+ LinphoneUtils.displayError(passwordOk, passwordError, "");
+ } else {
+ LinphoneUtils.displayError(passwordOk
+ , passwordError, LinphoneUtils.errorForPasswordStatus(status));
+ }
+ }
+
+ public void beforeTextChanged(CharSequence s, int start, int count, int after) {
+ }
+
+ public void onTextChanged(CharSequence s, int start, int count, int after) {
+ }
+ };
+
+ field1.addTextChangedListener(passwordListener);
+ }
+
+ private void addConfirmPasswordHandler(final EditText field1, final EditText field2, final ImageView icon) {
+ TextWatcher passwordListener = new TextWatcher() {
+ public void afterTextChanged(Editable s) {
+ confirmPasswordOk = false;
+ if (field1.getText().toString().equals(field2.getText().toString())) {
+ confirmPasswordOk = true;
+ if (!isPasswordCorrect(field1.getText().toString())) {
+ LinphoneUtils.displayError(passwordOk
+ , passwordError, getString(R.string.wizard_password_incorrect));
+ } else {
+ LinphoneUtils.displayError(confirmPasswordOk, passwordConfirmError, "");
+ }
+ } else {
+ LinphoneUtils.displayError(confirmPasswordOk
+ , passwordConfirmError, getString(R.string.wizard_passwords_unmatched));
+ }
+ }
+
+ public void beforeTextChanged(CharSequence s, int start, int count, int after) {
+ }
+
+ public void onTextChanged(CharSequence s, int start, int count, int after) {
+ }
+ };
+ field1.addTextChangedListener(passwordListener);
+ field2.addTextChangedListener(passwordListener);
+ }
+
+ @Override
+ public void onIsAccountExist(AccountCreator accountCreator, final Status status, String resp) {
+ if (status.equals(Status.AccountExist) || status.equals(Status.AccountExistWithAlias)) {
+ if (useEmail.isChecked()) {
+ createAccount.setEnabled(true);
+ LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForStatus(status)
+ , AssistantActivity.instance());
+ } else {
+ LinphoneManager.getLc().getConfig().loadFromXmlFile(LinphoneManager.getInstance().getmDynamicConfigFile());
+ accountCreator.isAliasUsed();
+ }
+ } else {
+ createAccount();
+ }
+ }
+
+ @Override
+ public void onCreateAccount(AccountCreator accountCreator, Status status, String resp) {
+ if (status.equals(Status.AccountCreated)) {
+ if (useEmail.isChecked() || !getResources().getBoolean(R.bool.use_phone_number_validation)) {
+ AssistantActivity.instance().displayAssistantConfirm(getUsername()
+ , passwordEdit.getText().toString(), emailEdit.getText().toString());
+ } else {
+ AssistantActivity.instance().displayAssistantCodeConfirm(getUsername()
+ , phoneNumberEdit.getText().toString()
+ , LinphoneUtils.getCountryCode(dialCode), false);
+ }
+ } else {
+ createAccount.setEnabled(true);
+ LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForStatus(status)
+ , AssistantActivity.instance());
+ }
+ }
+
+ @Override
+ public void onActivateAccount(AccountCreator accountCreator, Status status, String resp) {
+ }
+
+ @Override
+ public void onLinkAccount(AccountCreator accountCreator, Status status, String resp) {
+ if (AssistantActivity.instance() == null) {
+ return;
+ }
+ if (status.equals(Status.RequestOk)) {
+ AssistantActivity.instance().displayAssistantCodeConfirm(getUsername()
+ , phoneNumberEdit.getText().toString()
+ , LinphoneUtils.getCountryCode(dialCode), false);
+ }
+ }
+
+ @Override
+ public void onActivateAlias(AccountCreator accountCreator, Status status, String resp) {
+ if (AssistantActivity.instance() == null) {
+ return;
+ }
+ if (status.equals(Status.RequestOk)) {
+ AssistantActivity.instance().displayAssistantCodeConfirm(getUsername()
+ , phoneNumberEdit.getText().toString()
+ , LinphoneUtils.getCountryCode(dialCode), false);
+ }
+ }
+
+ @Override
+ public void onIsAccountActivated(AccountCreator accountCreator, Status status, String resp) {
+ if (AssistantActivity.instance() == null) {
+ return;
+ }
+ if (status.equals(Status.AccountNotActivated)) {
+ if (getResources().getBoolean(R.bool.isTablet)
+ || !getResources().getBoolean(R.bool.use_phone_number_validation)) {
+ //accountCreator.activateAccount(); // Resend email TODO
+ } else {
+ accountCreator.recoverAccount(); // Resend SMS
+ }
+ } else {
+ createAccount.setEnabled(true);
+ LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForStatus(status)
+ , AssistantActivity.instance());
+ }
+ }
+
+ @Override
+ public void onRecoverAccount(AccountCreator accountCreator, Status status, String resp) {
+ if (AssistantActivity.instance() == null) {
+ return;
+ }
+ if (status.equals(Status.RequestOk)) {
+ AssistantActivity.instance().displayAssistantCodeConfirm(getUsername()
+ , phoneNumberEdit.getText().toString(), dialCode.getText().toString(), false);
+ } else {
+ createAccount.setEnabled(true);
+ //SMS error
+ LinphoneUtils.displayErrorAlert(getString(R.string.request_failed)
+ , AssistantActivity.instance());
+ }
+ }
+
+ @Override
+ public void onIsAccountLinked(AccountCreator accountCreator, Status status, String resp) {
+ }
+
+ @Override
+ public void onIsAliasUsed(AccountCreator ac, Status status, String resp) {
+ if (AssistantActivity.instance() == null) {
+ return;
+ }
+ if (status.equals(Status.AliasIsAccount) || status.equals(Status.AliasExist)) {
+ if (accountCreator.getPhoneNumber() != null && accountCreator.getUsername() != null
+ && accountCreator.getPhoneNumber().compareTo(accountCreator.getUsername()) == 0) {
+ accountCreator.isAccountActivated();
+ } else {
+ createAccount.setEnabled(true);
+ LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForStatus(status)
+ , AssistantActivity.instance());
+ }
+ } else {
+ accountCreator.isAccountActivated();
+ }
+ }
+
+ @Override
+ public void onUpdateAccount(AccountCreator accountCreator, Status status, String resp) {
+
+ }
}
diff --git a/src/android/org/linphone/assistant/EchoCancellerCalibrationFragment.java b/src/android/org/linphone/assistant/EchoCancellerCalibrationFragment.java
index 5fcabf45e..73a5e13d8 100644
--- a/src/android/org/linphone/assistant/EchoCancellerCalibrationFragment.java
+++ b/src/android/org/linphone/assistant/EchoCancellerCalibrationFragment.java
@@ -19,19 +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 org.linphone.LinphoneManager;
-import org.linphone.LinphonePreferences;
-import org.linphone.R;
-import org.linphone.core.Core;
-import org.linphone.core.EcCalibratorStatus;
-import org.linphone.core.CoreException;
-import org.linphone.core.CoreListenerStub;
-import org.linphone.core.XmlRpcArgType;
-import org.linphone.core.XmlRpcRequest;
-import org.linphone.core.XmlRpcRequestListener;
-import org.linphone.core.XmlRpcSession;
-import org.linphone.mediastream.Log;
-
import android.app.Fragment;
import android.os.Build;
import android.os.Bundle;
@@ -40,68 +27,81 @@ import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
+import org.linphone.LinphoneManager;
+import org.linphone.LinphonePreferences;
+import org.linphone.R;
+import org.linphone.core.Core;
+import org.linphone.core.CoreException;
+import org.linphone.core.CoreListenerStub;
+import org.linphone.core.EcCalibratorStatus;
+import org.linphone.core.XmlRpcArgType;
+import org.linphone.core.XmlRpcRequest;
+import org.linphone.core.XmlRpcRequestListener;
+import org.linphone.core.XmlRpcSession;
+import org.linphone.mediastream.Log;
+
public class EchoCancellerCalibrationFragment extends Fragment implements XmlRpcRequestListener {
- private Handler mHandler = new Handler();
- private boolean mSendEcCalibrationResult = false;
- private CoreListenerStub mListener;
- private XmlRpcSession xmlRpcSession;
- private XmlRpcRequest xmlRpcRequest;
- private Runnable runFinished;
+ private Handler mHandler = new Handler();
+ private boolean mSendEcCalibrationResult = false;
+ private CoreListenerStub mListener;
+ private XmlRpcSession xmlRpcSession;
+ private XmlRpcRequest xmlRpcRequest;
+ private Runnable runFinished;
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- View view = inflater.inflate(R.layout.assistant_ec_calibration, container, false);
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container,
+ Bundle savedInstanceState) {
+ View view = inflater.inflate(R.layout.assistant_ec_calibration, container, false);
- mListener = new CoreListenerStub(){
- @Override
- public void onEcCalibrationResult(Core lc, EcCalibratorStatus status, int delay_ms) {
- lc.removeListener(mListener);
- LinphoneManager.getInstance().routeAudioToReceiver();
- if (mSendEcCalibrationResult) {
- sendEcCalibrationResult(status, delay_ms);
- } else {
- AssistantActivity.instance().isEchoCalibrationFinished();
- }
- }
- };
- runFinished = new Runnable() {
- public void run() {
- AssistantActivity.instance().isEchoCalibrationFinished();
- }
- };
+ mListener = new CoreListenerStub() {
+ @Override
+ public void onEcCalibrationResult(Core lc, EcCalibratorStatus status, int delay_ms) {
+ lc.removeListener(mListener);
+ LinphoneManager.getInstance().routeAudioToReceiver();
+ if (mSendEcCalibrationResult) {
+ sendEcCalibrationResult(status, delay_ms);
+ } else {
+ AssistantActivity.instance().isEchoCalibrationFinished();
+ }
+ }
+ };
+ runFinished = new Runnable() {
+ public void run() {
+ AssistantActivity.instance().isEchoCalibrationFinished();
+ }
+ };
- xmlRpcSession = LinphoneManager.getLcIfManagerNotDestroyedOrNull().createXmlRpcSession(LinphonePreferences.instance().getXmlrpcUrl());
- xmlRpcRequest = xmlRpcSession.createRequest(XmlRpcArgType.None, "add_ec_calibration_result");
- xmlRpcRequest.setListener(this);
+ xmlRpcSession = LinphoneManager.getLcIfManagerNotDestroyedOrNull().createXmlRpcSession(LinphonePreferences.instance().getXmlrpcUrl());
+ xmlRpcRequest = xmlRpcSession.createRequest(XmlRpcArgType.None, "add_ec_calibration_result");
+ xmlRpcRequest.setListener(this);
- try {
- LinphoneManager.getLc().addListener(mListener);
- LinphoneManager.getInstance().startEcCalibration();
- } catch (CoreException e) {
- Log.e(e, "Unable to calibrate EC");
- AssistantActivity.instance().isEchoCalibrationFinished();
- }
- return view;
- }
+ try {
+ LinphoneManager.getLc().addListener(mListener);
+ LinphoneManager.getInstance().startEcCalibration();
+ } catch (CoreException e) {
+ Log.e(e, "Unable to calibrate EC");
+ AssistantActivity.instance().isEchoCalibrationFinished();
+ }
+ return view;
+ }
- public void enableEcCalibrationResultSending(boolean enabled) {
- mSendEcCalibrationResult = enabled;
- }
+ public void enableEcCalibrationResultSending(boolean enabled) {
+ mSendEcCalibrationResult = enabled;
+ }
- @Override
- public void onResponse(XmlRpcRequest request) {
- mHandler.post(runFinished);
- }
+ @Override
+ public void onResponse(XmlRpcRequest request) {
+ mHandler.post(runFinished);
+ }
- private void sendEcCalibrationResult(EcCalibratorStatus status, int delayMs) {
- Boolean hasBuiltInEchoCanceler = LinphoneManager.getLc().hasBuiltinEchoCanceller();
- Log.i("Add echo canceller calibration result: manufacturer=" + Build.MANUFACTURER + " model=" + Build.MODEL + " status=" + status + " delay=" + delayMs + "ms" + " hasBuiltInEchoCanceler " + hasBuiltInEchoCanceler);
- xmlRpcRequest.addStringArg(Build.MANUFACTURER);
- xmlRpcRequest.addStringArg(Build.MODEL);
- xmlRpcRequest.addStringArg(status.toString());
- xmlRpcRequest.addIntArg(delayMs);
- xmlRpcRequest.addIntArg(hasBuiltInEchoCanceler ? 1 : 0);
- xmlRpcSession.sendRequest(xmlRpcRequest);
- }
+ private void sendEcCalibrationResult(EcCalibratorStatus status, int delayMs) {
+ Boolean hasBuiltInEchoCanceler = LinphoneManager.getLc().hasBuiltinEchoCanceller();
+ Log.i("Add echo canceller calibration result: manufacturer=" + Build.MANUFACTURER + " model=" + Build.MODEL + " status=" + status + " delay=" + delayMs + "ms" + " hasBuiltInEchoCanceler " + hasBuiltInEchoCanceler);
+ xmlRpcRequest.addStringArg(Build.MANUFACTURER);
+ xmlRpcRequest.addStringArg(Build.MODEL);
+ xmlRpcRequest.addStringArg(status.toString());
+ xmlRpcRequest.addIntArg(delayMs);
+ xmlRpcRequest.addIntArg(hasBuiltInEchoCanceler ? 1 : 0);
+ xmlRpcSession.sendRequest(xmlRpcRequest);
+ }
}
diff --git a/src/android/org/linphone/assistant/LinphoneLoginFragment.java b/src/android/org/linphone/assistant/LinphoneLoginFragment.java
index d16eddb97..98e5d4765 100644
--- a/src/android/org/linphone/assistant/LinphoneLoginFragment.java
+++ b/src/android/org/linphone/assistant/LinphoneLoginFragment.java
@@ -17,17 +17,6 @@ You should have received a copy of the GNU General Public License
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.util.Locale;
-
-import org.linphone.LinphoneManager;
-import org.linphone.LinphonePreferences;
-import org.linphone.LinphoneUtils;
-import org.linphone.R;
-import org.linphone.compatibility.Compatibility;
-import org.linphone.core.AccountCreatorListener;
-import org.linphone.core.DialPlan;
-import org.linphone.core.AccountCreator;
-import org.linphone.core.ProxyConfig;
import android.app.AlertDialog;
import android.app.Fragment;
@@ -50,351 +39,362 @@ import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
+import org.linphone.LinphoneManager;
+import org.linphone.LinphonePreferences;
+import org.linphone.LinphoneUtils;
+import org.linphone.R;
+import org.linphone.compatibility.Compatibility;
+import org.linphone.core.AccountCreator;
+import org.linphone.core.AccountCreatorListener;
+import org.linphone.core.DialPlan;
+
+import java.util.Locale;
+
public class LinphoneLoginFragment extends Fragment implements CompoundButton.OnCheckedChangeListener, OnClickListener, TextWatcher, AccountCreatorListener {
- private EditText login, password, phoneNumberEdit, dialCode;
- private Button apply, selectCountry;
- private CheckBox useUsername;
- private LinearLayout phoneNumberLayout, usernameLayout, passwordLayout;
- private TextView forgotPassword, messagePhoneNumber, phoneNumberError;
- private Boolean recoverAccount;
- private AccountCreator accountCreator;
- private int countryCode;
- private String phone, dialcode, username, pwd;
- private ImageView phoneNumberInfo;
+ private EditText login, password, phoneNumberEdit, dialCode;
+ private Button apply, selectCountry;
+ private CheckBox useUsername;
+ private LinearLayout phoneNumberLayout, usernameLayout, passwordLayout;
+ private TextView forgotPassword, messagePhoneNumber, phoneNumberError;
+ private Boolean recoverAccount;
+ private AccountCreator accountCreator;
+ private int countryCode;
+ private String phone, dialcode, username, pwd;
+ private ImageView phoneNumberInfo;
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- View view = inflater.inflate(R.layout.assistant_linphone_login, container, false);
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container,
+ Bundle savedInstanceState) {
+ View view = inflater.inflate(R.layout.assistant_linphone_login, container, false);
- accountCreator = LinphoneManager.getLc().createAccountCreator(LinphonePreferences.instance().getXmlrpcUrl());
- accountCreator.setListener(this);
+ accountCreator = LinphoneManager.getLc().createAccountCreator(LinphonePreferences.instance().getXmlrpcUrl());
+ accountCreator.setListener(this);
- String url = "http://linphone.org/free-sip-service.html&action=recover";
+ String url = "http://linphone.org/free-sip-service.html&action=recover";
- login = view.findViewById(R.id.assistant_username);
- login.addTextChangedListener(this);
+ login = view.findViewById(R.id.assistant_username);
+ login.addTextChangedListener(this);
- recoverAccount = true;
+ recoverAccount = true;
- dialCode = view.findViewById(R.id.dial_code);
+ dialCode = view.findViewById(R.id.dial_code);
- phoneNumberEdit = view.findViewById(R.id.phone_number);
- phoneNumberLayout = view.findViewById(R.id.phone_number_layout);
- phoneNumberError = view.findViewById(R.id.phone_number_error_2);
+ phoneNumberEdit = view.findViewById(R.id.phone_number);
+ phoneNumberLayout = view.findViewById(R.id.phone_number_layout);
+ phoneNumberError = view.findViewById(R.id.phone_number_error_2);
- phoneNumberInfo = view.findViewById(R.id.info_phone_number);
+ phoneNumberInfo = view.findViewById(R.id.info_phone_number);
- useUsername = view.findViewById(R.id.use_username);
- usernameLayout = view.findViewById(R.id.username_layout);
- passwordLayout = view.findViewById(R.id.password_layout);
- password = view.findViewById(R.id.assistant_password);
- messagePhoneNumber = view.findViewById(R.id.message_phone_number);
+ useUsername = view.findViewById(R.id.use_username);
+ usernameLayout = view.findViewById(R.id.username_layout);
+ passwordLayout = view.findViewById(R.id.password_layout);
+ password = view.findViewById(R.id.assistant_password);
+ messagePhoneNumber = view.findViewById(R.id.message_phone_number);
- forgotPassword = view.findViewById(R.id.forgot_password);
- selectCountry = view.findViewById(R.id.select_country);
+ forgotPassword = view.findViewById(R.id.forgot_password);
+ selectCountry = view.findViewById(R.id.select_country);
- apply = view.findViewById(R.id.assistant_apply);
- apply.setEnabled(true);
- apply.setOnClickListener(this);
+ apply = view.findViewById(R.id.assistant_apply);
+ apply.setEnabled(true);
+ apply.setOnClickListener(this);
- //Phone number
- if(getResources().getBoolean(R.bool.use_phone_number_validation)){
- messagePhoneNumber.setText(getString(R.string.assistant_create_account_part_1));
- phone = getArguments().getString("Phone");
- dialcode = getArguments().getString("Dialcode");
+ //Phone number
+ if (getResources().getBoolean(R.bool.use_phone_number_validation)) {
+ messagePhoneNumber.setText(getString(R.string.assistant_create_account_part_1));
+ phone = getArguments().getString("Phone");
+ dialcode = getArguments().getString("Dialcode");
- getActivity().getApplicationContext();
- //Automatically get the country code from the phone
- TelephonyManager tm =
- (TelephonyManager) getActivity().getApplicationContext().getSystemService(
- Context.TELEPHONY_SERVICE);
- String countryIso = tm.getNetworkCountryIso();
- countryCode = org.linphone.core.Utils.getCccFromIso(countryIso.toUpperCase());
+ getActivity().getApplicationContext();
+ //Automatically get the country code from the phone
+ TelephonyManager tm =
+ (TelephonyManager) getActivity().getApplicationContext().getSystemService(
+ Context.TELEPHONY_SERVICE);
+ String countryIso = tm.getNetworkCountryIso();
+ countryCode = org.linphone.core.Utils.getCccFromIso(countryIso.toUpperCase());
- DialPlan c = AssistantActivity.instance().country;
- if (c != null) {
- selectCountry.setText(c.getCountry());
- dialCode.setText(c.getCountryCallingCode().contains("+") ?
- c.getCountryCallingCode() : "+" + c.getCountryCallingCode());
- } else {
- c = AssistantActivity.instance().getCountryListAdapter()
- .getCountryFromCountryCode(String.valueOf(countryCode));
- if (c != null) {
- selectCountry.setText(c.getCountry());
- dialCode.setText(c.getCountryCallingCode().contains("+") ?
- c.getCountryCallingCode() : "+" + c.getCountryCallingCode());
- }
- }
+ DialPlan c = AssistantActivity.instance().country;
+ if (c != null) {
+ selectCountry.setText(c.getCountry());
+ dialCode.setText(c.getCountryCallingCode().contains("+") ?
+ c.getCountryCallingCode() : "+" + c.getCountryCallingCode());
+ } else {
+ c = AssistantActivity.instance().getCountryListAdapter()
+ .getCountryFromCountryCode(String.valueOf(countryCode));
+ if (c != null) {
+ selectCountry.setText(c.getCountry());
+ dialCode.setText(c.getCountryCallingCode().contains("+") ?
+ c.getCountryCallingCode() : "+" + c.getCountryCallingCode());
+ }
+ }
- phoneNumberLayout.setVisibility(View.VISIBLE);
- selectCountry.setOnClickListener(this);
- phoneNumberInfo.setOnClickListener(this);
+ phoneNumberLayout.setVisibility(View.VISIBLE);
+ selectCountry.setOnClickListener(this);
+ phoneNumberInfo.setOnClickListener(this);
- String previousPhone = AssistantActivity.instance().phone_number;
- if (previousPhone != null ) {
- phoneNumberEdit.setText(previousPhone);
- }
+ String previousPhone = AssistantActivity.instance().phone_number;
+ if (previousPhone != null) {
+ phoneNumberEdit.setText(previousPhone);
+ }
- //Allow user to enter a username instead use the phone number as username
- if (getResources().getBoolean(R.bool.assistant_allow_username) ) {
- useUsername.setVisibility(View.VISIBLE);
- useUsername.setOnCheckedChangeListener(this);
- }
+ //Allow user to enter a username instead use the phone number as username
+ if (getResources().getBoolean(R.bool.assistant_allow_username)) {
+ useUsername.setVisibility(View.VISIBLE);
+ useUsername.setOnCheckedChangeListener(this);
+ }
- if (phone != null)
- phoneNumberEdit.setText(phone);
- if (dialcode != null)
- dialCode.setText("+"+dialcode);
- }
+ if (phone != null)
+ phoneNumberEdit.setText(phone);
+ if (dialcode != null)
+ dialCode.setText("+" + dialcode);
+ }
- if(getResources().getBoolean(R.bool.assistant_allow_username)) {
- useUsername.setVisibility(View.VISIBLE);
- useUsername.setOnCheckedChangeListener(this);
- password.addTextChangedListener(this);
- forgotPassword.setText(Compatibility.fromHtml("" + getString(R.string.forgot_password) + ""));
- forgotPassword.setMovementMethod(LinkMovementMethod.getInstance());
- }
+ if (getResources().getBoolean(R.bool.assistant_allow_username)) {
+ useUsername.setVisibility(View.VISIBLE);
+ useUsername.setOnCheckedChangeListener(this);
+ password.addTextChangedListener(this);
+ forgotPassword.setText(Compatibility.fromHtml("" + getString(R.string.forgot_password) + ""));
+ forgotPassword.setMovementMethod(LinkMovementMethod.getInstance());
+ }
- //Hide phone number and display username/email/password
- if(!getResources().getBoolean(R.bool.use_phone_number_validation)){
- phoneNumberLayout.setVisibility(View.GONE);
- useUsername.setVisibility(View.GONE);
+ //Hide phone number and display username/email/password
+ if (!getResources().getBoolean(R.bool.use_phone_number_validation)) {
+ phoneNumberLayout.setVisibility(View.GONE);
+ useUsername.setVisibility(View.GONE);
- usernameLayout.setVisibility(View.VISIBLE);
- passwordLayout.setVisibility(View.VISIBLE);
- }
+ usernameLayout.setVisibility(View.VISIBLE);
+ passwordLayout.setVisibility(View.VISIBLE);
+ }
- // When we come from generic login fragment
- username = getArguments().getString("Username");
- pwd = getArguments().getString("Password");
- if (username != null && pwd != null) {
- useUsername.setChecked(true);
- onCheckedChanged(useUsername, true);
- login.setText(username);
- password.setText(pwd);
- }
+ // When we come from generic login fragment
+ username = getArguments().getString("Username");
+ pwd = getArguments().getString("Password");
+ if (username != null && pwd != null) {
+ useUsername.setChecked(true);
+ onCheckedChanged(useUsername, true);
+ login.setText(username);
+ password.setText(pwd);
+ }
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
- accountCreator.setLanguage(Locale.getDefault().toLanguageTag());
- }
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+ accountCreator.setLanguage(Locale.getDefault().toLanguageTag());
+ }
- addPhoneNumberHandler(dialCode, null);
- addPhoneNumberHandler(phoneNumberEdit, null);
+ addPhoneNumberHandler(dialCode, null);
+ addPhoneNumberHandler(phoneNumberEdit, null);
- return view;
- }
+ return view;
+ }
- public void linphoneLogIn() {
- if (login.getText() == null || login.length() == 0 || password.getText() == null || password.length() == 0) {
- LinphoneUtils.displayErrorAlert(getString(R.string.first_launch_no_login_password), AssistantActivity.instance());
- apply.setEnabled(true);
- return;
- }
- accountCreator.setUsername(login.getText().toString());
- accountCreator.setPassword(password.getText().toString());
- accountCreator.isAccountExist();
- }
+ public void linphoneLogIn() {
+ if (login.getText() == null || login.length() == 0 || password.getText() == null || password.length() == 0) {
+ LinphoneUtils.displayErrorAlert(getString(R.string.first_launch_no_login_password), AssistantActivity.instance());
+ apply.setEnabled(true);
+ return;
+ }
+ accountCreator.setUsername(login.getText().toString());
+ accountCreator.setPassword(password.getText().toString());
+ accountCreator.isAccountExist();
+ }
- private int getPhoneNumberStatus() {
- return accountCreator.setPhoneNumber(phoneNumberEdit.getText().toString(), LinphoneUtils.getCountryCode(dialCode));
- }
+ private int getPhoneNumberStatus() {
+ return accountCreator.setPhoneNumber(phoneNumberEdit.getText().toString(), LinphoneUtils.getCountryCode(dialCode));
+ }
- private void addPhoneNumberHandler(final EditText field, final ImageView icon) {
- field.addTextChangedListener(new TextWatcher() {
- public void afterTextChanged(Editable s) {
- if (field.equals(dialCode)) {
- DialPlan c = AssistantActivity.instance().getCountryListAdapter().getCountryFromCountryCode(dialCode.getText().toString());
- if (c != null) {
- AssistantActivity.instance().country = c;
- selectCountry.setText(c.getCountry());
- } else {
- selectCountry.setText(R.string.select_your_country);
- }
- }
- }
+ private void addPhoneNumberHandler(final EditText field, final ImageView icon) {
+ field.addTextChangedListener(new TextWatcher() {
+ public void afterTextChanged(Editable s) {
+ if (field.equals(dialCode)) {
+ DialPlan c = AssistantActivity.instance().getCountryListAdapter().getCountryFromCountryCode(dialCode.getText().toString());
+ if (c != null) {
+ AssistantActivity.instance().country = c;
+ selectCountry.setText(c.getCountry());
+ } else {
+ selectCountry.setText(R.string.select_your_country);
+ }
+ }
+ }
- public void beforeTextChanged(CharSequence s, int start, int count, int after) {
- }
+ public void beforeTextChanged(CharSequence s, int start, int count, int after) {
+ }
- public void onTextChanged(CharSequence s, int start, int count, int after) {
- onTextChanged2();
- }
- });
- }
+ public void onTextChanged(CharSequence s, int start, int count, int after) {
+ onTextChanged2();
+ }
+ });
+ }
- @Override
- public void onResume() {
- super.onResume();
- if (useUsername != null && useUsername.isChecked())
- recoverAccount = false;
- else
- recoverAccount = true;
- }
+ @Override
+ public void onResume() {
+ super.onResume();
+ if (useUsername != null && useUsername.isChecked())
+ recoverAccount = false;
+ else
+ recoverAccount = true;
+ }
- @Override
- public void onClick(View v) {
- int id = v.getId();
- if(id == R.id.assistant_apply){
- apply.setEnabled(false);
- if (recoverAccount) {
- recoverAccount();
- } else {
- linphoneLogIn();
- }
- }
- else if(id == R.id.info_phone_number){
- new AlertDialog.Builder(getActivity())
- .setTitle(getString(R.string.phone_number_info_title))
- .setMessage(getString(R.string.phone_number_link_info_content))
- .show();
- }
- else if(id == R.id.select_country){
- AssistantActivity.instance().displayCountryChooser();
- }
+ @Override
+ public void onClick(View v) {
+ int id = v.getId();
+ if (id == R.id.assistant_apply) {
+ apply.setEnabled(false);
+ if (recoverAccount) {
+ recoverAccount();
+ } else {
+ linphoneLogIn();
+ }
+ } else if (id == R.id.info_phone_number) {
+ new AlertDialog.Builder(getActivity())
+ .setTitle(getString(R.string.phone_number_info_title))
+ .setMessage(getString(R.string.phone_number_link_info_content))
+ .show();
+ } else if (id == R.id.select_country) {
+ AssistantActivity.instance().displayCountryChooser();
+ }
- }
+ }
- private void recoverAccount() {
- if (phoneNumberEdit.length() > 0 || dialCode.length() > 1) {
- int status = getPhoneNumberStatus();
- boolean isOk = status == AccountCreator.PhoneNumberStatus.Ok.toInt();
- if (isOk) {
- LinphoneManager.getLc().getConfig().loadFromXmlFile(LinphoneManager.getInstance().getmDynamicConfigFile());
- accountCreator.isAliasUsed();
- } else {
- apply.setEnabled(true);
- LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForPhoneNumberStatus(status),
- AssistantActivity.instance());
- LinphoneUtils.displayError(isOk, phoneNumberError,
- LinphoneUtils.errorForPhoneNumberStatus(status));
- }
- } else {
- apply.setEnabled(true);
- LinphoneUtils.displayErrorAlert(getString(R.string.assistant_create_account_part_1), AssistantActivity.instance());
- }
- }
+ private void recoverAccount() {
+ if (phoneNumberEdit.length() > 0 || dialCode.length() > 1) {
+ int status = getPhoneNumberStatus();
+ boolean isOk = status == AccountCreator.PhoneNumberStatus.Ok.toInt();
+ if (isOk) {
+ LinphoneManager.getLc().getConfig().loadFromXmlFile(LinphoneManager.getInstance().getmDynamicConfigFile());
+ accountCreator.isAliasUsed();
+ } else {
+ apply.setEnabled(true);
+ LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForPhoneNumberStatus(status),
+ AssistantActivity.instance());
+ LinphoneUtils.displayError(isOk, phoneNumberError,
+ LinphoneUtils.errorForPhoneNumberStatus(status));
+ }
+ } else {
+ apply.setEnabled(true);
+ LinphoneUtils.displayErrorAlert(getString(R.string.assistant_create_account_part_1), AssistantActivity.instance());
+ }
+ }
- @Override
- public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
+ @Override
+ public void beforeTextChanged(CharSequence s, int start, int count, int after) {
+ }
- public void onTextChanged2() {
- int status = getPhoneNumberStatus();
- boolean isOk = status == AccountCreator.PhoneNumberStatus.Ok.toInt();
- LinphoneUtils.displayError(isOk, phoneNumberError, LinphoneUtils.errorForPhoneNumberStatus(status));
- if (!isOk) {
- if ((1 == (status & AccountCreator.PhoneNumberStatus.InvalidCountryCode.toInt()))) {
- dialCode.setBackgroundResource(R.drawable.resizable_textfield_error);
- phoneNumberEdit.setBackgroundResource(R.drawable.resizable_textfield);
- } else {
- dialCode.setBackgroundResource(R.drawable.resizable_textfield);
- phoneNumberEdit.setBackgroundResource(R.drawable.resizable_textfield_error);
- }
- } else {
- accountCreator.setPhoneNumber(phoneNumberEdit.getText().toString(), dialCode.getText().toString());
- dialCode.setBackgroundResource(R.drawable.resizable_textfield);
- phoneNumberEdit.setBackgroundResource(R.drawable.resizable_textfield);
- }
- }
+ public void onTextChanged2() {
+ int status = getPhoneNumberStatus();
+ boolean isOk = status == AccountCreator.PhoneNumberStatus.Ok.toInt();
+ LinphoneUtils.displayError(isOk, phoneNumberError, LinphoneUtils.errorForPhoneNumberStatus(status));
+ if (!isOk) {
+ if ((1 == (status & AccountCreator.PhoneNumberStatus.InvalidCountryCode.toInt()))) {
+ dialCode.setBackgroundResource(R.drawable.resizable_textfield_error);
+ phoneNumberEdit.setBackgroundResource(R.drawable.resizable_textfield);
+ } else {
+ dialCode.setBackgroundResource(R.drawable.resizable_textfield);
+ phoneNumberEdit.setBackgroundResource(R.drawable.resizable_textfield_error);
+ }
+ } else {
+ accountCreator.setPhoneNumber(phoneNumberEdit.getText().toString(), dialCode.getText().toString());
+ dialCode.setBackgroundResource(R.drawable.resizable_textfield);
+ phoneNumberEdit.setBackgroundResource(R.drawable.resizable_textfield);
+ }
+ }
- @Override
- public void onTextChanged(CharSequence s, int start, int before, int count) {
- onTextChanged2();
- }
+ @Override
+ public void onTextChanged(CharSequence s, int start, int before, int count) {
+ onTextChanged2();
+ }
- @Override
- public void afterTextChanged(Editable s) {}
+ @Override
+ public void afterTextChanged(Editable s) {
+ }
- @Override
- public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
- if(buttonView.getId() == R.id.use_username) {
- if(isChecked) {
- usernameLayout.setVisibility(View.VISIBLE);
- passwordLayout.setVisibility(View.VISIBLE);
- phoneNumberEdit.setVisibility(EditText.GONE);
- phoneNumberLayout.setVisibility(LinearLayout.GONE);
- messagePhoneNumber.setText(getString(R.string.assistant_linphone_login_desc));
- recoverAccount = false;
- } else {
- usernameLayout.setVisibility(View.GONE);
- passwordLayout.setVisibility(View.GONE);
- phoneNumberEdit.setVisibility(EditText.VISIBLE);
- phoneNumberLayout.setVisibility(LinearLayout.VISIBLE);
- messagePhoneNumber.setText(getString(R.string.assistant_create_account_part_1));
- recoverAccount = true;
- }
- }
- }
+ @Override
+ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
+ if (buttonView.getId() == R.id.use_username) {
+ if (isChecked) {
+ usernameLayout.setVisibility(View.VISIBLE);
+ passwordLayout.setVisibility(View.VISIBLE);
+ phoneNumberEdit.setVisibility(EditText.GONE);
+ phoneNumberLayout.setVisibility(LinearLayout.GONE);
+ messagePhoneNumber.setText(getString(R.string.assistant_linphone_login_desc));
+ recoverAccount = false;
+ } else {
+ usernameLayout.setVisibility(View.GONE);
+ passwordLayout.setVisibility(View.GONE);
+ phoneNumberEdit.setVisibility(EditText.VISIBLE);
+ phoneNumberLayout.setVisibility(LinearLayout.VISIBLE);
+ messagePhoneNumber.setText(getString(R.string.assistant_create_account_part_1));
+ recoverAccount = true;
+ }
+ }
+ }
- @Override
- public void onIsAccountExist(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
- if (AssistantActivity.instance() == null) {
- apply.setEnabled(true);
- return;
- }
- if (status.equals(AccountCreator.Status.AccountExist) || status.equals(AccountCreator.Status.AccountExistWithAlias)) {
- AssistantActivity.instance().linphoneLogIn(accountCreator);
- } else {
- LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForStatus(status), AssistantActivity.instance());
- }
- apply.setEnabled(true);
- }
+ @Override
+ public void onIsAccountExist(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
+ if (AssistantActivity.instance() == null) {
+ apply.setEnabled(true);
+ return;
+ }
+ if (status.equals(AccountCreator.Status.AccountExist) || status.equals(AccountCreator.Status.AccountExistWithAlias)) {
+ AssistantActivity.instance().linphoneLogIn(accountCreator);
+ } else {
+ LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForStatus(status), AssistantActivity.instance());
+ }
+ apply.setEnabled(true);
+ }
- @Override
- public void onCreateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
- }
+ @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 onActivateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
+ }
- @Override
- public void onLinkAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
- }
+ @Override
+ public void onLinkAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
+ }
- @Override
- public void onActivateAlias(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
- }
+ @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 onIsAccountActivated(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
+ }
- @Override
- public void onRecoverAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
- if (AssistantActivity.instance() == null) {
- apply.setEnabled(true);
- return;
- }
- if (status.equals(AccountCreator.Status.ServerError)) {
- LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForStatus(AccountCreator.Status.RequestFailed), AssistantActivity.instance());
- apply.setEnabled(true);
- } else {
- AssistantActivity.instance().displayAssistantCodeConfirm(accountCreator.getUsername(), phoneNumberEdit.getText().toString(), LinphoneUtils.getCountryCode(dialCode), true);
- }
- }
+ @Override
+ public void onRecoverAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
+ if (AssistantActivity.instance() == null) {
+ apply.setEnabled(true);
+ return;
+ }
+ if (status.equals(AccountCreator.Status.ServerError)) {
+ LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForStatus(AccountCreator.Status.RequestFailed), AssistantActivity.instance());
+ apply.setEnabled(true);
+ } else {
+ AssistantActivity.instance().displayAssistantCodeConfirm(accountCreator.getUsername(), phoneNumberEdit.getText().toString(), LinphoneUtils.getCountryCode(dialCode), true);
+ }
+ }
- @Override
- public void onIsAccountLinked(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
- }
+ @Override
+ public void onIsAccountLinked(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
+ }
- @Override
- public void onIsAliasUsed(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
- if (AssistantActivity.instance() == null) {
- apply.setEnabled(true);
- return;
- }
- if (status.equals(AccountCreator.Status.AliasIsAccount) || status.equals(AccountCreator.Status.AliasExist)) {
- accountCreator.recoverAccount();
- } else {
- apply.setEnabled(true);
- LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForStatus(status), AssistantActivity.instance());
- }
- }
+ @Override
+ public void onIsAliasUsed(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
+ if (AssistantActivity.instance() == null) {
+ apply.setEnabled(true);
+ return;
+ }
+ if (status.equals(AccountCreator.Status.AliasIsAccount) || status.equals(AccountCreator.Status.AliasExist)) {
+ accountCreator.recoverAccount();
+ } else {
+ apply.setEnabled(true);
+ LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForStatus(status), AssistantActivity.instance());
+ }
+ }
- @Override
- public void onUpdateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
+ @Override
+ public void onUpdateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) {
- }
+ }
}
diff --git a/src/android/org/linphone/assistant/LoginFragment.java b/src/android/org/linphone/assistant/LoginFragment.java
index 70621c1b5..e0088f7d9 100644
--- a/src/android/org/linphone/assistant/LoginFragment.java
+++ b/src/android/org/linphone/assistant/LoginFragment.java
@@ -17,8 +17,6 @@ You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
-import org.linphone.R;
-import org.linphone.core.TransportType;
import android.app.Fragment;
import android.os.Bundle;
@@ -33,73 +31,77 @@ import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;
+import org.linphone.R;
+import org.linphone.core.TransportType;
+
public class LoginFragment extends Fragment implements OnClickListener, TextWatcher {
- private EditText login, userid, password, domain, displayName;
- private RadioGroup transports;
- private Button apply;
+ private EditText login, userid, password, domain, displayName;
+ private RadioGroup transports;
+ private Button apply;
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- View view = inflater.inflate(R.layout.assistant_login, container, false);
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container,
+ Bundle savedInstanceState) {
+ View view = inflater.inflate(R.layout.assistant_login, container, false);
- login = view.findViewById(R.id.assistant_username);
- login.addTextChangedListener(this);
- displayName = view.findViewById(R.id.assistant_display_name);
- displayName.addTextChangedListener(this);
- userid = view.findViewById(R.id.assistant_userid);
- userid.addTextChangedListener(this);
- password = view.findViewById(R.id.assistant_password);
- password.addTextChangedListener(this);
- domain = view.findViewById(R.id.assistant_domain);
- domain.addTextChangedListener(this);
- transports = view.findViewById(R.id.assistant_transports);
- apply = view.findViewById(R.id.assistant_apply);
- apply.setEnabled(false);
- apply.setOnClickListener(this);
+ login = view.findViewById(R.id.assistant_username);
+ login.addTextChangedListener(this);
+ displayName = view.findViewById(R.id.assistant_display_name);
+ displayName.addTextChangedListener(this);
+ userid = view.findViewById(R.id.assistant_userid);
+ userid.addTextChangedListener(this);
+ password = view.findViewById(R.id.assistant_password);
+ password.addTextChangedListener(this);
+ domain = view.findViewById(R.id.assistant_domain);
+ domain.addTextChangedListener(this);
+ transports = view.findViewById(R.id.assistant_transports);
+ apply = view.findViewById(R.id.assistant_apply);
+ apply.setEnabled(false);
+ apply.setOnClickListener(this);
- return view;
- }
+ return view;
+ }
- @Override
- public void onClick(View v) {
- int id = v.getId();
+ @Override
+ public void onClick(View v) {
+ int id = v.getId();
- if (id == R.id.assistant_apply) {
- if (login.getText() == null || login.length() == 0 || password.getText() == null || password.length() == 0 || domain.getText() == null || domain.length() == 0) {
- Toast.makeText(getActivity(), getString(R.string.first_launch_no_login_password), Toast.LENGTH_LONG).show();
- return;
- }
+ if (id == R.id.assistant_apply) {
+ if (login.getText() == null || login.length() == 0 || password.getText() == null || password.length() == 0 || domain.getText() == null || domain.length() == 0) {
+ Toast.makeText(getActivity(), getString(R.string.first_launch_no_login_password), Toast.LENGTH_LONG).show();
+ return;
+ }
- TransportType transport;
- if(transports.getCheckedRadioButtonId() == R.id.transport_udp){
- transport = TransportType.Udp;
- } else {
- if(transports.getCheckedRadioButtonId() == R.id.transport_tcp){
- transport = TransportType.Tcp;
- } else {
- transport = TransportType.Tls;
- }
- }
+ TransportType transport;
+ if (transports.getCheckedRadioButtonId() == R.id.transport_udp) {
+ transport = TransportType.Udp;
+ } else {
+ if (transports.getCheckedRadioButtonId() == R.id.transport_tcp) {
+ transport = TransportType.Tcp;
+ } else {
+ transport = TransportType.Tls;
+ }
+ }
- if (domain.getText().toString().compareTo(getString(R.string.default_domain)) == 0) {
- AssistantActivity.instance().displayLoginLinphone(login.getText().toString(), password.getText().toString());
- } else {
- AssistantActivity.instance().genericLogIn(login.getText().toString(), userid.getText().toString(), password.getText().toString(), displayName.getText().toString(), null, domain.getText().toString(), transport);
- }
- }
- }
+ if (domain.getText().toString().compareTo(getString(R.string.default_domain)) == 0) {
+ AssistantActivity.instance().displayLoginLinphone(login.getText().toString(), password.getText().toString());
+ } else {
+ AssistantActivity.instance().genericLogIn(login.getText().toString(), userid.getText().toString(), password.getText().toString(), displayName.getText().toString(), null, domain.getText().toString(), transport);
+ }
+ }
+ }
- @Override
- public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
+ @Override
+ public void beforeTextChanged(CharSequence s, int start, int count, int after) {
+ }
- @Override
- public void onTextChanged(CharSequence s, int start, int before, int count) {
- apply.setEnabled(!login.getText().toString().isEmpty() && !password.getText().toString().isEmpty() && !domain.getText().toString().isEmpty());
- }
+ @Override
+ public void onTextChanged(CharSequence s, int start, int before, int count) {
+ apply.setEnabled(!login.getText().toString().isEmpty() && !password.getText().toString().isEmpty() && !domain.getText().toString().isEmpty());
+ }
- @Override
- public void afterTextChanged(Editable s) {
+ @Override
+ public void afterTextChanged(Editable s) {
- }
+ }
}
diff --git a/src/android/org/linphone/assistant/RemoteProvisioningActivity.java b/src/android/org/linphone/assistant/RemoteProvisioningActivity.java
index 795172734..114af2e88 100644
--- a/src/android/org/linphone/assistant/RemoteProvisioningActivity.java
+++ b/src/android/org/linphone/assistant/RemoteProvisioningActivity.java
@@ -18,19 +18,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.io.UnsupportedEncodingException;
-import java.net.URLDecoder;
-
-import org.linphone.activities.LinphoneLauncherActivity;
-import org.linphone.LinphoneManager;
-import org.linphone.LinphonePreferences;
-import org.linphone.LinphoneService;
-import org.linphone.R;
-import org.linphone.core.Core;
-import org.linphone.core.ConfiguringState;
-import org.linphone.core.CoreListenerStub;
-import org.linphone.mediastream.Log;
-
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
@@ -42,158 +29,171 @@ import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
+import org.linphone.LinphoneManager;
+import org.linphone.LinphonePreferences;
+import org.linphone.LinphoneService;
+import org.linphone.R;
+import org.linphone.activities.LinphoneLauncherActivity;
+import org.linphone.core.ConfiguringState;
+import org.linphone.core.Core;
+import org.linphone.core.CoreListenerStub;
+import org.linphone.mediastream.Log;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URLDecoder;
+
public class RemoteProvisioningActivity extends Activity {
- private Handler mHandler = new Handler();
- private String configUriParam = null;
- private ProgressBar spinner;
- private CoreListenerStub mListener;
+ private Handler mHandler = new Handler();
+ private String configUriParam = null;
+ private ProgressBar spinner;
+ private CoreListenerStub mListener;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.remote_provisioning);
- spinner = findViewById(R.id.spinner);
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.remote_provisioning);
+ spinner = findViewById(R.id.spinner);
- mListener = new CoreListenerStub(){
- @Override
- public void onConfiguringStatus(Core lc, final ConfiguringState state, String message) {
- if (spinner != null) spinner.setVisibility(View.GONE);
- if (state == ConfiguringState.Successful) {
- goToLinphoneActivity();
- } else if (state == ConfiguringState.Failed) {
- Toast.makeText(RemoteProvisioningActivity.this, R.string.remote_provisioning_failure, Toast.LENGTH_LONG).show();
- }
- }
- };
- }
+ mListener = new CoreListenerStub() {
+ @Override
+ public void onConfiguringStatus(Core lc, final ConfiguringState state, String message) {
+ if (spinner != null) spinner.setVisibility(View.GONE);
+ if (state == ConfiguringState.Successful) {
+ goToLinphoneActivity();
+ } else if (state == ConfiguringState.Failed) {
+ Toast.makeText(RemoteProvisioningActivity.this, R.string.remote_provisioning_failure, Toast.LENGTH_LONG).show();
+ }
+ }
+ };
+ }
- @Override
- protected void onResume() {
- super.onResume();
- Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- if (lc != null) {
- lc.addListener(mListener);
- }
- LinphonePreferences.instance().setContext(this);
+ @Override
+ protected void onResume() {
+ super.onResume();
+ Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ if (lc != null) {
+ lc.addListener(mListener);
+ }
+ LinphonePreferences.instance().setContext(this);
- checkIntentForConfigUri(getIntent());
- }
+ checkIntentForConfigUri(getIntent());
+ }
- @Override
- protected void onPause() {
- Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- if (lc != null) {
- lc.removeListener(mListener);
- }
- super.onPause();
- }
+ @Override
+ protected void onPause() {
+ Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ if (lc != null) {
+ lc.removeListener(mListener);
+ }
+ super.onPause();
+ }
- @Override
- protected void onDestroy() {
- super.onDestroy();
- }
+ @Override
+ protected void onDestroy() {
+ super.onDestroy();
+ }
- @Override
- protected void onNewIntent(Intent intent) {
- super.onNewIntent(intent);
- checkIntentForConfigUri(intent);
- }
+ @Override
+ protected void onNewIntent(Intent intent) {
+ super.onNewIntent(intent);
+ checkIntentForConfigUri(intent);
+ }
- private void checkIntentForConfigUri(final Intent intent) {
- new Thread(new Runnable() {
+ private void checkIntentForConfigUri(final Intent intent) {
+ new Thread(new Runnable() {
- @Override
- public void run() {
- Uri openUri = intent.getData();
- if (openUri != null) {
- // We expect something like linphone-config://http://linphone.org/config.xml
- configUriParam = openUri.getEncodedSchemeSpecificPart().substring(2); // Removes the linphone-config://
- try {
- configUriParam = URLDecoder.decode(configUriParam, "UTF-8");
- } catch (UnsupportedEncodingException e) {
- Log.e(e);
- }
- Log.d("Using config uri: " + configUriParam);
- }
+ @Override
+ public void run() {
+ Uri openUri = intent.getData();
+ if (openUri != null) {
+ // We expect something like linphone-config://http://linphone.org/config.xml
+ configUriParam = openUri.getEncodedSchemeSpecificPart().substring(2); // Removes the linphone-config://
+ try {
+ configUriParam = URLDecoder.decode(configUriParam, "UTF-8");
+ } catch (UnsupportedEncodingException e) {
+ Log.e(e);
+ }
+ Log.d("Using config uri: " + configUriParam);
+ }
- if (configUriParam == null) {
- if (!LinphonePreferences.instance().isFirstRemoteProvisioning()) {
- mHandler.post(new Runnable() {
- @Override
- public void run() {
- goToLinphoneActivity();
- }
- });
- } else if (!getResources().getBoolean(R.bool.forbid_app_usage_until_remote_provisioning_completed)) {
- // Show this view for a few seconds then go to the dialer
- mHandler.postDelayed(new Runnable() {
- @Override
- public void run() {
- goToLinphoneActivity();
- }
- }, 1500);
- } // else we do nothing if there is no config uri parameter and if user not allowed to leave this screen
- } else {
- if (getResources().getBoolean(R.bool.display_confirmation_popup_after_first_configuration)
- && !LinphonePreferences.instance().isFirstRemoteProvisioning()) {
- mHandler.post(new Runnable() {
- @Override
- public void run() {
- displayDialogConfirmation();
- }
- });
- } else {
- mHandler.post(new Runnable() {
- @Override
- public void run() {
- setRemoteProvisioningAddressAndRestart(configUriParam);
- }
- });
- }
- }
- }
- }).start();
- }
+ if (configUriParam == null) {
+ if (!LinphonePreferences.instance().isFirstRemoteProvisioning()) {
+ mHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ goToLinphoneActivity();
+ }
+ });
+ } else if (!getResources().getBoolean(R.bool.forbid_app_usage_until_remote_provisioning_completed)) {
+ // Show this view for a few seconds then go to the dialer
+ mHandler.postDelayed(new Runnable() {
+ @Override
+ public void run() {
+ goToLinphoneActivity();
+ }
+ }, 1500);
+ } // else we do nothing if there is no config uri parameter and if user not allowed to leave this screen
+ } else {
+ if (getResources().getBoolean(R.bool.display_confirmation_popup_after_first_configuration)
+ && !LinphonePreferences.instance().isFirstRemoteProvisioning()) {
+ mHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ displayDialogConfirmation();
+ }
+ });
+ } else {
+ mHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ setRemoteProvisioningAddressAndRestart(configUriParam);
+ }
+ });
+ }
+ }
+ }
+ }).start();
+ }
- private void displayDialogConfirmation() {
- new AlertDialog.Builder(RemoteProvisioningActivity.this)
- .setTitle(getString(R.string.remote_provisioning_again_title))
- .setMessage(getString(R.string.remote_provisioning_again_message))
- .setPositiveButton(R.string.accept, new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- setRemoteProvisioningAddressAndRestart(configUriParam);
- }
- })
- .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- goToLinphoneActivity();
- }
- })
- .show();
- }
+ private void displayDialogConfirmation() {
+ new AlertDialog.Builder(RemoteProvisioningActivity.this)
+ .setTitle(getString(R.string.remote_provisioning_again_title))
+ .setMessage(getString(R.string.remote_provisioning_again_message))
+ .setPositiveButton(R.string.accept, new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int which) {
+ setRemoteProvisioningAddressAndRestart(configUriParam);
+ }
+ })
+ .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int which) {
+ goToLinphoneActivity();
+ }
+ })
+ .show();
+ }
- private void setRemoteProvisioningAddressAndRestart(final String configUri) {
- if (spinner != null) spinner.setVisibility(View.VISIBLE);
+ private void setRemoteProvisioningAddressAndRestart(final String configUri) {
+ if (spinner != null) spinner.setVisibility(View.VISIBLE);
- LinphonePreferences.instance().setContext(this); // Needed, else the next call will crash
- LinphonePreferences.instance().setRemoteProvisioningUrl(configUri);
+ LinphonePreferences.instance().setContext(this); // Needed, else the next call will crash
+ LinphonePreferences.instance().setRemoteProvisioningUrl(configUri);
- mHandler.postDelayed(new Runnable() {
- @Override
- public void run() {
- LinphoneManager.getInstance().restartCore();
- }
- }, 1000);
- }
+ mHandler.postDelayed(new Runnable() {
+ @Override
+ public void run() {
+ LinphoneManager.getInstance().restartCore();
+ }
+ }, 1000);
+ }
- private void goToLinphoneActivity() {
- if (LinphoneService.isReady()) {
- LinphoneService.instance().setActivityToLaunchOnIncomingReceived("org.linphone.activities.LinphoneLauncherActivity");
- //finish(); // To prevent the user to come back to this page using back button
- startActivity(new Intent().setClass(this, LinphoneLauncherActivity.class));
- } else {
- finish();
- }
- }
+ private void goToLinphoneActivity() {
+ if (LinphoneService.isReady()) {
+ LinphoneService.instance().setActivityToLaunchOnIncomingReceived("org.linphone.activities.LinphoneLauncherActivity");
+ //finish(); // To prevent the user to come back to this page using back button
+ startActivity(new Intent().setClass(this, LinphoneLauncherActivity.class));
+ } else {
+ finish();
+ }
+ }
}
diff --git a/src/android/org/linphone/assistant/RemoteProvisioningFragment.java b/src/android/org/linphone/assistant/RemoteProvisioningFragment.java
index 9b9a1172f..9b1936e59 100644
--- a/src/android/org/linphone/assistant/RemoteProvisioningFragment.java
+++ b/src/android/org/linphone/assistant/RemoteProvisioningFragment.java
@@ -18,10 +18,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 org.linphone.LinphoneManager;
-import org.linphone.LinphonePreferences;
-import org.linphone.R;
-
import android.app.Fragment;
import android.os.Bundle;
import android.text.Editable;
@@ -33,50 +29,54 @@ import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
-public class RemoteProvisioningFragment extends Fragment implements OnClickListener, TextWatcher{
- private EditText remoteProvisioningUrl;
- private Button apply;
+import org.linphone.LinphoneManager;
+import org.linphone.LinphonePreferences;
+import org.linphone.R;
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- View view = inflater.inflate(R.layout.assistant_remote_provisioning, container, false);
+public class RemoteProvisioningFragment extends Fragment implements OnClickListener, TextWatcher {
+ private EditText remoteProvisioningUrl;
+ private Button apply;
- remoteProvisioningUrl = view.findViewById(R.id.assistant_remote_provisioning_url);
- remoteProvisioningUrl.addTextChangedListener(this);
- apply = view.findViewById(R.id.assistant_apply);
- apply.setEnabled(false);
- apply.setOnClickListener(this);
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container,
+ Bundle savedInstanceState) {
+ View view = inflater.inflate(R.layout.assistant_remote_provisioning, container, false);
- return view;
- }
+ remoteProvisioningUrl = view.findViewById(R.id.assistant_remote_provisioning_url);
+ remoteProvisioningUrl.addTextChangedListener(this);
+ apply = view.findViewById(R.id.assistant_apply);
+ apply.setEnabled(false);
+ apply.setOnClickListener(this);
- @Override
- public void onClick(View v) {
- int id = v.getId();
+ return view;
+ }
- if (id == R.id.assistant_apply) {
- String url = remoteProvisioningUrl.getText().toString();
- AssistantActivity.instance().displayRemoteProvisioningInProgressDialog();
- LinphonePreferences.instance().setRemoteProvisioningUrl(url);
- LinphoneManager.getLc().getConfig().sync();
- LinphoneManager.getInstance().restartCore();
- AssistantActivity.instance().setCoreListener();
- }
- }
+ @Override
+ public void onClick(View v) {
+ int id = v.getId();
- @Override
- public void beforeTextChanged(CharSequence s, int start, int count, int after) {
+ if (id == R.id.assistant_apply) {
+ String url = remoteProvisioningUrl.getText().toString();
+ AssistantActivity.instance().displayRemoteProvisioningInProgressDialog();
+ LinphonePreferences.instance().setRemoteProvisioningUrl(url);
+ LinphoneManager.getLc().getConfig().sync();
+ LinphoneManager.getInstance().restartCore();
+ AssistantActivity.instance().setCoreListener();
+ }
+ }
- }
+ @Override
+ public void beforeTextChanged(CharSequence s, int start, int count, int after) {
- @Override
- public void onTextChanged(CharSequence s, int start, int before, int count) {
- apply.setEnabled(!remoteProvisioningUrl.getText().toString().isEmpty());
- }
+ }
- @Override
- public void afterTextChanged(Editable s) {
+ @Override
+ public void onTextChanged(CharSequence s, int start, int before, int count) {
+ apply.setEnabled(!remoteProvisioningUrl.getText().toString().isEmpty());
+ }
- }
+ @Override
+ public void afterTextChanged(Editable s) {
+
+ }
}
diff --git a/src/android/org/linphone/assistant/RemoteProvisioningLoginActivity.java b/src/android/org/linphone/assistant/RemoteProvisioningLoginActivity.java
index 7556b994e..c3384a391 100644
--- a/src/android/org/linphone/assistant/RemoteProvisioningLoginActivity.java
+++ b/src/android/org/linphone/assistant/RemoteProvisioningLoginActivity.java
@@ -18,6 +18,14 @@ along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
+import android.app.Activity;
+import android.os.Bundle;
+import android.view.View;
+import android.view.View.OnClickListener;
+import android.widget.Button;
+import android.widget.EditText;
+import android.widget.Toast;
+
import org.linphone.LinphoneManager;
import org.linphone.LinphonePreferences;
import org.linphone.R;
@@ -27,105 +35,97 @@ import org.linphone.core.CoreListenerStub;
import org.linphone.xmlrpc.XmlRpcHelper;
import org.linphone.xmlrpc.XmlRpcListenerBase;
-import android.app.Activity;
-import android.os.Bundle;
-import android.view.View;
-import android.view.View.OnClickListener;
-import android.widget.Button;
-import android.widget.EditText;
-import android.widget.Toast;
-
public class RemoteProvisioningLoginActivity extends Activity implements OnClickListener {
- private EditText login, password, domain;
- private Button connect;
- private CoreListenerStub mListener;
+ private EditText login, password, domain;
+ private Button connect;
+ private CoreListenerStub mListener;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.assistant_remote_provisioning_login);
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.assistant_remote_provisioning_login);
- login = findViewById(R.id.assistant_username);
- password = findViewById(R.id.assistant_password);
- domain = findViewById(R.id.assistant_domain);
+ login = findViewById(R.id.assistant_username);
+ password = findViewById(R.id.assistant_password);
+ domain = findViewById(R.id.assistant_domain);
- connect = findViewById(R.id.assistant_connect);
- connect.setOnClickListener(this);
+ connect = findViewById(R.id.assistant_connect);
+ connect.setOnClickListener(this);
- String defaultDomain = getIntent().getStringExtra("Domain");
- if (defaultDomain != null) {
- domain.setText(defaultDomain);
- domain.setEnabled(false);
- }
+ String defaultDomain = getIntent().getStringExtra("Domain");
+ if (defaultDomain != null) {
+ domain.setText(defaultDomain);
+ domain.setEnabled(false);
+ }
- mListener = new CoreListenerStub(){
- @Override
- public void onConfiguringStatus(Core lc, final ConfiguringState state, String message) {
- if (state == ConfiguringState.Successful) {
- //TODO
- } else if (state == ConfiguringState.Failed) {
- Toast.makeText(RemoteProvisioningLoginActivity.this, R.string.remote_provisioning_failure, Toast.LENGTH_LONG).show();
- }
- }
- };
- }
+ mListener = new CoreListenerStub() {
+ @Override
+ public void onConfiguringStatus(Core lc, final ConfiguringState state, String message) {
+ if (state == ConfiguringState.Successful) {
+ //TODO
+ } else if (state == ConfiguringState.Failed) {
+ Toast.makeText(RemoteProvisioningLoginActivity.this, R.string.remote_provisioning_failure, Toast.LENGTH_LONG).show();
+ }
+ }
+ };
+ }
- private void cancelWizard(boolean bypassCheck) {
- if (bypassCheck || getResources().getBoolean(R.bool.allow_cancel_remote_provisioning_login_activity)) {
- LinphonePreferences.instance().disableProvisioningLoginView();
- setResult(bypassCheck ? Activity.RESULT_OK : Activity.RESULT_CANCELED);
- finish();
- }
- }
+ private void cancelWizard(boolean bypassCheck) {
+ if (bypassCheck || getResources().getBoolean(R.bool.allow_cancel_remote_provisioning_login_activity)) {
+ LinphonePreferences.instance().disableProvisioningLoginView();
+ setResult(bypassCheck ? Activity.RESULT_OK : Activity.RESULT_CANCELED);
+ finish();
+ }
+ }
- private boolean storeAccount(String username, String password, String domain) {
- XmlRpcHelper xmlRpcHelper = new XmlRpcHelper();
- xmlRpcHelper.getRemoteProvisioningFilenameAsync(new XmlRpcListenerBase() {
- @Override
- public void onRemoteProvisioningFilenameSent(String result) {
- LinphonePreferences.instance().setRemoteProvisioningUrl(result);
- LinphoneManager.getInstance().restartCore();
- }
- }, username.toString(), password.toString(), domain.toString());
+ private boolean storeAccount(String username, String password, String domain) {
+ XmlRpcHelper xmlRpcHelper = new XmlRpcHelper();
+ xmlRpcHelper.getRemoteProvisioningFilenameAsync(new XmlRpcListenerBase() {
+ @Override
+ public void onRemoteProvisioningFilenameSent(String result) {
+ LinphonePreferences.instance().setRemoteProvisioningUrl(result);
+ LinphoneManager.getInstance().restartCore();
+ }
+ }, username.toString(), password.toString(), domain.toString());
- LinphonePreferences.instance().firstLaunchSuccessful();
- setResult(Activity.RESULT_OK);
- finish();
- return true;
- }
+ LinphonePreferences.instance().firstLaunchSuccessful();
+ setResult(Activity.RESULT_OK);
+ finish();
+ return true;
+ }
- @Override
- protected void onResume() {
- super.onResume();
- Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- if (lc != null) {
- lc.addListener(mListener);
- }
- }
+ @Override
+ protected void onResume() {
+ super.onResume();
+ Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ if (lc != null) {
+ lc.addListener(mListener);
+ }
+ }
- @Override
- protected void onPause() {
- Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- if (lc != null) {
- lc.removeListener(mListener);
- }
- super.onPause();
- }
+ @Override
+ protected void onPause() {
+ Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ if (lc != null) {
+ lc.removeListener(mListener);
+ }
+ super.onPause();
+ }
- @Override
- public void onClick(View v) {
- int id = v.getId();
+ @Override
+ public void onClick(View v) {
+ int id = v.getId();
- if (id == R.id.cancel) {
- cancelWizard(false);
- }
- if (id == R.id.assistant_connect){
- storeAccount(login.getText().toString(), password.getText().toString(), domain.getText().toString());
- }
- }
+ if (id == R.id.cancel) {
+ cancelWizard(false);
+ }
+ if (id == R.id.assistant_connect) {
+ storeAccount(login.getText().toString(), password.getText().toString(), domain.getText().toString());
+ }
+ }
- @Override
- public void onBackPressed() {
- cancelWizard(false);
- }
+ @Override
+ public void onBackPressed() {
+ cancelWizard(false);
+ }
}
diff --git a/src/android/org/linphone/assistant/WelcomeFragment.java b/src/android/org/linphone/assistant/WelcomeFragment.java
index 070aac22c..8440b409f 100644
--- a/src/android/org/linphone/assistant/WelcomeFragment.java
+++ b/src/android/org/linphone/assistant/WelcomeFragment.java
@@ -18,8 +18,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 org.linphone.R;
-
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
@@ -28,52 +26,54 @@ import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
+import org.linphone.R;
+
public class WelcomeFragment extends Fragment implements OnClickListener {
- private Button createAccount, logLinphoneAccount, logGenericAccount, remoteProvisioning;
+ private Button createAccount, logLinphoneAccount, logGenericAccount, remoteProvisioning;
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- View view = inflater.inflate(R.layout.assistant_welcome, container, false);
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container,
+ Bundle savedInstanceState) {
+ View view = inflater.inflate(R.layout.assistant_welcome, container, false);
- createAccount = view.findViewById(R.id.create_account);
- createAccount.setOnClickListener(this);
+ createAccount = view.findViewById(R.id.create_account);
+ createAccount.setOnClickListener(this);
- logLinphoneAccount = view.findViewById(R.id.login_linphone);
- if (getResources().getBoolean(R.bool.hide_linphone_accounts_in_assistant)) {
- logLinphoneAccount.setVisibility(View.GONE);
- } else {
- logLinphoneAccount.setOnClickListener(this);
- }
+ logLinphoneAccount = view.findViewById(R.id.login_linphone);
+ if (getResources().getBoolean(R.bool.hide_linphone_accounts_in_assistant)) {
+ logLinphoneAccount.setVisibility(View.GONE);
+ } else {
+ logLinphoneAccount.setOnClickListener(this);
+ }
- logGenericAccount = view.findViewById(R.id.login_generic);
- if (getResources().getBoolean(R.bool.hide_generic_accounts_in_assistant)) {
- logGenericAccount.setVisibility(View.GONE);
- } else {
- logGenericAccount.setOnClickListener(this);
- }
+ logGenericAccount = view.findViewById(R.id.login_generic);
+ if (getResources().getBoolean(R.bool.hide_generic_accounts_in_assistant)) {
+ logGenericAccount.setVisibility(View.GONE);
+ } else {
+ logGenericAccount.setOnClickListener(this);
+ }
- remoteProvisioning = view.findViewById(R.id.remote_provisioning);
- if (getResources().getBoolean(R.bool.hide_remote_provisioning_in_assistant)) {
- remoteProvisioning.setVisibility(View.GONE);
- } else {
- remoteProvisioning.setOnClickListener(this);
- }
+ remoteProvisioning = view.findViewById(R.id.remote_provisioning);
+ if (getResources().getBoolean(R.bool.hide_remote_provisioning_in_assistant)) {
+ remoteProvisioning.setVisibility(View.GONE);
+ } else {
+ remoteProvisioning.setOnClickListener(this);
+ }
- return view;
- }
+ return view;
+ }
- @Override
- public void onClick(View v) {
- int id = v.getId();
- if (id == R.id.login_generic) {
- AssistantActivity.instance().displayLoginGeneric();
- } else if (id == R.id.login_linphone) {
- AssistantActivity.instance().displayLoginLinphone(null, null);
- } else if (id == R.id.create_account) {
- AssistantActivity.instance().displayCreateAccount();
- } else if (id == R.id.remote_provisioning) {
- AssistantActivity.instance().displayRemoteProvisioning();
- }
- }
+ @Override
+ public void onClick(View v) {
+ int id = v.getId();
+ if (id == R.id.login_generic) {
+ AssistantActivity.instance().displayLoginGeneric();
+ } else if (id == R.id.login_linphone) {
+ AssistantActivity.instance().displayLoginLinphone(null, null);
+ } else if (id == R.id.create_account) {
+ AssistantActivity.instance().displayCreateAccount();
+ } else if (id == R.id.remote_provisioning) {
+ AssistantActivity.instance().displayRemoteProvisioning();
+ }
+ }
}
diff --git a/src/android/org/linphone/call/CallActivity.java b/src/android/org/linphone/call/CallActivity.java
index dc3ca40e0..ac15ecf15 100644
--- a/src/android/org/linphone/call/CallActivity.java
+++ b/src/android/org/linphone/call/CallActivity.java
@@ -59,9 +59,6 @@ import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
-import org.linphone.receivers.BluetoothManager;
-import org.linphone.contacts.ContactsManager;
-import org.linphone.contacts.LinphoneContact;
import org.linphone.LinphoneManager;
import org.linphone.LinphonePreferences;
import org.linphone.LinphoneService;
@@ -69,24 +66,27 @@ import org.linphone.LinphoneUtils;
import org.linphone.R;
import org.linphone.activities.LinphoneActivity;
import org.linphone.activities.LinphoneGenericActivity;
+import org.linphone.contacts.ContactsManager;
+import org.linphone.contacts.LinphoneContact;
import org.linphone.core.Address;
+import org.linphone.core.AddressFamily;
import org.linphone.core.Call;
-import org.linphone.core.CallListenerStub;
import org.linphone.core.Call.State;
+import org.linphone.core.CallListenerStub;
import org.linphone.core.CallParams;
import org.linphone.core.CallStats;
-import org.linphone.core.AddressFamily;
import org.linphone.core.ChatMessage;
import org.linphone.core.ChatRoom;
import org.linphone.core.Core;
import org.linphone.core.CoreListenerStub;
import org.linphone.core.MediaEncryption;
-import org.linphone.core.Player;
import org.linphone.core.PayloadType;
+import org.linphone.core.Player;
import org.linphone.core.StreamType;
import org.linphone.fragments.StatusFragment;
import org.linphone.mediastream.Log;
import org.linphone.mediastream.video.capture.hwconf.AndroidCameraConfiguration;
+import org.linphone.receivers.BluetoothManager;
import org.linphone.ui.Numpad;
import java.text.DecimalFormat;
@@ -97,1714 +97,1704 @@ import java.util.Timer;
import java.util.TimerTask;
public class CallActivity extends LinphoneGenericActivity implements OnClickListener, ActivityCompat.OnRequestPermissionsResultCallback {
- private final static int SECONDS_BEFORE_HIDING_CONTROLS = 4000;
- private final static int SECONDS_BEFORE_DENYING_CALL_UPDATE = 30000;
- private static final int PERMISSIONS_REQUEST_CAMERA = 202;
- private static final int PERMISSIONS_ENABLED_CAMERA = 203;
- private static final int PERMISSIONS_ENABLED_MIC = 204;
+ private final static int SECONDS_BEFORE_HIDING_CONTROLS = 4000;
+ private final static int SECONDS_BEFORE_DENYING_CALL_UPDATE = 30000;
+ private static final int PERMISSIONS_REQUEST_CAMERA = 202;
+ private static final int PERMISSIONS_ENABLED_CAMERA = 203;
+ private static final int PERMISSIONS_ENABLED_MIC = 204;
- private static CallActivity instance;
+ private static CallActivity instance;
- private Handler mControlsHandler = new Handler();
- private Runnable mControls;
- private ImageView switchCamera;
- private TextView missedChats;
- private RelativeLayout mActiveCallHeader, sideMenuContent, avatar_layout;
- private ImageView pause, hangUp, dialer, video, micro, speaker, options, addCall, transfer, conference, conferenceStatus, contactPicture;
- private ImageView audioRoute, routeSpeaker, routeEarpiece, routeBluetooth, menu, chat;
- private LinearLayout mNoCurrentCall, callInfo, mCallPaused;
- private ProgressBar videoProgress;
- private StatusFragment status;
- private CallAudioFragment audioCallFragment;
- private CallVideoFragment videoCallFragment;
- private boolean isSpeakerEnabled = false, isMicMuted = false, isTransferAllowed, isVideoAsk;
- private LinearLayout mControlsLayout;
- private Numpad numpad;
- private int cameraNumber;
- private CountDownTimer timer;
- private boolean isVideoCallPaused = false;
- private Dialog dialog = null;
- private static long TimeRemind = 0;
- private HeadsetReceiver headsetReceiver;
+ private Handler mControlsHandler = new Handler();
+ private Runnable mControls;
+ private ImageView switchCamera;
+ private TextView missedChats;
+ private RelativeLayout mActiveCallHeader, sideMenuContent, avatar_layout;
+ private ImageView pause, hangUp, dialer, video, micro, speaker, options, addCall, transfer, conference, conferenceStatus, contactPicture;
+ private ImageView audioRoute, routeSpeaker, routeEarpiece, routeBluetooth, menu, chat;
+ private LinearLayout mNoCurrentCall, callInfo, mCallPaused;
+ private ProgressBar videoProgress;
+ private StatusFragment status;
+ private CallAudioFragment audioCallFragment;
+ private CallVideoFragment videoCallFragment;
+ private boolean isSpeakerEnabled = false, isMicMuted = false, isTransferAllowed, isVideoAsk;
+ private LinearLayout mControlsLayout;
+ private Numpad numpad;
+ private int cameraNumber;
+ private CountDownTimer timer;
+ private boolean isVideoCallPaused = false;
+ private Dialog dialog = null;
+ private static long TimeRemind = 0;
+ private HeadsetReceiver headsetReceiver;
- private LinearLayout callsList, conferenceList;
- private LayoutInflater inflater;
- private ViewGroup container;
- private boolean isConferenceRunning = false;
- private CoreListenerStub mListener;
- private DrawerLayout sideMenu;
+ private LinearLayout callsList, conferenceList;
+ private LayoutInflater inflater;
+ private ViewGroup container;
+ private boolean isConferenceRunning = false;
+ private CoreListenerStub mListener;
+ private DrawerLayout sideMenu;
- private Handler mHandler = new Handler();
- private Timer mTimer;
- private TimerTask mTask;
- private HashMap mEncoderTexts;
- private HashMap mDecoderTexts;
- private CallListenerStub mCallListener;
- private Call mCallDisplayedInStats;
+ private Handler mHandler = new Handler();
+ private Timer mTimer;
+ private TimerTask mTask;
+ private HashMap mEncoderTexts;
+ private HashMap mDecoderTexts;
+ private CallListenerStub mCallListener;
+ private Call mCallDisplayedInStats;
- private boolean oldIsSpeakerEnabled = false;
+ private boolean oldIsSpeakerEnabled = false;
- public static CallActivity instance() {
- return instance;
- }
+ public static CallActivity instance() {
+ return instance;
+ }
- public static boolean isInstanciated() {
- return instance != null;
- }
+ public static boolean isInstanciated() {
+ return instance != null;
+ }
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- instance = this;
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ instance = this;
- if (getResources().getBoolean(R.bool.orientation_portrait_only)) {
- setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
- }
+ if (getResources().getBoolean(R.bool.orientation_portrait_only)) {
+ setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
+ }
- getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
- setContentView(R.layout.call);
+ getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
+ setContentView(R.layout.call);
- //Earset Connectivity Broadcast Processing
- IntentFilter intentFilter = new IntentFilter();
- intentFilter.addAction("android.intent.action.HEADSET_PLUG");
- headsetReceiver = new HeadsetReceiver();
- registerReceiver(headsetReceiver, intentFilter);
+ //Earset Connectivity Broadcast Processing
+ IntentFilter intentFilter = new IntentFilter();
+ intentFilter.addAction("android.intent.action.HEADSET_PLUG");
+ headsetReceiver = new HeadsetReceiver();
+ registerReceiver(headsetReceiver, intentFilter);
- isTransferAllowed = getApplicationContext().getResources().getBoolean(R.bool.allow_transfers);
+ isTransferAllowed = getApplicationContext().getResources().getBoolean(R.bool.allow_transfers);
- cameraNumber = AndroidCameraConfiguration.retrieveCameras().length;
+ cameraNumber = AndroidCameraConfiguration.retrieveCameras().length;
- mEncoderTexts = new HashMap<>();
- mDecoderTexts = new HashMap<>();
+ mEncoderTexts = new HashMap<>();
+ mDecoderTexts = new HashMap<>();
- mListener = new CoreListenerStub() {
- @Override
- public void onMessageReceived(Core lc, ChatRoom cr, ChatMessage message) {
- displayMissedChats();
- }
+ mListener = new CoreListenerStub() {
+ @Override
+ public void onMessageReceived(Core lc, ChatRoom cr, ChatMessage message) {
+ displayMissedChats();
+ }
- @Override
- public void onCallStateChanged(Core lc, final Call call, Call.State state, String message) {
- if (LinphoneManager.getLc().getCallsNb() == 0) {
- if (status != null) {
- LinphoneService.instance().removeSasNotification();
- status.setisZrtpAsk(false);
- }
- finish();
- return;
- }
+ @Override
+ public void onCallStateChanged(Core lc, final Call call, Call.State state, String message) {
+ if (LinphoneManager.getLc().getCallsNb() == 0) {
+ if (status != null) {
+ LinphoneService.instance().removeSasNotification();
+ status.setisZrtpAsk(false);
+ }
+ finish();
+ return;
+ }
- if (state == State.IncomingReceived) {
- startIncomingCallActivity();
- return;
- } else if (state == State.Paused || state == State.PausedByRemote || state == State.Pausing) {
- if(LinphoneManager.getLc().getCurrentCall() != null) {
- enabledVideoButton(false);
- }
- if(isVideoEnabled(call)){
- showAudioView();
- }
- } else if (state == State.Resuming) {
- if(LinphonePreferences.instance().isVideoEnabled()){
- status.refreshStatusItems(call, isVideoEnabled(call));
- if(call.getCurrentParams().videoEnabled()){
- showVideoView();
- }
- }
- if(LinphoneManager.getLc().getCurrentCall() != null) {
- enabledVideoButton(true);
- }
- } else if (state == State.StreamsRunning) {
- switchVideo(isVideoEnabled(call));
- enableAndRefreshInCallActions();
+ if (state == State.IncomingReceived) {
+ startIncomingCallActivity();
+ return;
+ } else if (state == State.Paused || state == State.PausedByRemote || state == State.Pausing) {
+ if (LinphoneManager.getLc().getCurrentCall() != null) {
+ enabledVideoButton(false);
+ }
+ if (isVideoEnabled(call)) {
+ showAudioView();
+ }
+ } else if (state == State.Resuming) {
+ if (LinphonePreferences.instance().isVideoEnabled()) {
+ status.refreshStatusItems(call, isVideoEnabled(call));
+ if (call.getCurrentParams().videoEnabled()) {
+ showVideoView();
+ }
+ }
+ if (LinphoneManager.getLc().getCurrentCall() != null) {
+ enabledVideoButton(true);
+ }
+ } else if (state == State.StreamsRunning) {
+ switchVideo(isVideoEnabled(call));
+ enableAndRefreshInCallActions();
- if (status != null) {
- videoProgress.setVisibility(View.GONE);
- status.refreshStatusItems(call, isVideoEnabled(call));
- }
- } else if (state == State.UpdatedByRemote) {
- // If the correspondent proposes video while audio call
- boolean videoEnabled = LinphonePreferences.instance().isVideoEnabled();
- if (!videoEnabled) {
- acceptCallUpdate(false);
- }
+ if (status != null) {
+ videoProgress.setVisibility(View.GONE);
+ status.refreshStatusItems(call, isVideoEnabled(call));
+ }
+ } else if (state == State.UpdatedByRemote) {
+ // If the correspondent proposes video while audio call
+ boolean videoEnabled = LinphonePreferences.instance().isVideoEnabled();
+ if (!videoEnabled) {
+ acceptCallUpdate(false);
+ }
- boolean remoteVideo = call.getRemoteParams().videoEnabled();
- boolean localVideo = call.getCurrentParams().videoEnabled();
- boolean autoAcceptCameraPolicy = LinphonePreferences.instance().shouldAutomaticallyAcceptVideoRequests();
- if (remoteVideo && !localVideo && !autoAcceptCameraPolicy && !LinphoneManager.getLc().isInConference()) {
- showAcceptCallUpdateDialog();
- createTimerForDialog(SECONDS_BEFORE_DENYING_CALL_UPDATE);
- }
- }
+ boolean remoteVideo = call.getRemoteParams().videoEnabled();
+ boolean localVideo = call.getCurrentParams().videoEnabled();
+ boolean autoAcceptCameraPolicy = LinphonePreferences.instance().shouldAutomaticallyAcceptVideoRequests();
+ if (remoteVideo && !localVideo && !autoAcceptCameraPolicy && !LinphoneManager.getLc().isInConference()) {
+ showAcceptCallUpdateDialog();
+ createTimerForDialog(SECONDS_BEFORE_DENYING_CALL_UPDATE);
+ }
+ }
- refreshIncallUi();
- transfer.setEnabled(LinphoneManager.getLc().getCurrentCall() != null);
- }
+ refreshIncallUi();
+ transfer.setEnabled(LinphoneManager.getLc().getCurrentCall() != null);
+ }
- @Override
- public void onCallEncryptionChanged(Core lc, final Call call, boolean encrypted, String authenticationToken) {
- if (status != null) {
- if(call.getCurrentParams().getMediaEncryption().equals(MediaEncryption.ZRTP) && !call.getAuthenticationTokenVerified()){
- status.showZRTPDialog(call);
- }
- status.refreshStatusItems(call, call.getCurrentParams().videoEnabled());
- }
- }
+ @Override
+ public void onCallEncryptionChanged(Core lc, final Call call, boolean encrypted, String authenticationToken) {
+ if (status != null) {
+ if (call.getCurrentParams().getMediaEncryption().equals(MediaEncryption.ZRTP) && !call.getAuthenticationTokenVerified()) {
+ status.showZRTPDialog(call);
+ }
+ status.refreshStatusItems(call, call.getCurrentParams().videoEnabled());
+ }
+ }
- };
+ };
- if (findViewById(R.id.fragmentContainer) != null) {
- initUI();
+ if (findViewById(R.id.fragmentContainer) != null) {
+ initUI();
- if (LinphoneManager.getLc().getCallsNb() > 0) {
- Call call = LinphoneManager.getLc().getCalls()[0];
+ if (LinphoneManager.getLc().getCallsNb() > 0) {
+ Call call = LinphoneManager.getLc().getCalls()[0];
- if (LinphoneUtils.isCallEstablished(call)) {
- enableAndRefreshInCallActions();
- }
- }
- if (savedInstanceState != null) {
- // Fragment already created, no need to create it again (else it will generate a memory leak with duplicated fragments)
- isSpeakerEnabled = savedInstanceState.getBoolean("Speaker");
- isMicMuted = savedInstanceState.getBoolean("Mic");
- isVideoCallPaused = savedInstanceState.getBoolean("VideoCallPaused");
- if (savedInstanceState.getBoolean("AskingVideo")) {
- showAcceptCallUpdateDialog();
- TimeRemind = savedInstanceState.getLong("TimeRemind");
- createTimerForDialog(TimeRemind);
- }
+ if (LinphoneUtils.isCallEstablished(call)) {
+ enableAndRefreshInCallActions();
+ }
+ }
+ if (savedInstanceState != null) {
+ // Fragment already created, no need to create it again (else it will generate a memory leak with duplicated fragments)
+ isSpeakerEnabled = savedInstanceState.getBoolean("Speaker");
+ isMicMuted = savedInstanceState.getBoolean("Mic");
+ isVideoCallPaused = savedInstanceState.getBoolean("VideoCallPaused");
+ if (savedInstanceState.getBoolean("AskingVideo")) {
+ showAcceptCallUpdateDialog();
+ TimeRemind = savedInstanceState.getLong("TimeRemind");
+ createTimerForDialog(TimeRemind);
+ }
if (status != null && savedInstanceState.getBoolean("AskingZrtp")) {
status.setisZrtpAsk(savedInstanceState.getBoolean("AskingZrtp"));
}
- refreshInCallActions();
- return;
- } else {
- isSpeakerEnabled = LinphoneManager.getInstance().isSpeakerEnabled();
- isMicMuted = !LinphoneManager.getLc().micEnabled();
- }
+ refreshInCallActions();
+ return;
+ } else {
+ isSpeakerEnabled = LinphoneManager.getInstance().isSpeakerEnabled();
+ isMicMuted = !LinphoneManager.getLc().micEnabled();
+ }
- Fragment callFragment;
- if (isVideoEnabled(LinphoneManager.getLc().getCurrentCall())) {
- callFragment = new CallVideoFragment();
- videoCallFragment = (CallVideoFragment) callFragment;
- displayVideoCall(false);
- LinphoneManager.getInstance().routeAudioToSpeaker();
- isSpeakerEnabled = true;
- } else {
- callFragment = new CallAudioFragment();
- audioCallFragment = (CallAudioFragment) callFragment;
- }
+ Fragment callFragment;
+ if (isVideoEnabled(LinphoneManager.getLc().getCurrentCall())) {
+ callFragment = new CallVideoFragment();
+ videoCallFragment = (CallVideoFragment) callFragment;
+ displayVideoCall(false);
+ LinphoneManager.getInstance().routeAudioToSpeaker();
+ isSpeakerEnabled = true;
+ } else {
+ callFragment = new CallAudioFragment();
+ audioCallFragment = (CallAudioFragment) callFragment;
+ }
- if(BluetoothManager.getInstance().isBluetoothHeadsetAvailable()){
- BluetoothManager.getInstance().routeAudioToBluetooth();
- }
+ if (BluetoothManager.getInstance().isBluetoothHeadsetAvailable()) {
+ BluetoothManager.getInstance().routeAudioToBluetooth();
+ }
- callFragment.setArguments(getIntent().getExtras());
- getFragmentManager().beginTransaction().add(R.id.fragmentContainer, callFragment).commitAllowingStateLoss();
- }
- }
+ callFragment.setArguments(getIntent().getExtras());
+ getFragmentManager().beginTransaction().add(R.id.fragmentContainer, callFragment).commitAllowingStateLoss();
+ }
+ }
- public void createTimerForDialog(long time) {
- timer = new CountDownTimer(time , 1000) {
- public void onTick(long millisUntilFinished) {
- TimeRemind = millisUntilFinished;
- }
- public void onFinish() {
- if (dialog != null) {
- dialog.dismiss();
- dialog = null;
- }
- acceptCallUpdate(false);
- }
- }.start();
- }
+ public void createTimerForDialog(long time) {
+ timer = new CountDownTimer(time, 1000) {
+ public void onTick(long millisUntilFinished) {
+ TimeRemind = millisUntilFinished;
+ }
- private boolean isVideoEnabled(Call call) {
- if(call != null){
- return call.getCurrentParams().videoEnabled();
- }
- return false;
- }
+ public void onFinish() {
+ if (dialog != null) {
+ dialog.dismiss();
+ dialog = null;
+ }
+ acceptCallUpdate(false);
+ }
+ }.start();
+ }
- @Override
- protected void onSaveInstanceState(Bundle outState) {
- outState.putBoolean("Speaker", LinphoneManager.getInstance().isSpeakerEnabled());
- outState.putBoolean("Mic", !LinphoneManager.getLc().micEnabled());
- outState.putBoolean("VideoCallPaused", isVideoCallPaused);
- outState.putBoolean("AskingVideo", isVideoAsk);
- outState.putLong("TimeRemind", TimeRemind);
+ private boolean isVideoEnabled(Call call) {
+ if (call != null) {
+ return call.getCurrentParams().videoEnabled();
+ }
+ return false;
+ }
+
+ @Override
+ protected void onSaveInstanceState(Bundle outState) {
+ outState.putBoolean("Speaker", LinphoneManager.getInstance().isSpeakerEnabled());
+ outState.putBoolean("Mic", !LinphoneManager.getLc().micEnabled());
+ outState.putBoolean("VideoCallPaused", isVideoCallPaused);
+ outState.putBoolean("AskingVideo", isVideoAsk);
+ outState.putLong("TimeRemind", TimeRemind);
if (status != null) outState.putBoolean("AskingZrtp", status.getisZrtpAsk());
- if (dialog != null) dialog.dismiss();
- super.onSaveInstanceState(outState);
- }
-
- private boolean isTablet() {
- return getResources().getBoolean(R.bool.isTablet);
- }
-
- private void initUI() {
- inflater = LayoutInflater.from(this);
- container = findViewById(R.id.topLayout);
- callsList = findViewById(R.id.calls_list);
- conferenceList = findViewById(R.id.conference_list);
-
- //TopBar
- video = findViewById(R.id.video);
- video.setOnClickListener(this);
- enabledVideoButton(false);
-
- videoProgress = findViewById(R.id.video_in_progress);
- videoProgress.setVisibility(View.GONE);
-
- micro = findViewById(R.id.micro);
- micro.setOnClickListener(this);
-
- speaker = findViewById(R.id.speaker);
- speaker.setOnClickListener(this);
-
- options = findViewById(R.id.options);
- options.setOnClickListener(this);
- options.setEnabled(false);
-
- //BottonBar
- hangUp = findViewById(R.id.hang_up);
- hangUp.setOnClickListener(this);
-
- dialer = findViewById(R.id.dialer);
- dialer.setOnClickListener(this);
-
- numpad = findViewById(R.id.numpad);
- numpad.getBackground().setAlpha(240);
-
- chat = findViewById(R.id.chat);
- chat.setOnClickListener(this);
- missedChats = findViewById(R.id.missed_chats);
-
- //Others
-
- //Active Call
- callInfo = findViewById(R.id.active_call_info);
-
- pause = findViewById(R.id.pause);
- pause.setOnClickListener(this);
- enabledPauseButton(false);
-
- mActiveCallHeader = findViewById(R.id.active_call);
- mNoCurrentCall = findViewById(R.id.no_current_call);
- mCallPaused = findViewById(R.id.remote_pause);
-
- contactPicture = findViewById(R.id.contact_picture);
- avatar_layout = findViewById(R.id.avatar_layout);
-
- //Options
- addCall = findViewById(R.id.add_call);
- addCall.setOnClickListener(this);
- addCall.setEnabled(false);
-
- transfer = findViewById(R.id.transfer);
- transfer.setOnClickListener(this);
- transfer.setEnabled(false);
-
- conference = findViewById(R.id.conference);
- conference.setEnabled(false);
- conference.setOnClickListener(this);
-
- try {
- audioRoute = findViewById(R.id.audio_route);
- audioRoute.setOnClickListener(this);
- routeSpeaker = findViewById(R.id.route_speaker);
- routeSpeaker.setOnClickListener(this);
- routeEarpiece = findViewById(R.id.route_earpiece);
- routeEarpiece.setOnClickListener(this);
- routeBluetooth = findViewById(R.id.route_bluetooth);
- routeBluetooth.setOnClickListener(this);
- } catch (NullPointerException npe) {
- Log.e("Bluetooth: Audio routes menu disabled on tablets for now (1)");
- }
-
- switchCamera = findViewById(R.id.switchCamera);
- switchCamera.setOnClickListener(this);
-
- mControlsLayout = findViewById(R.id.menu);
-
- if (!isTransferAllowed) {
- addCall.setBackgroundResource(R.drawable.options_add_call);
- }
-
- if (BluetoothManager.getInstance().isBluetoothHeadsetAvailable()) {
- try {
- audioRoute.setVisibility(View.VISIBLE);
- speaker.setVisibility(View.GONE);
- } catch (NullPointerException npe) { Log.e("Bluetooth: Audio routes menu disabled on tablets for now (2)"); }
- } else {
- try {
- audioRoute.setVisibility(View.GONE);
- speaker.setVisibility(View.VISIBLE);
- } catch (NullPointerException npe) { Log.e("Bluetooth: Audio routes menu disabled on tablets for now (3)"); }
- }
-
- createInCallStats();
- LinphoneManager.getInstance().changeStatusToOnThePhone();
- }
-
- public void checkAndRequestPermission(String permission, int result) {
- int permissionGranted = getPackageManager().checkPermission(permission, getPackageName());
- Log.i("[Permission] " + permission + " is " + (permissionGranted == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
-
- if (permissionGranted != PackageManager.PERMISSION_GRANTED) {
- if (LinphonePreferences.instance().firstTimeAskingForPermission(permission) || ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
- Log.i("[Permission] Asking for " + permission);
- ActivityCompat.requestPermissions(this, new String[] { permission }, result);
- }
- }
- }
-
- @Override
- public void onRequestPermissionsResult(int requestCode, String[] permissions, final int[] grantResults) {
- for (int i = 0; i < permissions.length; i++) {
- Log.i("[Permission] " + permissions[i] + " is " + (grantResults[i] == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
- }
-
- switch (requestCode) {
- case PERMISSIONS_REQUEST_CAMERA:
- LinphoneUtils.dispatchOnUIThread(new Runnable() {
- @Override
- public void run() {
- acceptCallUpdate(grantResults[0] == PackageManager.PERMISSION_GRANTED);
- }
- });
- break;
- case PERMISSIONS_ENABLED_CAMERA:
- LinphoneUtils.dispatchOnUIThread(new Runnable() {
- @Override
- public void run() {
- disableVideo(grantResults[0] != PackageManager.PERMISSION_GRANTED);
- }
- });
- break;
- case PERMISSIONS_ENABLED_MIC:
- LinphoneUtils.dispatchOnUIThread(new Runnable() {
- @Override
- public void run() {
- if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
- toggleMicro();
- }
- }
- });
- break;
- }
- }
-
- public void createInCallStats() {
- sideMenu = findViewById(R.id.side_menu);
- menu = findViewById(R.id.call_quality);
-
- sideMenuContent = findViewById(R.id.side_menu_content);
-
- menu.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View view) {
- if (sideMenu.isDrawerVisible(Gravity.LEFT)) {
- sideMenu.closeDrawer(sideMenuContent);
- } else {
- sideMenu.openDrawer(sideMenuContent);
- }
- }
- });
-
- Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- if (lc != null) {
- initCallStatsRefresher(lc.getCurrentCall(), findViewById(R.id.incall_stats));
- }
- }
-
- private void refreshIncallUi(){
- refreshInCallActions();
- refreshCallList(getResources());
- enableAndRefreshInCallActions();
- displayMissedChats();
- }
-
- public void setSpeakerEnabled(boolean enabled){
- isSpeakerEnabled = enabled;
- }
-
- public void refreshInCallActions() {
- if (!LinphonePreferences.instance().isVideoEnabled() || isConferenceRunning) {
- enabledVideoButton(false);
- } else {
- if(video.isEnabled()) {
- if (isVideoEnabled(LinphoneManager.getLc().getCurrentCall())) {
- video.setImageResource(R.drawable.camera_selected);
- videoProgress.setVisibility(View.INVISIBLE);
- } else {
- video.setImageResource(R.drawable.camera_button);
- }
- } else {
- video.setImageResource(R.drawable.camera_button);
- }
- }
- if (getPackageManager().checkPermission(Manifest.permission.CAMERA, getPackageName()) != PackageManager.PERMISSION_GRANTED) {
- video.setImageResource(R.drawable.camera_button);
- }
-
- if (isSpeakerEnabled) {
- speaker.setImageResource(R.drawable.speaker_selected);
- } else {
- speaker.setImageResource(R.drawable.speaker_default);
- }
-
- if (getPackageManager().checkPermission(Manifest.permission.RECORD_AUDIO, getPackageName()) != PackageManager.PERMISSION_GRANTED) {
- isMicMuted = true;
- }
- if (isMicMuted) {
- micro.setImageResource(R.drawable.micro_selected);
- } else {
- micro.setImageResource(R.drawable.micro_default);
- }
-
- try {
- routeSpeaker.setImageResource(R.drawable.route_speaker);
- if (BluetoothManager.getInstance().isUsingBluetoothAudioRoute()) {
- isSpeakerEnabled = false; // We need this if isSpeakerEnabled wasn't set correctly
- routeEarpiece.setImageResource(R.drawable.route_earpiece);
- routeBluetooth.setImageResource(R.drawable.route_bluetooth_selected);
- return;
- } else {
- routeEarpiece.setImageResource(R.drawable.route_earpiece_selected);
- routeBluetooth.setImageResource(R.drawable.route_bluetooth);
- }
-
- if (isSpeakerEnabled) {
- routeSpeaker.setImageResource(R.drawable.route_speaker_selected);
- routeEarpiece.setImageResource(R.drawable.route_earpiece);
- routeBluetooth.setImageResource(R.drawable.route_bluetooth);
- }
- } catch (NullPointerException npe) {
- Log.e("Bluetooth: Audio routes menu disabled on tablets for now (4)");
- }
- }
-
- private void enableAndRefreshInCallActions() {
- int confsize = 0;
-
- if(LinphoneManager.getLc().isInConference()) {
- confsize = LinphoneManager.getLc().getConferenceSize() - (LinphoneManager.getLc().getConference() != null ? 1 : 0);
- }
-
- //Enabled transfer button
- if(isTransferAllowed && !LinphoneManager.getLc().soundResourcesLocked())
- enabledTransferButton(true);
-
- //Enable conference button
- if(LinphoneManager.getLc().getCallsNb() > 1 && LinphoneManager.getLc().getCallsNb() > confsize && !LinphoneManager.getLc().soundResourcesLocked()) {
- enabledConferenceButton(true);
- } else {
- enabledConferenceButton(false);
- }
-
- addCall.setEnabled(LinphoneManager.getLc().getCallsNb() < LinphoneManager.getLc().getMaxCalls() && !LinphoneManager.getLc().soundResourcesLocked());
- options.setEnabled(!getResources().getBoolean(R.bool.disable_options_in_call) && (addCall.isEnabled() || transfer.isEnabled()));
-
- if(LinphoneManager.getLc().getCurrentCall() != null && LinphonePreferences.instance().isVideoEnabled() && !LinphoneManager.getLc().getCurrentCall().mediaInProgress()) {
- enabledVideoButton(true);
- } else {
- enabledVideoButton(false);
- }
- if(LinphoneManager.getLc().getCurrentCall() != null && !LinphoneManager.getLc().getCurrentCall().mediaInProgress()){
- enabledPauseButton(true);
- } else {
- enabledPauseButton(false);
- }
- micro.setEnabled(true);
- if(!isTablet()){
- speaker.setEnabled(true);
- }
- transfer.setEnabled(true);
- pause.setEnabled(true);
- dialer.setEnabled(true);
- }
-
- public void updateStatusFragment(StatusFragment statusFragment) {
- status = statusFragment;
- }
-
- @Override
- public void onClick(View v) {
- int id = v.getId();
-
- if (isVideoEnabled(LinphoneManager.getLc().getCurrentCall())) {
- //displayVideoCallControlsIfHidden();
- }
-
- if (id == R.id.video) {
- int camera = getPackageManager().checkPermission(Manifest.permission.CAMERA, getPackageName());
- Log.i("[Permission] Camera permission is " + (camera == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
-
- if (camera == PackageManager.PERMISSION_GRANTED) {
- disableVideo(isVideoEnabled(LinphoneManager.getLc().getCurrentCall()));
- } else {
- checkAndRequestPermission(Manifest.permission.CAMERA, PERMISSIONS_ENABLED_CAMERA);
-
- }
- }
- else if (id == R.id.micro) {
- int recordAudio = getPackageManager().checkPermission(Manifest.permission.RECORD_AUDIO, getPackageName());
- Log.i("[Permission] Record audio permission is " + (recordAudio == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
-
- if (recordAudio == PackageManager.PERMISSION_GRANTED) {
- toggleMicro();
- } else {
- checkAndRequestPermission(Manifest.permission.RECORD_AUDIO, PERMISSIONS_ENABLED_MIC);
- }
- }
- else if (id == R.id.speaker) {
- toggleSpeaker();
- }
- else if (id == R.id.add_call) {
- goBackToDialer();
- }
- else if (id == R.id.pause) {
- pauseOrResumeCall(LinphoneManager.getLc().getCurrentCall());
- }
- else if (id == R.id.hang_up) {
- hangUp();
- }
- else if (id == R.id.dialer) {
- hideOrDisplayNumpad();
- }
- else if (id == R.id.chat) {
- goToChatList();
- }
- else if (id == R.id.conference) {
- enterConference();
- hideOrDisplayCallOptions();
- }
- else if (id == R.id.switchCamera) {
- if (videoCallFragment != null) {
- videoCallFragment.switchCamera();
- }
- }
- else if (id == R.id.transfer) {
- goBackToDialerAndDisplayTransferButton();
- }
- else if (id == R.id.options) {
- hideOrDisplayCallOptions();
- }
- else if (id == R.id.audio_route) {
- hideOrDisplayAudioRoutes();
- }
- else if (id == R.id.route_bluetooth) {
- if (BluetoothManager.getInstance().routeAudioToBluetooth()) {
- isSpeakerEnabled = false;
- routeBluetooth.setImageResource(R.drawable.route_bluetooth_selected);
- routeSpeaker.setImageResource(R.drawable.route_speaker);
- routeEarpiece.setImageResource(R.drawable.route_earpiece);
- }
- hideOrDisplayAudioRoutes();
- }
- else if (id == R.id.route_earpiece) {
- LinphoneManager.getInstance().routeAudioToReceiver();
- isSpeakerEnabled = false;
- routeBluetooth.setImageResource(R.drawable.route_bluetooth);
- routeSpeaker.setImageResource(R.drawable.route_speaker);
- routeEarpiece.setImageResource(R.drawable.route_earpiece_selected);
- hideOrDisplayAudioRoutes();
- }
- else if (id == R.id.route_speaker) {
- LinphoneManager.getInstance().routeAudioToSpeaker();
- isSpeakerEnabled = true;
- routeBluetooth.setImageResource(R.drawable.route_bluetooth);
- routeSpeaker.setImageResource(R.drawable.route_speaker_selected);
- routeEarpiece.setImageResource(R.drawable.route_earpiece);
- hideOrDisplayAudioRoutes();
- }
-
- else if (id == R.id.call_pause) {
- Call call = (Call) v.getTag();
- pauseOrResumeCall(call);
- }
- else if (id == R.id.conference_pause) {
- pauseOrResumeConference();
- }
- }
-
- private void enabledVideoButton(boolean enabled){
- if(enabled) {
- video.setEnabled(true);
- } else {
- video.setEnabled(false);
- }
- }
-
- private void enabledPauseButton(boolean enabled){
- if(enabled) {
- pause.setEnabled(true);
- pause.setImageResource(R.drawable.pause_big_default);
- } else {
- pause.setEnabled(false);
- pause.setImageResource(R.drawable.pause_big_disabled);
- }
- }
-
- private void enabledTransferButton(boolean enabled){
- if(enabled) {
- transfer.setEnabled(true);
- } else {
- transfer.setEnabled(false);
- }
- }
-
- private void enabledConferenceButton(boolean enabled){
- if (enabled) {
- conference.setEnabled(true);
- } else {
- conference.setEnabled(false);
- }
- }
-
- private void disableVideo(final boolean videoDisabled) {
- final Call call = LinphoneManager.getLc().getCurrentCall();
- if (call == null) {
- return;
- }
-
- if (videoDisabled) {
- CallParams params = LinphoneManager.getLc().createCallParams(call);
- params.enableVideo(false);
- LinphoneManager.getLc().updateCall(call, params);
- } else {
- videoProgress.setVisibility(View.VISIBLE);
- if (call.getRemoteParams() != null && !call.getRemoteParams().lowBandwidthEnabled()) {
- LinphoneManager.getInstance().addVideo();
- } else {
- displayCustomToast(getString(R.string.error_low_bandwidth), Toast.LENGTH_LONG);
- }
- }
- }
-
- public void displayCustomToast(final String message, final int duration) {
- LayoutInflater inflater = getLayoutInflater();
- View layout = inflater.inflate(R.layout.toast, (ViewGroup) findViewById(R.id.toastRoot));
-
- TextView toastText = layout.findViewById(R.id.toastMessage);
- toastText.setText(message);
-
- final Toast toast = new Toast(getApplicationContext());
- toast.setGravity(Gravity.CENTER, 0, 0);
- toast.setDuration(duration);
- toast.setView(layout);
- toast.show();
- }
-
- private void switchVideo(final boolean displayVideo) {
- final Call call = LinphoneManager.getLc().getCurrentCall();
- if (call == null) {
- return;
- }
-
- //Check if the call is not terminated
- if(call.getState() == State.End || call.getState() == State.Released) return;
-
- if (!displayVideo) {
- showAudioView();
- } else {
- if (!call.getRemoteParams().lowBandwidthEnabled()) {
- LinphoneManager.getInstance().addVideo();
- if (videoCallFragment == null || !videoCallFragment.isVisible())
- showVideoView();
- } else {
- displayCustomToast(getString(R.string.error_low_bandwidth), Toast.LENGTH_LONG);
- }
- }
- }
-
- private void showAudioView() {
- if (LinphoneManager.getLc().getCurrentCall() != null) {
- if (!isSpeakerEnabled) {
- LinphoneManager.getInstance().enableProximitySensing(true);
- }
- }
- replaceFragmentVideoByAudio();
- displayAudioCall();
- showStatusBar();
- removeCallbacks();
- }
-
- private void showVideoView() {
- if (!BluetoothManager.getInstance().isBluetoothHeadsetAvailable()) {
- Log.w("Bluetooth not available, using speaker");
- LinphoneManager.getInstance().routeAudioToSpeaker();
- isSpeakerEnabled = true;
- }
- refreshInCallActions();
-
- LinphoneManager.getInstance().enableProximitySensing(false);
-
- replaceFragmentAudioByVideo();
- hideStatusBar();
- }
-
- private void displayNoCurrentCall(boolean display){
- if(!display) {
- mActiveCallHeader.setVisibility(View.VISIBLE);
- mNoCurrentCall.setVisibility(View.GONE);
- } else {
- mActiveCallHeader.setVisibility(View.GONE);
- mNoCurrentCall.setVisibility(View.VISIBLE);
- }
- }
-
- private void displayCallPaused(boolean display){
- if(display){
- mCallPaused.setVisibility(View.VISIBLE);
- } else {
- mCallPaused.setVisibility(View.GONE);
- }
- }
-
- private void displayAudioCall(){
- mControlsLayout.setVisibility(View.VISIBLE);
- mActiveCallHeader.setVisibility(View.VISIBLE);
- callInfo.setVisibility(View.VISIBLE);
- avatar_layout.setVisibility(View.VISIBLE);
- switchCamera.setVisibility(View.GONE);
- }
-
- private void replaceFragmentVideoByAudio() {
- audioCallFragment = new CallAudioFragment();
- FragmentTransaction transaction = getFragmentManager().beginTransaction();
- transaction.replace(R.id.fragmentContainer, audioCallFragment);
- try {
- transaction.commitAllowingStateLoss();
- } catch (Exception e) {
- }
- }
-
- private void replaceFragmentAudioByVideo() {
+ if (dialog != null) dialog.dismiss();
+ super.onSaveInstanceState(outState);
+ }
+
+ private boolean isTablet() {
+ return getResources().getBoolean(R.bool.isTablet);
+ }
+
+ private void initUI() {
+ inflater = LayoutInflater.from(this);
+ container = findViewById(R.id.topLayout);
+ callsList = findViewById(R.id.calls_list);
+ conferenceList = findViewById(R.id.conference_list);
+
+ //TopBar
+ video = findViewById(R.id.video);
+ video.setOnClickListener(this);
+ enabledVideoButton(false);
+
+ videoProgress = findViewById(R.id.video_in_progress);
+ videoProgress.setVisibility(View.GONE);
+
+ micro = findViewById(R.id.micro);
+ micro.setOnClickListener(this);
+
+ speaker = findViewById(R.id.speaker);
+ speaker.setOnClickListener(this);
+
+ options = findViewById(R.id.options);
+ options.setOnClickListener(this);
+ options.setEnabled(false);
+
+ //BottonBar
+ hangUp = findViewById(R.id.hang_up);
+ hangUp.setOnClickListener(this);
+
+ dialer = findViewById(R.id.dialer);
+ dialer.setOnClickListener(this);
+
+ numpad = findViewById(R.id.numpad);
+ numpad.getBackground().setAlpha(240);
+
+ chat = findViewById(R.id.chat);
+ chat.setOnClickListener(this);
+ missedChats = findViewById(R.id.missed_chats);
+
+ //Others
+
+ //Active Call
+ callInfo = findViewById(R.id.active_call_info);
+
+ pause = findViewById(R.id.pause);
+ pause.setOnClickListener(this);
+ enabledPauseButton(false);
+
+ mActiveCallHeader = findViewById(R.id.active_call);
+ mNoCurrentCall = findViewById(R.id.no_current_call);
+ mCallPaused = findViewById(R.id.remote_pause);
+
+ contactPicture = findViewById(R.id.contact_picture);
+ avatar_layout = findViewById(R.id.avatar_layout);
+
+ //Options
+ addCall = findViewById(R.id.add_call);
+ addCall.setOnClickListener(this);
+ addCall.setEnabled(false);
+
+ transfer = findViewById(R.id.transfer);
+ transfer.setOnClickListener(this);
+ transfer.setEnabled(false);
+
+ conference = findViewById(R.id.conference);
+ conference.setEnabled(false);
+ conference.setOnClickListener(this);
+
+ try {
+ audioRoute = findViewById(R.id.audio_route);
+ audioRoute.setOnClickListener(this);
+ routeSpeaker = findViewById(R.id.route_speaker);
+ routeSpeaker.setOnClickListener(this);
+ routeEarpiece = findViewById(R.id.route_earpiece);
+ routeEarpiece.setOnClickListener(this);
+ routeBluetooth = findViewById(R.id.route_bluetooth);
+ routeBluetooth.setOnClickListener(this);
+ } catch (NullPointerException npe) {
+ Log.e("Bluetooth: Audio routes menu disabled on tablets for now (1)");
+ }
+
+ switchCamera = findViewById(R.id.switchCamera);
+ switchCamera.setOnClickListener(this);
+
+ mControlsLayout = findViewById(R.id.menu);
+
+ if (!isTransferAllowed) {
+ addCall.setBackgroundResource(R.drawable.options_add_call);
+ }
+
+ if (BluetoothManager.getInstance().isBluetoothHeadsetAvailable()) {
+ try {
+ audioRoute.setVisibility(View.VISIBLE);
+ speaker.setVisibility(View.GONE);
+ } catch (NullPointerException npe) {
+ Log.e("Bluetooth: Audio routes menu disabled on tablets for now (2)");
+ }
+ } else {
+ try {
+ audioRoute.setVisibility(View.GONE);
+ speaker.setVisibility(View.VISIBLE);
+ } catch (NullPointerException npe) {
+ Log.e("Bluetooth: Audio routes menu disabled on tablets for now (3)");
+ }
+ }
+
+ createInCallStats();
+ LinphoneManager.getInstance().changeStatusToOnThePhone();
+ }
+
+ public void checkAndRequestPermission(String permission, int result) {
+ int permissionGranted = getPackageManager().checkPermission(permission, getPackageName());
+ Log.i("[Permission] " + permission + " is " + (permissionGranted == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
+
+ if (permissionGranted != PackageManager.PERMISSION_GRANTED) {
+ if (LinphonePreferences.instance().firstTimeAskingForPermission(permission) || ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
+ Log.i("[Permission] Asking for " + permission);
+ ActivityCompat.requestPermissions(this, new String[]{permission}, result);
+ }
+ }
+ }
+
+ @Override
+ public void onRequestPermissionsResult(int requestCode, String[] permissions, final int[] grantResults) {
+ for (int i = 0; i < permissions.length; i++) {
+ Log.i("[Permission] " + permissions[i] + " is " + (grantResults[i] == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
+ }
+
+ switch (requestCode) {
+ case PERMISSIONS_REQUEST_CAMERA:
+ LinphoneUtils.dispatchOnUIThread(new Runnable() {
+ @Override
+ public void run() {
+ acceptCallUpdate(grantResults[0] == PackageManager.PERMISSION_GRANTED);
+ }
+ });
+ break;
+ case PERMISSIONS_ENABLED_CAMERA:
+ LinphoneUtils.dispatchOnUIThread(new Runnable() {
+ @Override
+ public void run() {
+ disableVideo(grantResults[0] != PackageManager.PERMISSION_GRANTED);
+ }
+ });
+ break;
+ case PERMISSIONS_ENABLED_MIC:
+ LinphoneUtils.dispatchOnUIThread(new Runnable() {
+ @Override
+ public void run() {
+ if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
+ toggleMicro();
+ }
+ }
+ });
+ break;
+ }
+ }
+
+ public void createInCallStats() {
+ sideMenu = findViewById(R.id.side_menu);
+ menu = findViewById(R.id.call_quality);
+
+ sideMenuContent = findViewById(R.id.side_menu_content);
+
+ menu.setOnClickListener(new OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ if (sideMenu.isDrawerVisible(Gravity.LEFT)) {
+ sideMenu.closeDrawer(sideMenuContent);
+ } else {
+ sideMenu.openDrawer(sideMenuContent);
+ }
+ }
+ });
+
+ Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ if (lc != null) {
+ initCallStatsRefresher(lc.getCurrentCall(), findViewById(R.id.incall_stats));
+ }
+ }
+
+ private void refreshIncallUi() {
+ refreshInCallActions();
+ refreshCallList(getResources());
+ enableAndRefreshInCallActions();
+ displayMissedChats();
+ }
+
+ public void setSpeakerEnabled(boolean enabled) {
+ isSpeakerEnabled = enabled;
+ }
+
+ public void refreshInCallActions() {
+ if (!LinphonePreferences.instance().isVideoEnabled() || isConferenceRunning) {
+ enabledVideoButton(false);
+ } else {
+ if (video.isEnabled()) {
+ if (isVideoEnabled(LinphoneManager.getLc().getCurrentCall())) {
+ video.setImageResource(R.drawable.camera_selected);
+ videoProgress.setVisibility(View.INVISIBLE);
+ } else {
+ video.setImageResource(R.drawable.camera_button);
+ }
+ } else {
+ video.setImageResource(R.drawable.camera_button);
+ }
+ }
+ if (getPackageManager().checkPermission(Manifest.permission.CAMERA, getPackageName()) != PackageManager.PERMISSION_GRANTED) {
+ video.setImageResource(R.drawable.camera_button);
+ }
+
+ if (isSpeakerEnabled) {
+ speaker.setImageResource(R.drawable.speaker_selected);
+ } else {
+ speaker.setImageResource(R.drawable.speaker_default);
+ }
+
+ if (getPackageManager().checkPermission(Manifest.permission.RECORD_AUDIO, getPackageName()) != PackageManager.PERMISSION_GRANTED) {
+ isMicMuted = true;
+ }
+ if (isMicMuted) {
+ micro.setImageResource(R.drawable.micro_selected);
+ } else {
+ micro.setImageResource(R.drawable.micro_default);
+ }
+
+ try {
+ routeSpeaker.setImageResource(R.drawable.route_speaker);
+ if (BluetoothManager.getInstance().isUsingBluetoothAudioRoute()) {
+ isSpeakerEnabled = false; // We need this if isSpeakerEnabled wasn't set correctly
+ routeEarpiece.setImageResource(R.drawable.route_earpiece);
+ routeBluetooth.setImageResource(R.drawable.route_bluetooth_selected);
+ return;
+ } else {
+ routeEarpiece.setImageResource(R.drawable.route_earpiece_selected);
+ routeBluetooth.setImageResource(R.drawable.route_bluetooth);
+ }
+
+ if (isSpeakerEnabled) {
+ routeSpeaker.setImageResource(R.drawable.route_speaker_selected);
+ routeEarpiece.setImageResource(R.drawable.route_earpiece);
+ routeBluetooth.setImageResource(R.drawable.route_bluetooth);
+ }
+ } catch (NullPointerException npe) {
+ Log.e("Bluetooth: Audio routes menu disabled on tablets for now (4)");
+ }
+ }
+
+ private void enableAndRefreshInCallActions() {
+ int confsize = 0;
+
+ if (LinphoneManager.getLc().isInConference()) {
+ confsize = LinphoneManager.getLc().getConferenceSize() - (LinphoneManager.getLc().getConference() != null ? 1 : 0);
+ }
+
+ //Enabled transfer button
+ if (isTransferAllowed && !LinphoneManager.getLc().soundResourcesLocked())
+ enabledTransferButton(true);
+
+ //Enable conference button
+ if (LinphoneManager.getLc().getCallsNb() > 1 && LinphoneManager.getLc().getCallsNb() > confsize && !LinphoneManager.getLc().soundResourcesLocked()) {
+ enabledConferenceButton(true);
+ } else {
+ enabledConferenceButton(false);
+ }
+
+ addCall.setEnabled(LinphoneManager.getLc().getCallsNb() < LinphoneManager.getLc().getMaxCalls() && !LinphoneManager.getLc().soundResourcesLocked());
+ options.setEnabled(!getResources().getBoolean(R.bool.disable_options_in_call) && (addCall.isEnabled() || transfer.isEnabled()));
+
+ if (LinphoneManager.getLc().getCurrentCall() != null && LinphonePreferences.instance().isVideoEnabled() && !LinphoneManager.getLc().getCurrentCall().mediaInProgress()) {
+ enabledVideoButton(true);
+ } else {
+ enabledVideoButton(false);
+ }
+ if (LinphoneManager.getLc().getCurrentCall() != null && !LinphoneManager.getLc().getCurrentCall().mediaInProgress()) {
+ enabledPauseButton(true);
+ } else {
+ enabledPauseButton(false);
+ }
+ micro.setEnabled(true);
+ if (!isTablet()) {
+ speaker.setEnabled(true);
+ }
+ transfer.setEnabled(true);
+ pause.setEnabled(true);
+ dialer.setEnabled(true);
+ }
+
+ public void updateStatusFragment(StatusFragment statusFragment) {
+ status = statusFragment;
+ }
+
+ @Override
+ public void onClick(View v) {
+ int id = v.getId();
+
+ if (isVideoEnabled(LinphoneManager.getLc().getCurrentCall())) {
+ //displayVideoCallControlsIfHidden();
+ }
+
+ if (id == R.id.video) {
+ int camera = getPackageManager().checkPermission(Manifest.permission.CAMERA, getPackageName());
+ Log.i("[Permission] Camera permission is " + (camera == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
+
+ if (camera == PackageManager.PERMISSION_GRANTED) {
+ disableVideo(isVideoEnabled(LinphoneManager.getLc().getCurrentCall()));
+ } else {
+ checkAndRequestPermission(Manifest.permission.CAMERA, PERMISSIONS_ENABLED_CAMERA);
+
+ }
+ } else if (id == R.id.micro) {
+ int recordAudio = getPackageManager().checkPermission(Manifest.permission.RECORD_AUDIO, getPackageName());
+ Log.i("[Permission] Record audio permission is " + (recordAudio == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
+
+ if (recordAudio == PackageManager.PERMISSION_GRANTED) {
+ toggleMicro();
+ } else {
+ checkAndRequestPermission(Manifest.permission.RECORD_AUDIO, PERMISSIONS_ENABLED_MIC);
+ }
+ } else if (id == R.id.speaker) {
+ toggleSpeaker();
+ } else if (id == R.id.add_call) {
+ goBackToDialer();
+ } else if (id == R.id.pause) {
+ pauseOrResumeCall(LinphoneManager.getLc().getCurrentCall());
+ } else if (id == R.id.hang_up) {
+ hangUp();
+ } else if (id == R.id.dialer) {
+ hideOrDisplayNumpad();
+ } else if (id == R.id.chat) {
+ goToChatList();
+ } else if (id == R.id.conference) {
+ enterConference();
+ hideOrDisplayCallOptions();
+ } else if (id == R.id.switchCamera) {
+ if (videoCallFragment != null) {
+ videoCallFragment.switchCamera();
+ }
+ } else if (id == R.id.transfer) {
+ goBackToDialerAndDisplayTransferButton();
+ } else if (id == R.id.options) {
+ hideOrDisplayCallOptions();
+ } else if (id == R.id.audio_route) {
+ hideOrDisplayAudioRoutes();
+ } else if (id == R.id.route_bluetooth) {
+ if (BluetoothManager.getInstance().routeAudioToBluetooth()) {
+ isSpeakerEnabled = false;
+ routeBluetooth.setImageResource(R.drawable.route_bluetooth_selected);
+ routeSpeaker.setImageResource(R.drawable.route_speaker);
+ routeEarpiece.setImageResource(R.drawable.route_earpiece);
+ }
+ hideOrDisplayAudioRoutes();
+ } else if (id == R.id.route_earpiece) {
+ LinphoneManager.getInstance().routeAudioToReceiver();
+ isSpeakerEnabled = false;
+ routeBluetooth.setImageResource(R.drawable.route_bluetooth);
+ routeSpeaker.setImageResource(R.drawable.route_speaker);
+ routeEarpiece.setImageResource(R.drawable.route_earpiece_selected);
+ hideOrDisplayAudioRoutes();
+ } else if (id == R.id.route_speaker) {
+ LinphoneManager.getInstance().routeAudioToSpeaker();
+ isSpeakerEnabled = true;
+ routeBluetooth.setImageResource(R.drawable.route_bluetooth);
+ routeSpeaker.setImageResource(R.drawable.route_speaker_selected);
+ routeEarpiece.setImageResource(R.drawable.route_earpiece);
+ hideOrDisplayAudioRoutes();
+ } else if (id == R.id.call_pause) {
+ Call call = (Call) v.getTag();
+ pauseOrResumeCall(call);
+ } else if (id == R.id.conference_pause) {
+ pauseOrResumeConference();
+ }
+ }
+
+ private void enabledVideoButton(boolean enabled) {
+ if (enabled) {
+ video.setEnabled(true);
+ } else {
+ video.setEnabled(false);
+ }
+ }
+
+ private void enabledPauseButton(boolean enabled) {
+ if (enabled) {
+ pause.setEnabled(true);
+ pause.setImageResource(R.drawable.pause_big_default);
+ } else {
+ pause.setEnabled(false);
+ pause.setImageResource(R.drawable.pause_big_disabled);
+ }
+ }
+
+ private void enabledTransferButton(boolean enabled) {
+ if (enabled) {
+ transfer.setEnabled(true);
+ } else {
+ transfer.setEnabled(false);
+ }
+ }
+
+ private void enabledConferenceButton(boolean enabled) {
+ if (enabled) {
+ conference.setEnabled(true);
+ } else {
+ conference.setEnabled(false);
+ }
+ }
+
+ private void disableVideo(final boolean videoDisabled) {
+ final Call call = LinphoneManager.getLc().getCurrentCall();
+ if (call == null) {
+ return;
+ }
+
+ if (videoDisabled) {
+ CallParams params = LinphoneManager.getLc().createCallParams(call);
+ params.enableVideo(false);
+ LinphoneManager.getLc().updateCall(call, params);
+ } else {
+ videoProgress.setVisibility(View.VISIBLE);
+ if (call.getRemoteParams() != null && !call.getRemoteParams().lowBandwidthEnabled()) {
+ LinphoneManager.getInstance().addVideo();
+ } else {
+ displayCustomToast(getString(R.string.error_low_bandwidth), Toast.LENGTH_LONG);
+ }
+ }
+ }
+
+ public void displayCustomToast(final String message, final int duration) {
+ LayoutInflater inflater = getLayoutInflater();
+ View layout = inflater.inflate(R.layout.toast, (ViewGroup) findViewById(R.id.toastRoot));
+
+ TextView toastText = layout.findViewById(R.id.toastMessage);
+ toastText.setText(message);
+
+ final Toast toast = new Toast(getApplicationContext());
+ toast.setGravity(Gravity.CENTER, 0, 0);
+ toast.setDuration(duration);
+ toast.setView(layout);
+ toast.show();
+ }
+
+ private void switchVideo(final boolean displayVideo) {
+ final Call call = LinphoneManager.getLc().getCurrentCall();
+ if (call == null) {
+ return;
+ }
+
+ //Check if the call is not terminated
+ if (call.getState() == State.End || call.getState() == State.Released) return;
+
+ if (!displayVideo) {
+ showAudioView();
+ } else {
+ if (!call.getRemoteParams().lowBandwidthEnabled()) {
+ LinphoneManager.getInstance().addVideo();
+ if (videoCallFragment == null || !videoCallFragment.isVisible())
+ showVideoView();
+ } else {
+ displayCustomToast(getString(R.string.error_low_bandwidth), Toast.LENGTH_LONG);
+ }
+ }
+ }
+
+ private void showAudioView() {
+ if (LinphoneManager.getLc().getCurrentCall() != null) {
+ if (!isSpeakerEnabled) {
+ LinphoneManager.getInstance().enableProximitySensing(true);
+ }
+ }
+ replaceFragmentVideoByAudio();
+ displayAudioCall();
+ showStatusBar();
+ removeCallbacks();
+ }
+
+ private void showVideoView() {
+ if (!BluetoothManager.getInstance().isBluetoothHeadsetAvailable()) {
+ Log.w("Bluetooth not available, using speaker");
+ LinphoneManager.getInstance().routeAudioToSpeaker();
+ isSpeakerEnabled = true;
+ }
+ refreshInCallActions();
+
+ LinphoneManager.getInstance().enableProximitySensing(false);
+
+ replaceFragmentAudioByVideo();
+ hideStatusBar();
+ }
+
+ private void displayNoCurrentCall(boolean display) {
+ if (!display) {
+ mActiveCallHeader.setVisibility(View.VISIBLE);
+ mNoCurrentCall.setVisibility(View.GONE);
+ } else {
+ mActiveCallHeader.setVisibility(View.GONE);
+ mNoCurrentCall.setVisibility(View.VISIBLE);
+ }
+ }
+
+ private void displayCallPaused(boolean display) {
+ if (display) {
+ mCallPaused.setVisibility(View.VISIBLE);
+ } else {
+ mCallPaused.setVisibility(View.GONE);
+ }
+ }
+
+ private void displayAudioCall() {
+ mControlsLayout.setVisibility(View.VISIBLE);
+ mActiveCallHeader.setVisibility(View.VISIBLE);
+ callInfo.setVisibility(View.VISIBLE);
+ avatar_layout.setVisibility(View.VISIBLE);
+ switchCamera.setVisibility(View.GONE);
+ }
+
+ private void replaceFragmentVideoByAudio() {
+ audioCallFragment = new CallAudioFragment();
+ FragmentTransaction transaction = getFragmentManager().beginTransaction();
+ transaction.replace(R.id.fragmentContainer, audioCallFragment);
+ try {
+ transaction.commitAllowingStateLoss();
+ } catch (Exception e) {
+ }
+ }
+
+ private void replaceFragmentAudioByVideo() {
// Hiding controls to let displayVideoCallControlsIfHidden add them plus the callback
- videoCallFragment = new CallVideoFragment();
+ videoCallFragment = new CallVideoFragment();
- FragmentTransaction transaction = getFragmentManager().beginTransaction();
- transaction.replace(R.id.fragmentContainer, videoCallFragment);
- try {
- transaction.commitAllowingStateLoss();
- } catch (Exception e) {
- }
- }
+ FragmentTransaction transaction = getFragmentManager().beginTransaction();
+ transaction.replace(R.id.fragmentContainer, videoCallFragment);
+ try {
+ transaction.commitAllowingStateLoss();
+ } catch (Exception e) {
+ }
+ }
- private void toggleMicro() {
- Core lc = LinphoneManager.getLc();
- isMicMuted = !isMicMuted;
- lc.enableMic(!isMicMuted);
- if (isMicMuted) {
- micro.setImageResource(R.drawable.micro_selected);
- } else {
- micro.setImageResource(R.drawable.micro_default);
- }
- }
+ private void toggleMicro() {
+ Core lc = LinphoneManager.getLc();
+ isMicMuted = !isMicMuted;
+ lc.enableMic(!isMicMuted);
+ if (isMicMuted) {
+ micro.setImageResource(R.drawable.micro_selected);
+ } else {
+ micro.setImageResource(R.drawable.micro_default);
+ }
+ }
- protected void toggleSpeaker() {
- isSpeakerEnabled = !isSpeakerEnabled;
- if (LinphoneManager.getLc().getCurrentCall() != null) {
- if (isVideoEnabled(LinphoneManager.getLc().getCurrentCall()))
- LinphoneManager.getInstance().enableProximitySensing(false);
- else
- LinphoneManager.getInstance().enableProximitySensing(!isSpeakerEnabled);
- }
- if (isSpeakerEnabled) {
- LinphoneManager.getInstance().routeAudioToSpeaker();
- speaker.setImageResource(R.drawable.speaker_selected);
- LinphoneManager.getInstance().enableSpeaker(isSpeakerEnabled);
- } else {
- Log.d("Toggle speaker off, routing back to earpiece");
- LinphoneManager.getInstance().routeAudioToReceiver();
- speaker.setImageResource(R.drawable.speaker_default);
- }
- }
+ protected void toggleSpeaker() {
+ isSpeakerEnabled = !isSpeakerEnabled;
+ if (LinphoneManager.getLc().getCurrentCall() != null) {
+ if (isVideoEnabled(LinphoneManager.getLc().getCurrentCall()))
+ LinphoneManager.getInstance().enableProximitySensing(false);
+ else
+ LinphoneManager.getInstance().enableProximitySensing(!isSpeakerEnabled);
+ }
+ if (isSpeakerEnabled) {
+ LinphoneManager.getInstance().routeAudioToSpeaker();
+ speaker.setImageResource(R.drawable.speaker_selected);
+ LinphoneManager.getInstance().enableSpeaker(isSpeakerEnabled);
+ } else {
+ Log.d("Toggle speaker off, routing back to earpiece");
+ LinphoneManager.getInstance().routeAudioToReceiver();
+ speaker.setImageResource(R.drawable.speaker_default);
+ }
+ }
- public void pauseOrResumeCall(Call call) {
- Core lc = LinphoneManager.getLc();
- if (call != null && LinphoneManager.getLc().getCurrentCall() == call) {
- lc.pauseCall(call);
- if (isVideoEnabled(LinphoneManager.getLc().getCurrentCall())) {
- isVideoCallPaused = true;
- }
- pause.setImageResource(R.drawable.pause_big_over_selected);
- } else if (call != null) {
- if (call.getState() == State.Paused) {
- lc.resumeCall(call);
- if (isVideoCallPaused) {
- isVideoCallPaused = false;
- }
- pause.setImageResource(R.drawable.pause_big_default);
- }
- }
- }
+ public void pauseOrResumeCall(Call call) {
+ Core lc = LinphoneManager.getLc();
+ if (call != null && LinphoneManager.getLc().getCurrentCall() == call) {
+ lc.pauseCall(call);
+ if (isVideoEnabled(LinphoneManager.getLc().getCurrentCall())) {
+ isVideoCallPaused = true;
+ }
+ pause.setImageResource(R.drawable.pause_big_over_selected);
+ } else if (call != null) {
+ if (call.getState() == State.Paused) {
+ lc.resumeCall(call);
+ if (isVideoCallPaused) {
+ isVideoCallPaused = false;
+ }
+ pause.setImageResource(R.drawable.pause_big_default);
+ }
+ }
+ }
- private void hangUp() {
- Core lc = LinphoneManager.getLc();
- Call currentCall = lc.getCurrentCall();
+ private void hangUp() {
+ Core lc = LinphoneManager.getLc();
+ Call currentCall = lc.getCurrentCall();
- if (currentCall != null) {
- lc.terminateCall(currentCall);
- } else if (lc.isInConference()) {
- lc.terminateConference();
- } else {
- lc.terminateAllCalls();
- }
- }
+ if (currentCall != null) {
+ lc.terminateCall(currentCall);
+ } else if (lc.isInConference()) {
+ lc.terminateConference();
+ } else {
+ lc.terminateAllCalls();
+ }
+ }
- public void displayVideoCall(boolean display){
- if(display) {
- showStatusBar();
- mControlsLayout.setVisibility(View.VISIBLE);
- mActiveCallHeader.setVisibility(View.VISIBLE);
- callInfo.setVisibility(View.VISIBLE);
- avatar_layout.setVisibility(View.GONE);
- callsList.setVisibility(View.VISIBLE);
- if (cameraNumber > 1) {
- switchCamera.setVisibility(View.VISIBLE);
- }
- } else {
- hideStatusBar();
- mControlsLayout.setVisibility(View.GONE);
- mActiveCallHeader.setVisibility(View.GONE);
- switchCamera.setVisibility(View.GONE);
- callsList.setVisibility(View.GONE);
- }
- }
+ public void displayVideoCall(boolean display) {
+ if (display) {
+ showStatusBar();
+ mControlsLayout.setVisibility(View.VISIBLE);
+ mActiveCallHeader.setVisibility(View.VISIBLE);
+ callInfo.setVisibility(View.VISIBLE);
+ avatar_layout.setVisibility(View.GONE);
+ callsList.setVisibility(View.VISIBLE);
+ if (cameraNumber > 1) {
+ switchCamera.setVisibility(View.VISIBLE);
+ }
+ } else {
+ hideStatusBar();
+ mControlsLayout.setVisibility(View.GONE);
+ mActiveCallHeader.setVisibility(View.GONE);
+ switchCamera.setVisibility(View.GONE);
+ callsList.setVisibility(View.GONE);
+ }
+ }
- public void displayVideoCallControlsIfHidden() {
- if (mControlsLayout != null) {
- if (mControlsLayout.getVisibility() != View.VISIBLE) {
- displayVideoCall(true);
- }
- resetControlsHidingCallBack();
- }
- }
+ public void displayVideoCallControlsIfHidden() {
+ if (mControlsLayout != null) {
+ if (mControlsLayout.getVisibility() != View.VISIBLE) {
+ displayVideoCall(true);
+ }
+ resetControlsHidingCallBack();
+ }
+ }
- public void resetControlsHidingCallBack() {
- if (mControlsHandler != null && mControls != null) {
- mControlsHandler.removeCallbacks(mControls);
- }
- mControls = null;
+ public void resetControlsHidingCallBack() {
+ if (mControlsHandler != null && mControls != null) {
+ mControlsHandler.removeCallbacks(mControls);
+ }
+ mControls = null;
- if (isVideoEnabled(LinphoneManager.getLc().getCurrentCall()) && mControlsHandler != null) {
- mControlsHandler.postDelayed(mControls = new Runnable() {
- public void run() {
- hideNumpad();
- video.setEnabled(true);
- transfer.setVisibility(View.INVISIBLE);
- addCall.setVisibility(View.INVISIBLE);
- conference.setVisibility(View.INVISIBLE);
- displayVideoCall(false);
- numpad.setVisibility(View.GONE);
- options.setImageResource(R.drawable.options_default);
- }
- }, SECONDS_BEFORE_HIDING_CONTROLS);
- }
- }
+ if (isVideoEnabled(LinphoneManager.getLc().getCurrentCall()) && mControlsHandler != null) {
+ mControlsHandler.postDelayed(mControls = new Runnable() {
+ public void run() {
+ hideNumpad();
+ video.setEnabled(true);
+ transfer.setVisibility(View.INVISIBLE);
+ addCall.setVisibility(View.INVISIBLE);
+ conference.setVisibility(View.INVISIBLE);
+ displayVideoCall(false);
+ numpad.setVisibility(View.GONE);
+ options.setImageResource(R.drawable.options_default);
+ }
+ }, SECONDS_BEFORE_HIDING_CONTROLS);
+ }
+ }
- public void removeCallbacks() {
- if (mControlsHandler != null && mControls != null) {
- mControlsHandler.removeCallbacks(mControls);
- }
- mControls = null;
- }
+ public void removeCallbacks() {
+ if (mControlsHandler != null && mControls != null) {
+ mControlsHandler.removeCallbacks(mControls);
+ }
+ mControls = null;
+ }
- private void hideNumpad() {
- if (numpad == null || numpad.getVisibility() != View.VISIBLE) {
- return;
- }
+ private void hideNumpad() {
+ if (numpad == null || numpad.getVisibility() != View.VISIBLE) {
+ return;
+ }
- dialer.setImageResource(R.drawable.footer_dialer);
- numpad.setVisibility(View.GONE);
- }
+ dialer.setImageResource(R.drawable.footer_dialer);
+ numpad.setVisibility(View.GONE);
+ }
- private void hideOrDisplayNumpad() {
- if (numpad == null) {
- return;
- }
+ private void hideOrDisplayNumpad() {
+ if (numpad == null) {
+ return;
+ }
- if (numpad.getVisibility() == View.VISIBLE) {
- hideNumpad();
- } else {
- dialer.setImageResource(R.drawable.dialer_alt_back);
- numpad.setVisibility(View.VISIBLE);
- }
- }
+ if (numpad.getVisibility() == View.VISIBLE) {
+ hideNumpad();
+ } else {
+ dialer.setImageResource(R.drawable.dialer_alt_back);
+ numpad.setVisibility(View.VISIBLE);
+ }
+ }
- private void hideOrDisplayAudioRoutes() {
- if (routeSpeaker.getVisibility() == View.VISIBLE) {
- routeSpeaker.setVisibility(View.INVISIBLE);
- routeBluetooth.setVisibility(View.INVISIBLE);
- routeEarpiece.setVisibility(View.INVISIBLE);
- } else {
- routeSpeaker.setVisibility(View.VISIBLE);
- routeBluetooth.setVisibility(View.VISIBLE);
- routeEarpiece.setVisibility(View.VISIBLE);
- }
- }
+ private void hideOrDisplayAudioRoutes() {
+ if (routeSpeaker.getVisibility() == View.VISIBLE) {
+ routeSpeaker.setVisibility(View.INVISIBLE);
+ routeBluetooth.setVisibility(View.INVISIBLE);
+ routeEarpiece.setVisibility(View.INVISIBLE);
+ } else {
+ routeSpeaker.setVisibility(View.VISIBLE);
+ routeBluetooth.setVisibility(View.VISIBLE);
+ routeEarpiece.setVisibility(View.VISIBLE);
+ }
+ }
- private void hideOrDisplayCallOptions() {
- //Hide options
- if (addCall.getVisibility() == View.VISIBLE) {
- options.setImageResource(R.drawable.options_default);
- if (isTransferAllowed) {
- transfer.setVisibility(View.INVISIBLE);
- }
- addCall.setVisibility(View.INVISIBLE);
- conference.setVisibility(View.INVISIBLE);
- } else { //Display options
- if (isTransferAllowed) {
- transfer.setVisibility(View.VISIBLE);
- }
- addCall.setVisibility(View.VISIBLE);
- conference.setVisibility(View.VISIBLE);
- options.setImageResource(R.drawable.options_selected);
- transfer.setEnabled(LinphoneManager.getLc().getCurrentCall() != null);
- }
- }
+ private void hideOrDisplayCallOptions() {
+ //Hide options
+ if (addCall.getVisibility() == View.VISIBLE) {
+ options.setImageResource(R.drawable.options_default);
+ if (isTransferAllowed) {
+ transfer.setVisibility(View.INVISIBLE);
+ }
+ addCall.setVisibility(View.INVISIBLE);
+ conference.setVisibility(View.INVISIBLE);
+ } else { //Display options
+ if (isTransferAllowed) {
+ transfer.setVisibility(View.VISIBLE);
+ }
+ addCall.setVisibility(View.VISIBLE);
+ conference.setVisibility(View.VISIBLE);
+ options.setImageResource(R.drawable.options_selected);
+ transfer.setEnabled(LinphoneManager.getLc().getCurrentCall() != null);
+ }
+ }
- public void goBackToDialer() {
- Intent intent = new Intent();
- intent.putExtra("Transfer", false);
- setResult(Activity.RESULT_FIRST_USER, intent);
- finish();
- }
+ public void goBackToDialer() {
+ Intent intent = new Intent();
+ intent.putExtra("Transfer", false);
+ setResult(Activity.RESULT_FIRST_USER, intent);
+ finish();
+ }
- private void goBackToDialerAndDisplayTransferButton() {
- Intent intent = new Intent();
- intent.putExtra("Transfer", true);
- setResult(Activity.RESULT_FIRST_USER, intent);
- finish();
- }
+ private void goBackToDialerAndDisplayTransferButton() {
+ Intent intent = new Intent();
+ intent.putExtra("Transfer", true);
+ setResult(Activity.RESULT_FIRST_USER, intent);
+ finish();
+ }
- private void goToChatList() {
- Intent intent = new Intent();
- intent.putExtra("chat", true);
- setResult(Activity.RESULT_FIRST_USER, intent);
- finish();
- }
+ private void goToChatList() {
+ Intent intent = new Intent();
+ intent.putExtra("chat", true);
+ setResult(Activity.RESULT_FIRST_USER, intent);
+ finish();
+ }
- public void acceptCallUpdate(boolean accept) {
- if (timer != null) {
- timer.cancel();
- }
+ public void acceptCallUpdate(boolean accept) {
+ if (timer != null) {
+ timer.cancel();
+ }
- Call call = LinphoneManager.getLc().getCurrentCall();
- if (call == null) {
- return;
- }
+ Call call = LinphoneManager.getLc().getCurrentCall();
+ if (call == null) {
+ return;
+ }
- CallParams params = LinphoneManager.getLc().createCallParams(call);
- if (accept) {
- params.enableVideo(true);
- LinphoneManager.getLc().enableVideoCapture(true);
- LinphoneManager.getLc().enableVideoDisplay(true);
- }
+ CallParams params = LinphoneManager.getLc().createCallParams(call);
+ if (accept) {
+ params.enableVideo(true);
+ LinphoneManager.getLc().enableVideoCapture(true);
+ LinphoneManager.getLc().enableVideoDisplay(true);
+ }
- LinphoneManager.getLc().acceptCallUpdate(call, params);
- }
+ LinphoneManager.getLc().acceptCallUpdate(call, params);
+ }
- public void startIncomingCallActivity() {
- startActivity(new Intent(this, CallIncomingActivity.class));
- }
+ public void startIncomingCallActivity() {
+ startActivity(new Intent(this, CallIncomingActivity.class));
+ }
- public void hideStatusBar() {
- if (isTablet()) {
- return;
- }
+ public void hideStatusBar() {
+ if (isTablet()) {
+ return;
+ }
- findViewById(R.id.status).setVisibility(View.GONE);
- findViewById(R.id.fragmentContainer).setPadding(0, 0, 0, 0);
- }
+ findViewById(R.id.status).setVisibility(View.GONE);
+ findViewById(R.id.fragmentContainer).setPadding(0, 0, 0, 0);
+ }
- public void showStatusBar() {
- if (isTablet()) {
- return;
- }
+ public void showStatusBar() {
+ if (isTablet()) {
+ return;
+ }
- if (status != null && !status.isVisible()) {
- // Hack to ensure statusFragment is visible after coming back to
- // dialer from chat
- status.getView().setVisibility(View.VISIBLE);
- }
- findViewById(R.id.status).setVisibility(View.VISIBLE);
- //findViewById(R.id.fragmentContainer).setPadding(0, LinphoneUtils.pixelsToDpi(getResources(), 40), 0, 0);
- }
+ if (status != null && !status.isVisible()) {
+ // Hack to ensure statusFragment is visible after coming back to
+ // dialer from chat
+ status.getView().setVisibility(View.VISIBLE);
+ }
+ findViewById(R.id.status).setVisibility(View.VISIBLE);
+ //findViewById(R.id.fragmentContainer).setPadding(0, LinphoneUtils.pixelsToDpi(getResources(), 40), 0, 0);
+ }
- private void showAcceptCallUpdateDialog() {
- dialog = new Dialog(this);
- dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
- dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
- dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
- dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
- Drawable d = new ColorDrawable(ContextCompat.getColor(this, R.color.colorC));
- d.setAlpha(200);
- dialog.setContentView(R.layout.dialog);
- dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT,WindowManager.LayoutParams.MATCH_PARENT);
- dialog.getWindow().setBackgroundDrawable(d);
+ private void showAcceptCallUpdateDialog() {
+ dialog = new Dialog(this);
+ dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
+ dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
+ dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
+ dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
+ Drawable d = new ColorDrawable(ContextCompat.getColor(this, R.color.colorC));
+ d.setAlpha(200);
+ dialog.setContentView(R.layout.dialog);
+ dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
+ dialog.getWindow().setBackgroundDrawable(d);
- TextView customText = dialog.findViewById(R.id.customText);
- customText.setText(getResources().getString(R.string.add_video_dialog));
- Button delete = dialog.findViewById(R.id.delete_button);
- delete.setText(R.string.accept);
- Button cancel = dialog.findViewById(R.id.cancel);
- cancel.setText(R.string.decline);
+ TextView customText = dialog.findViewById(R.id.customText);
+ customText.setText(getResources().getString(R.string.add_video_dialog));
+ Button delete = dialog.findViewById(R.id.delete_button);
+ delete.setText(R.string.accept);
+ Button cancel = dialog.findViewById(R.id.cancel);
+ cancel.setText(R.string.decline);
isVideoAsk = true;
- delete.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View view) {
- int camera = getPackageManager().checkPermission(Manifest.permission.CAMERA, getPackageName());
- Log.i("[Permission] Camera permission is " + (camera == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
+ delete.setOnClickListener(new OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ int camera = getPackageManager().checkPermission(Manifest.permission.CAMERA, getPackageName());
+ Log.i("[Permission] Camera permission is " + (camera == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
- if (camera == PackageManager.PERMISSION_GRANTED) {
- CallActivity.instance().acceptCallUpdate(true);
- } else {
- checkAndRequestPermission(Manifest.permission.CAMERA, PERMISSIONS_REQUEST_CAMERA);
- }
+ if (camera == PackageManager.PERMISSION_GRANTED) {
+ CallActivity.instance().acceptCallUpdate(true);
+ } else {
+ checkAndRequestPermission(Manifest.permission.CAMERA, PERMISSIONS_REQUEST_CAMERA);
+ }
isVideoAsk = false;
- dialog.dismiss();
- dialog = null;
- }
- });
+ dialog.dismiss();
+ dialog = null;
+ }
+ });
- cancel.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick (View view){
- if (CallActivity.isInstanciated()) {
- CallActivity.instance().acceptCallUpdate(false);
- }
+ cancel.setOnClickListener(new OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ if (CallActivity.isInstanciated()) {
+ CallActivity.instance().acceptCallUpdate(false);
+ }
isVideoAsk = false;
- dialog.dismiss();
- dialog = null;
- }
- });
- dialog.show();
- }
+ dialog.dismiss();
+ dialog = null;
+ }
+ });
+ dialog.show();
+ }
- @Override
- protected void onResume() {
+ @Override
+ protected void onResume() {
- instance = this;
- super.onResume();
+ instance = this;
+ super.onResume();
- Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- if (lc != null) {
- lc.addListener(mListener);
- }
- isSpeakerEnabled = LinphoneManager.getInstance().isSpeakerEnabled();
+ Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ if (lc != null) {
+ lc.addListener(mListener);
+ }
+ isSpeakerEnabled = LinphoneManager.getInstance().isSpeakerEnabled();
- refreshIncallUi();
- handleViewIntent();
+ refreshIncallUi();
+ handleViewIntent();
if (status != null && status.getisZrtpAsk() && lc != null) {
status.showZRTPDialog(lc.getCurrentCall());
}
- if (!isVideoEnabled(LinphoneManager.getLc().getCurrentCall())) {
- if (!isSpeakerEnabled) {
- LinphoneManager.getInstance().enableProximitySensing(true);
- removeCallbacks();
- }
- }
- }
+ if (!isVideoEnabled(LinphoneManager.getLc().getCurrentCall())) {
+ if (!isSpeakerEnabled) {
+ LinphoneManager.getInstance().enableProximitySensing(true);
+ removeCallbacks();
+ }
+ }
+ }
- private void handleViewIntent() {
- Intent intent = getIntent();
- if(intent != null && intent.getAction() == "android.intent.action.VIEW") {
- Call call = LinphoneManager.getLc().getCurrentCall();
- if(call != null && isVideoEnabled(call)) {
- Player player = call.getPlayer();
- String path = intent.getData().getPath();
- Log.i("Openning " + path);
- /*int openRes = */player.open(path);
+ private void handleViewIntent() {
+ Intent intent = getIntent();
+ if (intent != null && intent.getAction() == "android.intent.action.VIEW") {
+ Call call = LinphoneManager.getLc().getCurrentCall();
+ if (call != null && isVideoEnabled(call)) {
+ Player player = call.getPlayer();
+ String path = intent.getData().getPath();
+ Log.i("Openning " + path);
+ /*int openRes = */
+ player.open(path);
/*if(openRes == -1) {
String message = "Could not open " + path;
Log.e(message);
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
return;
}*/
- Log.i("Start playing");
- /*if(*/player.start()/* == -1) {*/;
+ Log.i("Start playing");
+ /*if(*/
+ player.start()/* == -1) {*/;
/*player.close();
String message = "Could not start playing " + path;
Log.e(message);
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}*/
- }
- }
- }
-
- @Override
- protected void onPause() {
- Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- if (lc != null) {
- lc.removeListener(mListener);
- }
-
- super.onPause();
-
- if (mControlsHandler != null && mControls != null) {
- mControlsHandler.removeCallbacks(mControls);
- }
- mControls = null;
- }
-
- @Override
- protected void onDestroy() {
- LinphoneManager.getInstance().changeStatusToOnline();
- LinphoneManager.getInstance().enableProximitySensing(false);
-
- unregisterReceiver(headsetReceiver);
-
- if (mControlsHandler != null && mControls != null) {
- mControlsHandler.removeCallbacks(mControls);
- }
- mControls = null;
- mControlsHandler = null;
-
- unbindDrawables(findViewById(R.id.topLayout));
- if (mTimer != null) {
- mTimer.cancel();
- }
- instance = null;
- super.onDestroy();
- System.gc();
- }
-
- private void unbindDrawables(View view) {
- if (view.getBackground() != null) {
- view.getBackground().setCallback(null);
- }
- if (view instanceof ImageView) {
- view.setOnClickListener(null);
- }
- if (view instanceof ViewGroup && !(view instanceof AdapterView)) {
- for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
- unbindDrawables(((ViewGroup) view).getChildAt(i));
- }
- ((ViewGroup) view).removeAllViews();
- }
- }
-
- @Override
- public boolean onKeyDown(int keyCode, KeyEvent event) {
- if (LinphoneUtils.onKeyVolumeAdjust(keyCode)) return true;
- if (LinphoneUtils.onKeyBackGoHome(this, keyCode, event)) return true;
- return super.onKeyDown(keyCode, event);
- }
-
- @Override // Never invoke actually
- public void onBackPressed() {
- if (dialog != null) {
- acceptCallUpdate(false);
- dialog.dismiss();
- dialog = null;
- }
- return;
- }
-
- public void bindAudioFragment(CallAudioFragment fragment) {
- audioCallFragment = fragment;
- }
-
- public void bindVideoFragment(CallVideoFragment fragment) {
- videoCallFragment = fragment;
- }
-
-
- //CALL INFORMATION
- private void displayCurrentCall(Call call){
- Address lAddress = call.getRemoteAddress();
- TextView contactName = findViewById(R.id.current_contact_name);
- setContactInformation(contactName, contactPicture, lAddress);
- registerCallDurationTimer(null, call);
- }
-
- private void displayPausedCalls(Resources resources, final Call call, int index) {
- // Control Row
- LinearLayout callView;
-
- if(call == null) {
- callView = (LinearLayout) inflater.inflate(R.layout.conference_paused_row, container, false);
- callView.setId(index + 1);
- callView.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View view) {
- pauseOrResumeConference();
- }
- });
- } else {
- callView = (LinearLayout) inflater.inflate(R.layout.call_inactive_row, container, false);
- callView.setId(index+1);
-
- TextView contactName = callView.findViewById(R.id.contact_name);
- ImageView contactImage = callView.findViewById(R.id.contact_picture);
-
- Address lAddress = call.getRemoteAddress();
- setContactInformation(contactName, contactImage, lAddress);
- displayCallStatusIconAndReturnCallPaused(callView, call);
- registerCallDurationTimer(callView, call);
- }
- callsList.addView(callView);
- }
-
- private void setContactInformation(TextView contactName, ImageView contactPicture, Address lAddress) {
- LinphoneContact lContact = ContactsManager.getInstance().findContactFromAddress(lAddress);
- if (lContact == null) {
- contactName.setText(LinphoneUtils.getAddressDisplayName(lAddress));
- contactPicture.setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap());
- } else {
- contactName.setText(lContact.getFullName());
- LinphoneUtils.setImagePictureFromUri(contactPicture.getContext(), contactPicture, lContact.getPhotoUri(), lContact.getThumbnailUri());
- }
- }
-
- private boolean displayCallStatusIconAndReturnCallPaused(LinearLayout callView, Call call) {
- boolean isCallPaused, isInConference;
- ImageView onCallStateChanged = callView.findViewById(R.id.call_pause);
- onCallStateChanged.setTag(call);
- onCallStateChanged.setOnClickListener(this);
-
- if (call.getState() == State.Paused || call.getState() == State.PausedByRemote || call.getState() == State.Pausing) {
- onCallStateChanged.setImageResource(R.drawable.pause);
- isCallPaused = true;
- isInConference = false;
- } else if (call.getState() == State.OutgoingInit || call.getState() == State.OutgoingProgress || call.getState() == State.OutgoingRinging) {
- isCallPaused = false;
- isInConference = false;
- } else {
- isInConference = isConferenceRunning && call.getConference() != null;
- isCallPaused = false;
- }
-
- return isCallPaused || isInConference;
- }
-
- private void registerCallDurationTimer(View v, Call call) {
- int callDuration = call.getDuration();
- if (callDuration == 0 && call.getState() != State.StreamsRunning) {
- return;
- }
-
- Chronometer timer;
- if(v == null){
- timer = findViewById(R.id.current_call_timer);
- } else {
- timer = v.findViewById(R.id.call_timer);
- }
-
- if (timer == null) {
- throw new IllegalArgumentException("no callee_duration view found");
- }
-
- timer.setBase(SystemClock.elapsedRealtime() - 1000 * callDuration);
- timer.start();
- }
-
- public void refreshCallList(Resources resources) {
- isConferenceRunning = LinphoneManager.getLc().isInConference();
- List pausedCalls = LinphoneUtils.getCallsInState(LinphoneManager.getLc(), Arrays.asList(State.PausedByRemote));
-
- //MultiCalls
- if(LinphoneManager.getLc().getCallsNb() > 1){
- callsList.setVisibility(View.VISIBLE);
- }
-
- //Active call
- if(LinphoneManager.getLc().getCurrentCall() != null) {
- displayNoCurrentCall(false);
- if(isVideoEnabled(LinphoneManager.getLc().getCurrentCall()) && !isConferenceRunning && pausedCalls.size() == 0) {
- displayVideoCall(false);
- } else {
- displayAudioCall();
- }
- } else {
- showAudioView();
- displayNoCurrentCall(true);
- if(LinphoneManager.getLc().getCallsNb() == 1) {
- callsList.setVisibility(View.VISIBLE);
- }
- }
-
- //Conference
- if (isConferenceRunning) {
- displayConference(true);
- } else {
- displayConference(false);
- }
-
- if(callsList != null) {
- callsList.removeAllViews();
- int index = 0;
-
- if (LinphoneManager.getLc().getCallsNb() == 0) {
- goBackToDialer();
- return;
- }
-
- boolean isConfPaused = false;
- for (Call call : LinphoneManager.getLc().getCalls()) {
- if (call.getConference() != null && !isConferenceRunning) {
- isConfPaused = true;
- index++;
- } else {
- if (call != LinphoneManager.getLc().getCurrentCall() && !(call.getConference() != null)) {
- displayPausedCalls(resources, call, index);
- index++;
- } else {
- displayCurrentCall(call);
- }
- }
- }
-
- if (!isConferenceRunning) {
- if (isConfPaused) {
- callsList.setVisibility(View.VISIBLE);
- displayPausedCalls(resources, null, index);
- }
-
- }
-
- }
-
- //Paused by remote
- if (pausedCalls.size() == 1) {
- displayCallPaused(true);
- } else {
- displayCallPaused(false);
- }
- }
-
- //Conference
- private void exitConference(final Call call){
- Core lc = LinphoneManager.getLc();
-
- if (lc.isInConference()) {
- lc.removeFromConference(call);
- if (lc.getConferenceSize() <= 1) {
- lc.leaveConference();
- }
- }
- refreshIncallUi();
- }
-
- private void enterConference() {
- LinphoneManager.getLc().addAllToConference();
- }
-
- public void pauseOrResumeConference() {
- Core lc = LinphoneManager.getLc();
- conferenceStatus = findViewById(R.id.conference_pause);
- if(conferenceStatus != null) {
- if (lc.isInConference()) {
- conferenceStatus.setImageResource(R.drawable.pause_big_over_selected);
- lc.leaveConference();
- } else {
- conferenceStatus.setImageResource(R.drawable.pause_big_default);
- lc.enterConference();
- }
- }
- refreshCallList(getResources());
- }
-
- private void displayConferenceParticipant(int index, final Call call){
- LinearLayout confView = (LinearLayout) inflater.inflate(R.layout.conf_call_control_row, container, false);
- conferenceList.setId(index + 1);
- TextView contact = confView.findViewById(R.id.contactNameOrNumber);
-
- LinphoneContact lContact = ContactsManager.getInstance().findContactFromAddress(call.getRemoteAddress());
- if (lContact == null) {
- contact.setText(call.getRemoteAddress().getUsername());
- } else {
- contact.setText(lContact.getFullName());
- }
-
- registerCallDurationTimer(confView, call);
-
- ImageView quitConference = confView.findViewById(R.id.quitConference);
- quitConference.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View view) {
- exitConference(call);
- }
- });
- conferenceList.addView(confView);
-
- }
-
- private void displayConferenceHeader(){
- conferenceList.setVisibility(View.VISIBLE);
- RelativeLayout headerConference = (RelativeLayout) inflater.inflate(R.layout.conference_header, container, false);
- conferenceStatus = headerConference.findViewById(R.id.conference_pause);
- conferenceStatus.setOnClickListener(this);
- conferenceList.addView(headerConference);
-
- }
-
- private void displayConference(boolean isInConf){
- if(isInConf) {
- mControlsLayout.setVisibility(View.VISIBLE);
- mActiveCallHeader.setVisibility(View.GONE);
- mNoCurrentCall.setVisibility(View.GONE);
- conferenceList.removeAllViews();
-
- //Conference Header
- displayConferenceHeader();
-
- //Conference participant
- int index = 1;
- for (Call call : LinphoneManager.getLc().getCalls()) {
- if (call.getConference() != null) {
- displayConferenceParticipant(index, call);
- index++;
- }
- }
- conferenceList.setVisibility(View.VISIBLE);
- } else {
- conferenceList.setVisibility(View.GONE);
- }
- }
-
- private void displayMissedChats() {
- int count = LinphoneManager.getInstance().getUnreadMessageCount();
-
- if (count > 0) {
- missedChats.setText(count + "");
- missedChats.setVisibility(View.VISIBLE);
- } else {
- missedChats.clearAnimation();
- missedChats.setVisibility(View.GONE);
- }
- }
-
- @SuppressWarnings("deprecation")
- private void formatText(TextView tv, String name, String value) {
- tv.setText(Html.fromHtml("" + name + " " + value));
- }
-
- private String getEncoderText(String mime){
- String ret = mEncoderTexts.get(mime);
- if (ret == null){
- org.linphone.mediastream.Factory msfactory = LinphoneManager.getLc().getMediastreamerFactory();
- ret = msfactory.getEncoderText(mime);
- mEncoderTexts.put(mime, ret);
- }
- return ret;
- }
- private String getDecoderText(String mime){
- String ret = mDecoderTexts.get(mime);
- if (ret == null){
- org.linphone.mediastream.Factory msfactory = LinphoneManager.getLc().getMediastreamerFactory();
- ret = msfactory.getDecoderText(mime);
- mDecoderTexts.put(mime, ret);
- }
- return ret;
- }
-
- private void displayMediaStats(CallParams params, CallStats stats
- , PayloadType media , View layout, TextView title, TextView codec, TextView dl
- , TextView ul, TextView edl, TextView ice, TextView ip, TextView senderLossRate
- , TextView receiverLossRate, TextView enc, TextView dec, TextView videoResolutionSent
- , TextView videoResolutionReceived, TextView videoFpsSent, TextView videoFpsReceived
- , boolean isVideo, TextView jitterBuffer) {
- if (stats != null) {
- String mime = null;
-
- layout.setVisibility(View.VISIBLE);
- title.setVisibility(TextView.VISIBLE);
- if (media != null) {
- mime = media.getMimeType();
- formatText(codec, getString(R.string.call_stats_codec),
- mime + " / " + (media.getClockRate() / 1000) + "kHz");
- }
- if (mime != null ){
- formatText(enc, getString(R.string.call_stats_encoder_name), getEncoderText(mime));
- formatText(dec, getString(R.string.call_stats_decoder_name), getDecoderText(mime));
- }
- formatText(dl, getString(R.string.call_stats_download),
- String.valueOf((int) stats.getDownloadBandwidth()) + " kbits/s");
- formatText(ul, getString(R.string.call_stats_upload),
- String.valueOf((int) stats.getUploadBandwidth()) + " kbits/s");
- if (isVideo) {
- formatText(edl, getString(R.string.call_stats_estimated_download),
- String.valueOf(stats.getEstimatedDownloadBandwidth()) + " kbits/s");
- }
- formatText(ice, getString(R.string.call_stats_ice),
- stats.getIceState().toString());
- formatText(ip, getString(R.string.call_stats_ip),
- (stats.getIpFamilyOfRemote() == AddressFamily.Inet6) ?
- "IpV6" : (stats.getIpFamilyOfRemote() == AddressFamily.Inet) ?
- "IpV4" : "Unknown");
- formatText(senderLossRate, getString(R.string.call_stats_sender_loss_rate),
- new DecimalFormat("##.##").format(stats.getSenderLossRate()) + "%");
- formatText(receiverLossRate, getString(R.string.call_stats_receiver_loss_rate),
- new DecimalFormat("##.##").format(stats.getReceiverLossRate())+ "%");
- if (isVideo) {
- formatText(videoResolutionSent,
- getString(R.string.call_stats_video_resolution_sent),
- "\u2191 " + params.getSentVideoDefinition().getName());
- formatText(videoResolutionReceived,
- getString(R.string.call_stats_video_resolution_received),
- "\u2193 " + params.getReceivedVideoDefinition().getName());
- formatText(videoFpsSent,
- getString(R.string.call_stats_video_fps_sent),
- "\u2191 " + params.getSentFramerate());
- formatText(videoFpsReceived,
- getString(R.string.call_stats_video_fps_received),
- "\u2193 " + params.getReceivedFramerate());
- } else {
- formatText(jitterBuffer, getString(R.string.call_stats_jitter_buffer),
- new DecimalFormat("##.##").format(stats.getJitterBufferSizeMs()) + " ms");
- }
- } else {
- layout.setVisibility(View.GONE);
- title.setVisibility(TextView.GONE);
- }
- }
-
- public void initCallStatsRefresher(final Call call, final View view) {
- if (mCallDisplayedInStats == call) return;
-
- if (mTimer != null && mTask != null) {
- mTimer.cancel();
- mTimer = null;
- mTask = null;
- }
- mCallDisplayedInStats = call;
-
- if (call == null) return;
-
- final TextView titleAudio = view.findViewById(R.id.call_stats_audio);
- final TextView titleVideo = view.findViewById(R.id.call_stats_video);
- final TextView codecAudio = view.findViewById(R.id.codec_audio);
- final TextView codecVideo = view.findViewById(R.id.codec_video);
- final TextView encoderAudio = view.findViewById(R.id.encoder_audio);
- final TextView decoderAudio = view.findViewById(R.id.decoder_audio);
- final TextView encoderVideo = view.findViewById(R.id.encoder_video);
- final TextView decoderVideo = view.findViewById(R.id.decoder_video);
- final TextView dlAudio = view.findViewById(R.id.downloadBandwith_audio);
- final TextView ulAudio = view.findViewById(R.id.uploadBandwith_audio);
- final TextView dlVideo = view.findViewById(R.id.downloadBandwith_video);
- final TextView ulVideo = view.findViewById(R.id.uploadBandwith_video);
- final TextView edlVideo = view.findViewById(R.id.estimatedDownloadBandwidth_video);
- final TextView iceAudio = view.findViewById(R.id.ice_audio);
- final TextView iceVideo = view.findViewById(R.id.ice_video);
- final TextView videoResolutionSent = view.findViewById(R.id.video_resolution_sent);
- final TextView videoResolutionReceived = view.findViewById(R.id.video_resolution_received);
- final TextView videoFpsSent = view.findViewById(R.id.video_fps_sent);
- final TextView videoFpsReceived = view.findViewById(R.id.video_fps_received);
- final TextView senderLossRateAudio = view.findViewById(R.id.senderLossRateAudio);
- final TextView receiverLossRateAudio = view.findViewById(R.id.receiverLossRateAudio);
- final TextView senderLossRateVideo = view.findViewById(R.id.senderLossRateVideo);
- final TextView receiverLossRateVideo = view.findViewById(R.id.receiverLossRateVideo);
- final TextView ipAudio = view.findViewById(R.id.ip_audio);
- final TextView ipVideo = view.findViewById(R.id.ip_video);
- final TextView jitterBufferAudio = view.findViewById(R.id.jitterBufferAudio);
- final View videoLayout = view.findViewById(R.id.callStatsVideo);
- final View audioLayout = view.findViewById(R.id.callStatsAudio);
-
- mCallListener = new CallListenerStub(){
- public void onStateChanged(Call call, Call.State cstate, String message){
- if (cstate == Call.State.End || cstate == Call.State.Error){
- if (mTimer != null) {
- Log.i("Call is terminated, stopping timer in charge of stats refreshing.");
- mTimer.cancel();
- }
- }
- }
- };
-
- mTimer = new Timer();
- mTask = new TimerTask() {
- @Override
- public void run() {
- if (call == null) {
- mTimer.cancel();
- return;
- }
-
- if (titleAudio == null || codecAudio == null || dlVideo == null || edlVideo == null || iceAudio == null
- || videoResolutionSent == null || videoLayout == null || titleVideo == null
- || ipVideo == null || ipAudio == null || codecVideo == null
- || dlAudio == null || ulAudio == null || ulVideo == null || iceVideo == null
- || videoResolutionReceived == null) {
- mTimer.cancel();
- return;
- }
-
- mHandler.post(new Runnable() {
- @Override
- public void run() {
- if (LinphoneManager.getLcIfManagerNotDestroyedOrNull() == null) return;
- synchronized(LinphoneManager.getLc()) {
- if (LinphoneActivity.isInstanciated() && call.getState() != Call.State.Released) {
- CallParams params = call.getCurrentParams();
- if (params != null) {
- CallStats audioStats = call.getStats(StreamType.Audio);
- CallStats videoStats = null;
-
- if (params.videoEnabled())
- videoStats = call.getStats(StreamType.Video);
-
- PayloadType payloadAudio = params.getUsedAudioPayloadType();
- PayloadType payloadVideo = params.getUsedVideoPayloadType();
-
- displayMediaStats(params, audioStats, payloadAudio, audioLayout
- , titleAudio, codecAudio, dlAudio, ulAudio, null, iceAudio
- , ipAudio, senderLossRateAudio, receiverLossRateAudio
- , encoderAudio, decoderAudio, null, null, null, null
- , false, jitterBufferAudio);
-
- displayMediaStats(params, videoStats, payloadVideo, videoLayout
- , titleVideo, codecVideo, dlVideo, ulVideo, edlVideo, iceVideo
- , ipVideo, senderLossRateVideo, receiverLossRateVideo
- , encoderVideo, decoderVideo
- , videoResolutionSent, videoResolutionReceived
- ,videoFpsSent, videoFpsReceived
- , true, null);
- }
- }
- }
- }
- });
- }
- };
- call.addListener(mCallListener);
- mTimer.scheduleAtFixedRate(mTask, 0, 1000);
- }
-
- ////Earset Connectivity Broadcast innerClass
- public class HeadsetReceiver extends BroadcastReceiver {
- @Override
- public void onReceive(Context context, Intent intent) {
- if (!BluetoothManager.getInstance().isBluetoothHeadsetAvailable()) {
- if (intent.hasExtra("state")) {
- switch (intent.getIntExtra("state", 0)) {
- case 0:
- if (oldIsSpeakerEnabled) {
- LinphoneManager.getInstance().routeAudioToSpeaker();
- isSpeakerEnabled = true;
- speaker.setEnabled(true);
- }
- break;
- case 1:
- LinphoneManager.getInstance().routeAudioToReceiver();
- oldIsSpeakerEnabled = isSpeakerEnabled;
- isSpeakerEnabled = false;
- speaker.setEnabled(false);
- break;
- }
- refreshInCallActions();
- }
- }
- }
- }
+ }
+ }
+ }
+
+ @Override
+ protected void onPause() {
+ Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ if (lc != null) {
+ lc.removeListener(mListener);
+ }
+
+ super.onPause();
+
+ if (mControlsHandler != null && mControls != null) {
+ mControlsHandler.removeCallbacks(mControls);
+ }
+ mControls = null;
+ }
+
+ @Override
+ protected void onDestroy() {
+ LinphoneManager.getInstance().changeStatusToOnline();
+ LinphoneManager.getInstance().enableProximitySensing(false);
+
+ unregisterReceiver(headsetReceiver);
+
+ if (mControlsHandler != null && mControls != null) {
+ mControlsHandler.removeCallbacks(mControls);
+ }
+ mControls = null;
+ mControlsHandler = null;
+
+ unbindDrawables(findViewById(R.id.topLayout));
+ if (mTimer != null) {
+ mTimer.cancel();
+ }
+ instance = null;
+ super.onDestroy();
+ System.gc();
+ }
+
+ private void unbindDrawables(View view) {
+ if (view.getBackground() != null) {
+ view.getBackground().setCallback(null);
+ }
+ if (view instanceof ImageView) {
+ view.setOnClickListener(null);
+ }
+ if (view instanceof ViewGroup && !(view instanceof AdapterView)) {
+ for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
+ unbindDrawables(((ViewGroup) view).getChildAt(i));
+ }
+ ((ViewGroup) view).removeAllViews();
+ }
+ }
+
+ @Override
+ public boolean onKeyDown(int keyCode, KeyEvent event) {
+ if (LinphoneUtils.onKeyVolumeAdjust(keyCode)) return true;
+ if (LinphoneUtils.onKeyBackGoHome(this, keyCode, event)) return true;
+ return super.onKeyDown(keyCode, event);
+ }
+
+ @Override // Never invoke actually
+ public void onBackPressed() {
+ if (dialog != null) {
+ acceptCallUpdate(false);
+ dialog.dismiss();
+ dialog = null;
+ }
+ return;
+ }
+
+ public void bindAudioFragment(CallAudioFragment fragment) {
+ audioCallFragment = fragment;
+ }
+
+ public void bindVideoFragment(CallVideoFragment fragment) {
+ videoCallFragment = fragment;
+ }
+
+
+ //CALL INFORMATION
+ private void displayCurrentCall(Call call) {
+ Address lAddress = call.getRemoteAddress();
+ TextView contactName = findViewById(R.id.current_contact_name);
+ setContactInformation(contactName, contactPicture, lAddress);
+ registerCallDurationTimer(null, call);
+ }
+
+ private void displayPausedCalls(Resources resources, final Call call, int index) {
+ // Control Row
+ LinearLayout callView;
+
+ if (call == null) {
+ callView = (LinearLayout) inflater.inflate(R.layout.conference_paused_row, container, false);
+ callView.setId(index + 1);
+ callView.setOnClickListener(new OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ pauseOrResumeConference();
+ }
+ });
+ } else {
+ callView = (LinearLayout) inflater.inflate(R.layout.call_inactive_row, container, false);
+ callView.setId(index + 1);
+
+ TextView contactName = callView.findViewById(R.id.contact_name);
+ ImageView contactImage = callView.findViewById(R.id.contact_picture);
+
+ Address lAddress = call.getRemoteAddress();
+ setContactInformation(contactName, contactImage, lAddress);
+ displayCallStatusIconAndReturnCallPaused(callView, call);
+ registerCallDurationTimer(callView, call);
+ }
+ callsList.addView(callView);
+ }
+
+ private void setContactInformation(TextView contactName, ImageView contactPicture, Address lAddress) {
+ LinphoneContact lContact = ContactsManager.getInstance().findContactFromAddress(lAddress);
+ if (lContact == null) {
+ contactName.setText(LinphoneUtils.getAddressDisplayName(lAddress));
+ contactPicture.setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap());
+ } else {
+ contactName.setText(lContact.getFullName());
+ LinphoneUtils.setImagePictureFromUri(contactPicture.getContext(), contactPicture, lContact.getPhotoUri(), lContact.getThumbnailUri());
+ }
+ }
+
+ private boolean displayCallStatusIconAndReturnCallPaused(LinearLayout callView, Call call) {
+ boolean isCallPaused, isInConference;
+ ImageView onCallStateChanged = callView.findViewById(R.id.call_pause);
+ onCallStateChanged.setTag(call);
+ onCallStateChanged.setOnClickListener(this);
+
+ if (call.getState() == State.Paused || call.getState() == State.PausedByRemote || call.getState() == State.Pausing) {
+ onCallStateChanged.setImageResource(R.drawable.pause);
+ isCallPaused = true;
+ isInConference = false;
+ } else if (call.getState() == State.OutgoingInit || call.getState() == State.OutgoingProgress || call.getState() == State.OutgoingRinging) {
+ isCallPaused = false;
+ isInConference = false;
+ } else {
+ isInConference = isConferenceRunning && call.getConference() != null;
+ isCallPaused = false;
+ }
+
+ return isCallPaused || isInConference;
+ }
+
+ private void registerCallDurationTimer(View v, Call call) {
+ int callDuration = call.getDuration();
+ if (callDuration == 0 && call.getState() != State.StreamsRunning) {
+ return;
+ }
+
+ Chronometer timer;
+ if (v == null) {
+ timer = findViewById(R.id.current_call_timer);
+ } else {
+ timer = v.findViewById(R.id.call_timer);
+ }
+
+ if (timer == null) {
+ throw new IllegalArgumentException("no callee_duration view found");
+ }
+
+ timer.setBase(SystemClock.elapsedRealtime() - 1000 * callDuration);
+ timer.start();
+ }
+
+ public void refreshCallList(Resources resources) {
+ isConferenceRunning = LinphoneManager.getLc().isInConference();
+ List pausedCalls = LinphoneUtils.getCallsInState(LinphoneManager.getLc(), Arrays.asList(State.PausedByRemote));
+
+ //MultiCalls
+ if (LinphoneManager.getLc().getCallsNb() > 1) {
+ callsList.setVisibility(View.VISIBLE);
+ }
+
+ //Active call
+ if (LinphoneManager.getLc().getCurrentCall() != null) {
+ displayNoCurrentCall(false);
+ if (isVideoEnabled(LinphoneManager.getLc().getCurrentCall()) && !isConferenceRunning && pausedCalls.size() == 0) {
+ displayVideoCall(false);
+ } else {
+ displayAudioCall();
+ }
+ } else {
+ showAudioView();
+ displayNoCurrentCall(true);
+ if (LinphoneManager.getLc().getCallsNb() == 1) {
+ callsList.setVisibility(View.VISIBLE);
+ }
+ }
+
+ //Conference
+ if (isConferenceRunning) {
+ displayConference(true);
+ } else {
+ displayConference(false);
+ }
+
+ if (callsList != null) {
+ callsList.removeAllViews();
+ int index = 0;
+
+ if (LinphoneManager.getLc().getCallsNb() == 0) {
+ goBackToDialer();
+ return;
+ }
+
+ boolean isConfPaused = false;
+ for (Call call : LinphoneManager.getLc().getCalls()) {
+ if (call.getConference() != null && !isConferenceRunning) {
+ isConfPaused = true;
+ index++;
+ } else {
+ if (call != LinphoneManager.getLc().getCurrentCall() && !(call.getConference() != null)) {
+ displayPausedCalls(resources, call, index);
+ index++;
+ } else {
+ displayCurrentCall(call);
+ }
+ }
+ }
+
+ if (!isConferenceRunning) {
+ if (isConfPaused) {
+ callsList.setVisibility(View.VISIBLE);
+ displayPausedCalls(resources, null, index);
+ }
+
+ }
+
+ }
+
+ //Paused by remote
+ if (pausedCalls.size() == 1) {
+ displayCallPaused(true);
+ } else {
+ displayCallPaused(false);
+ }
+ }
+
+ //Conference
+ private void exitConference(final Call call) {
+ Core lc = LinphoneManager.getLc();
+
+ if (lc.isInConference()) {
+ lc.removeFromConference(call);
+ if (lc.getConferenceSize() <= 1) {
+ lc.leaveConference();
+ }
+ }
+ refreshIncallUi();
+ }
+
+ private void enterConference() {
+ LinphoneManager.getLc().addAllToConference();
+ }
+
+ public void pauseOrResumeConference() {
+ Core lc = LinphoneManager.getLc();
+ conferenceStatus = findViewById(R.id.conference_pause);
+ if (conferenceStatus != null) {
+ if (lc.isInConference()) {
+ conferenceStatus.setImageResource(R.drawable.pause_big_over_selected);
+ lc.leaveConference();
+ } else {
+ conferenceStatus.setImageResource(R.drawable.pause_big_default);
+ lc.enterConference();
+ }
+ }
+ refreshCallList(getResources());
+ }
+
+ private void displayConferenceParticipant(int index, final Call call) {
+ LinearLayout confView = (LinearLayout) inflater.inflate(R.layout.conf_call_control_row, container, false);
+ conferenceList.setId(index + 1);
+ TextView contact = confView.findViewById(R.id.contactNameOrNumber);
+
+ LinphoneContact lContact = ContactsManager.getInstance().findContactFromAddress(call.getRemoteAddress());
+ if (lContact == null) {
+ contact.setText(call.getRemoteAddress().getUsername());
+ } else {
+ contact.setText(lContact.getFullName());
+ }
+
+ registerCallDurationTimer(confView, call);
+
+ ImageView quitConference = confView.findViewById(R.id.quitConference);
+ quitConference.setOnClickListener(new OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ exitConference(call);
+ }
+ });
+ conferenceList.addView(confView);
+
+ }
+
+ private void displayConferenceHeader() {
+ conferenceList.setVisibility(View.VISIBLE);
+ RelativeLayout headerConference = (RelativeLayout) inflater.inflate(R.layout.conference_header, container, false);
+ conferenceStatus = headerConference.findViewById(R.id.conference_pause);
+ conferenceStatus.setOnClickListener(this);
+ conferenceList.addView(headerConference);
+
+ }
+
+ private void displayConference(boolean isInConf) {
+ if (isInConf) {
+ mControlsLayout.setVisibility(View.VISIBLE);
+ mActiveCallHeader.setVisibility(View.GONE);
+ mNoCurrentCall.setVisibility(View.GONE);
+ conferenceList.removeAllViews();
+
+ //Conference Header
+ displayConferenceHeader();
+
+ //Conference participant
+ int index = 1;
+ for (Call call : LinphoneManager.getLc().getCalls()) {
+ if (call.getConference() != null) {
+ displayConferenceParticipant(index, call);
+ index++;
+ }
+ }
+ conferenceList.setVisibility(View.VISIBLE);
+ } else {
+ conferenceList.setVisibility(View.GONE);
+ }
+ }
+
+ private void displayMissedChats() {
+ int count = LinphoneManager.getInstance().getUnreadMessageCount();
+
+ if (count > 0) {
+ missedChats.setText(count + "");
+ missedChats.setVisibility(View.VISIBLE);
+ } else {
+ missedChats.clearAnimation();
+ missedChats.setVisibility(View.GONE);
+ }
+ }
+
+ @SuppressWarnings("deprecation")
+ private void formatText(TextView tv, String name, String value) {
+ tv.setText(Html.fromHtml("" + name + " " + value));
+ }
+
+ private String getEncoderText(String mime) {
+ String ret = mEncoderTexts.get(mime);
+ if (ret == null) {
+ org.linphone.mediastream.Factory msfactory = LinphoneManager.getLc().getMediastreamerFactory();
+ ret = msfactory.getEncoderText(mime);
+ mEncoderTexts.put(mime, ret);
+ }
+ return ret;
+ }
+
+ private String getDecoderText(String mime) {
+ String ret = mDecoderTexts.get(mime);
+ if (ret == null) {
+ org.linphone.mediastream.Factory msfactory = LinphoneManager.getLc().getMediastreamerFactory();
+ ret = msfactory.getDecoderText(mime);
+ mDecoderTexts.put(mime, ret);
+ }
+ return ret;
+ }
+
+ private void displayMediaStats(CallParams params, CallStats stats
+ , PayloadType media, View layout, TextView title, TextView codec, TextView dl
+ , TextView ul, TextView edl, TextView ice, TextView ip, TextView senderLossRate
+ , TextView receiverLossRate, TextView enc, TextView dec, TextView videoResolutionSent
+ , TextView videoResolutionReceived, TextView videoFpsSent, TextView videoFpsReceived
+ , boolean isVideo, TextView jitterBuffer) {
+ if (stats != null) {
+ String mime = null;
+
+ layout.setVisibility(View.VISIBLE);
+ title.setVisibility(TextView.VISIBLE);
+ if (media != null) {
+ mime = media.getMimeType();
+ formatText(codec, getString(R.string.call_stats_codec),
+ mime + " / " + (media.getClockRate() / 1000) + "kHz");
+ }
+ if (mime != null) {
+ formatText(enc, getString(R.string.call_stats_encoder_name), getEncoderText(mime));
+ formatText(dec, getString(R.string.call_stats_decoder_name), getDecoderText(mime));
+ }
+ formatText(dl, getString(R.string.call_stats_download),
+ String.valueOf((int) stats.getDownloadBandwidth()) + " kbits/s");
+ formatText(ul, getString(R.string.call_stats_upload),
+ String.valueOf((int) stats.getUploadBandwidth()) + " kbits/s");
+ if (isVideo) {
+ formatText(edl, getString(R.string.call_stats_estimated_download),
+ String.valueOf(stats.getEstimatedDownloadBandwidth()) + " kbits/s");
+ }
+ formatText(ice, getString(R.string.call_stats_ice),
+ stats.getIceState().toString());
+ formatText(ip, getString(R.string.call_stats_ip),
+ (stats.getIpFamilyOfRemote() == AddressFamily.Inet6) ?
+ "IpV6" : (stats.getIpFamilyOfRemote() == AddressFamily.Inet) ?
+ "IpV4" : "Unknown");
+ formatText(senderLossRate, getString(R.string.call_stats_sender_loss_rate),
+ new DecimalFormat("##.##").format(stats.getSenderLossRate()) + "%");
+ formatText(receiverLossRate, getString(R.string.call_stats_receiver_loss_rate),
+ new DecimalFormat("##.##").format(stats.getReceiverLossRate()) + "%");
+ if (isVideo) {
+ formatText(videoResolutionSent,
+ getString(R.string.call_stats_video_resolution_sent),
+ "\u2191 " + params.getSentVideoDefinition().getName());
+ formatText(videoResolutionReceived,
+ getString(R.string.call_stats_video_resolution_received),
+ "\u2193 " + params.getReceivedVideoDefinition().getName());
+ formatText(videoFpsSent,
+ getString(R.string.call_stats_video_fps_sent),
+ "\u2191 " + params.getSentFramerate());
+ formatText(videoFpsReceived,
+ getString(R.string.call_stats_video_fps_received),
+ "\u2193 " + params.getReceivedFramerate());
+ } else {
+ formatText(jitterBuffer, getString(R.string.call_stats_jitter_buffer),
+ new DecimalFormat("##.##").format(stats.getJitterBufferSizeMs()) + " ms");
+ }
+ } else {
+ layout.setVisibility(View.GONE);
+ title.setVisibility(TextView.GONE);
+ }
+ }
+
+ public void initCallStatsRefresher(final Call call, final View view) {
+ if (mCallDisplayedInStats == call) return;
+
+ if (mTimer != null && mTask != null) {
+ mTimer.cancel();
+ mTimer = null;
+ mTask = null;
+ }
+ mCallDisplayedInStats = call;
+
+ if (call == null) return;
+
+ final TextView titleAudio = view.findViewById(R.id.call_stats_audio);
+ final TextView titleVideo = view.findViewById(R.id.call_stats_video);
+ final TextView codecAudio = view.findViewById(R.id.codec_audio);
+ final TextView codecVideo = view.findViewById(R.id.codec_video);
+ final TextView encoderAudio = view.findViewById(R.id.encoder_audio);
+ final TextView decoderAudio = view.findViewById(R.id.decoder_audio);
+ final TextView encoderVideo = view.findViewById(R.id.encoder_video);
+ final TextView decoderVideo = view.findViewById(R.id.decoder_video);
+ final TextView dlAudio = view.findViewById(R.id.downloadBandwith_audio);
+ final TextView ulAudio = view.findViewById(R.id.uploadBandwith_audio);
+ final TextView dlVideo = view.findViewById(R.id.downloadBandwith_video);
+ final TextView ulVideo = view.findViewById(R.id.uploadBandwith_video);
+ final TextView edlVideo = view.findViewById(R.id.estimatedDownloadBandwidth_video);
+ final TextView iceAudio = view.findViewById(R.id.ice_audio);
+ final TextView iceVideo = view.findViewById(R.id.ice_video);
+ final TextView videoResolutionSent = view.findViewById(R.id.video_resolution_sent);
+ final TextView videoResolutionReceived = view.findViewById(R.id.video_resolution_received);
+ final TextView videoFpsSent = view.findViewById(R.id.video_fps_sent);
+ final TextView videoFpsReceived = view.findViewById(R.id.video_fps_received);
+ final TextView senderLossRateAudio = view.findViewById(R.id.senderLossRateAudio);
+ final TextView receiverLossRateAudio = view.findViewById(R.id.receiverLossRateAudio);
+ final TextView senderLossRateVideo = view.findViewById(R.id.senderLossRateVideo);
+ final TextView receiverLossRateVideo = view.findViewById(R.id.receiverLossRateVideo);
+ final TextView ipAudio = view.findViewById(R.id.ip_audio);
+ final TextView ipVideo = view.findViewById(R.id.ip_video);
+ final TextView jitterBufferAudio = view.findViewById(R.id.jitterBufferAudio);
+ final View videoLayout = view.findViewById(R.id.callStatsVideo);
+ final View audioLayout = view.findViewById(R.id.callStatsAudio);
+
+ mCallListener = new CallListenerStub() {
+ public void onStateChanged(Call call, Call.State cstate, String message) {
+ if (cstate == Call.State.End || cstate == Call.State.Error) {
+ if (mTimer != null) {
+ Log.i("Call is terminated, stopping timer in charge of stats refreshing.");
+ mTimer.cancel();
+ }
+ }
+ }
+ };
+
+ mTimer = new Timer();
+ mTask = new TimerTask() {
+ @Override
+ public void run() {
+ if (call == null) {
+ mTimer.cancel();
+ return;
+ }
+
+ if (titleAudio == null || codecAudio == null || dlVideo == null || edlVideo == null || iceAudio == null
+ || videoResolutionSent == null || videoLayout == null || titleVideo == null
+ || ipVideo == null || ipAudio == null || codecVideo == null
+ || dlAudio == null || ulAudio == null || ulVideo == null || iceVideo == null
+ || videoResolutionReceived == null) {
+ mTimer.cancel();
+ return;
+ }
+
+ mHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ if (LinphoneManager.getLcIfManagerNotDestroyedOrNull() == null) return;
+ synchronized (LinphoneManager.getLc()) {
+ if (LinphoneActivity.isInstanciated() && call.getState() != Call.State.Released) {
+ CallParams params = call.getCurrentParams();
+ if (params != null) {
+ CallStats audioStats = call.getStats(StreamType.Audio);
+ CallStats videoStats = null;
+
+ if (params.videoEnabled())
+ videoStats = call.getStats(StreamType.Video);
+
+ PayloadType payloadAudio = params.getUsedAudioPayloadType();
+ PayloadType payloadVideo = params.getUsedVideoPayloadType();
+
+ displayMediaStats(params, audioStats, payloadAudio, audioLayout
+ , titleAudio, codecAudio, dlAudio, ulAudio, null, iceAudio
+ , ipAudio, senderLossRateAudio, receiverLossRateAudio
+ , encoderAudio, decoderAudio, null, null, null, null
+ , false, jitterBufferAudio);
+
+ displayMediaStats(params, videoStats, payloadVideo, videoLayout
+ , titleVideo, codecVideo, dlVideo, ulVideo, edlVideo, iceVideo
+ , ipVideo, senderLossRateVideo, receiverLossRateVideo
+ , encoderVideo, decoderVideo
+ , videoResolutionSent, videoResolutionReceived
+ , videoFpsSent, videoFpsReceived
+ , true, null);
+ }
+ }
+ }
+ }
+ });
+ }
+ };
+ call.addListener(mCallListener);
+ mTimer.scheduleAtFixedRate(mTask, 0, 1000);
+ }
+
+ ////Earset Connectivity Broadcast innerClass
+ public class HeadsetReceiver extends BroadcastReceiver {
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ if (!BluetoothManager.getInstance().isBluetoothHeadsetAvailable()) {
+ if (intent.hasExtra("state")) {
+ switch (intent.getIntExtra("state", 0)) {
+ case 0:
+ if (oldIsSpeakerEnabled) {
+ LinphoneManager.getInstance().routeAudioToSpeaker();
+ isSpeakerEnabled = true;
+ speaker.setEnabled(true);
+ }
+ break;
+ case 1:
+ LinphoneManager.getInstance().routeAudioToReceiver();
+ oldIsSpeakerEnabled = isSpeakerEnabled;
+ isSpeakerEnabled = false;
+ speaker.setEnabled(false);
+ break;
+ }
+ refreshInCallActions();
+ }
+ }
+ }
+ }
}
diff --git a/src/android/org/linphone/call/CallAudioFragment.java b/src/android/org/linphone/call/CallAudioFragment.java
index 9112d0ae7..eca7df897 100644
--- a/src/android/org/linphone/call/CallAudioFragment.java
+++ b/src/android/org/linphone/call/CallAudioFragment.java
@@ -18,6 +18,7 @@ You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
+
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
@@ -27,27 +28,27 @@ import android.view.ViewGroup;
import org.linphone.R;
public class CallAudioFragment extends Fragment {
- private CallActivity incallActvityInstance;
+ private CallActivity incallActvityInstance;
- @Override
+ @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
+ Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.audio, container, false);
return view;
}
- @Override
- public void onStart() {
- super.onStart();
- incallActvityInstance = (CallActivity) getActivity();
+ @Override
+ public void onStart() {
+ super.onStart();
+ incallActvityInstance = (CallActivity) getActivity();
- if (incallActvityInstance != null) {
- incallActvityInstance.bindAudioFragment(this);
- }
+ if (incallActvityInstance != null) {
+ incallActvityInstance.bindAudioFragment(this);
+ }
- // Just to be sure we have incall controls
- if (incallActvityInstance != null) {
- incallActvityInstance.removeCallbacks();
- }
- }
+ // Just to be sure we have incall controls
+ if (incallActvityInstance != null) {
+ incallActvityInstance.removeCallbacks();
+ }
+ }
}
diff --git a/src/android/org/linphone/call/CallHistoryAdapter.java b/src/android/org/linphone/call/CallHistoryAdapter.java
index 7c6bcb06f..1114203c2 100644
--- a/src/android/org/linphone/call/CallHistoryAdapter.java
+++ b/src/android/org/linphone/call/CallHistoryAdapter.java
@@ -49,7 +49,7 @@ import java.util.List;
public class CallHistoryAdapter extends SelectableAdapter {
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
- View.OnLongClickListener{
+ View.OnLongClickListener {
public TextView contact;
public ImageView detail;
public CheckBox select;
@@ -92,6 +92,7 @@ public class CallHistoryAdapter extends SelectableAdapter logs,CallHistoryAdapter.ViewHolder.ClickListener listener ,SelectableHelper helper) {
+ public CallHistoryAdapter(Context aContext, List logs, CallHistoryAdapter.ViewHolder.ClickListener listener, SelectableHelper helper) {
super(helper);
this.mLogs = logs;
this.mContext = aContext;
@@ -125,7 +126,7 @@ public class CallHistoryAdapter extends SelectableAdapter 0) {
- CallLog previousLog = mLogs.get(position-1);
+ CallLog previousLog = mLogs.get(position - 1);
long previousTimestamp = previousLog.getStartDate() * 1000;
Calendar previousLogTime = Calendar.getInstance();
previousLogTime.setTimeInMillis(previousTimestamp);
diff --git a/src/android/org/linphone/call/CallIncomingActivity.java b/src/android/org/linphone/call/CallIncomingActivity.java
index cb149fafc..0fa350d01 100644
--- a/src/android/org/linphone/call/CallIncomingActivity.java
+++ b/src/android/org/linphone/call/CallIncomingActivity.java
@@ -33,8 +33,6 @@ import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
-import org.linphone.contacts.ContactsManager;
-import org.linphone.contacts.LinphoneContact;
import org.linphone.LinphoneManager;
import org.linphone.LinphonePreferences;
import org.linphone.LinphoneService;
@@ -42,6 +40,8 @@ import org.linphone.LinphoneUtils;
import org.linphone.R;
import org.linphone.activities.LinphoneActivity;
import org.linphone.activities.LinphoneGenericActivity;
+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;
@@ -54,306 +54,306 @@ import java.util.ArrayList;
import java.util.List;
public class CallIncomingActivity extends LinphoneGenericActivity {
- private static CallIncomingActivity instance;
+ private static CallIncomingActivity instance;
- private TextView name, number;
- private ImageView contactPicture, accept, decline, arrow;
- private Call mCall;
- private CoreListenerStub mListener;
- private LinearLayout acceptUnlock;
- private LinearLayout declineUnlock;
- private boolean alreadyAcceptedOrDeniedCall, begin;
- private float answerX, oldMove;
- private float declineX;
+ private TextView name, number;
+ private ImageView contactPicture, accept, decline, arrow;
+ private Call mCall;
+ private CoreListenerStub mListener;
+ private LinearLayout acceptUnlock;
+ private LinearLayout declineUnlock;
+ private boolean alreadyAcceptedOrDeniedCall, begin;
+ private float answerX, oldMove;
+ private float declineX;
- public static CallIncomingActivity instance() {
- return instance;
- }
+ public static CallIncomingActivity instance() {
+ return instance;
+ }
- public static boolean isInstanciated() {
- return instance != null;
- }
+ public static boolean isInstanciated() {
+ return instance != null;
+ }
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
- if (getResources().getBoolean(R.bool.orientation_portrait_only)) {
- setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
- }
+ if (getResources().getBoolean(R.bool.orientation_portrait_only)) {
+ setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
+ }
- getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
- setContentView(R.layout.call_incoming);
+ getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
+ setContentView(R.layout.call_incoming);
- name = findViewById(R.id.contact_name);
- number = findViewById(R.id.contact_number);
- contactPicture = findViewById(R.id.contact_picture);
+ name = findViewById(R.id.contact_name);
+ number = findViewById(R.id.contact_number);
+ contactPicture = findViewById(R.id.contact_picture);
- // set this flag so this activity will stay in front of the keyguard
- int flags = WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON;
- getWindow().addFlags(flags);
+ // set this flag so this activity will stay in front of the keyguard
+ int flags = WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON;
+ getWindow().addFlags(flags);
- final int screenWidth = getResources().getDisplayMetrics().widthPixels;
+ final int screenWidth = getResources().getDisplayMetrics().widthPixels;
- acceptUnlock = findViewById(R.id.acceptUnlock);
- declineUnlock = findViewById(R.id.declineUnlock);
+ acceptUnlock = findViewById(R.id.acceptUnlock);
+ declineUnlock = findViewById(R.id.declineUnlock);
- accept = findViewById(R.id.accept);
- lookupCurrentCall();
- if (LinphonePreferences.instance() != null && mCall != null && mCall.getRemoteParams() != null &&
- LinphonePreferences.instance().shouldAutomaticallyAcceptVideoRequests() &&
- mCall.getRemoteParams().videoEnabled()) {
- accept.setImageResource(R.drawable.call_video_start);
- }
- decline = findViewById(R.id.decline);
- arrow = findViewById(R.id.arrow_hangup);
- accept.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
+ accept = findViewById(R.id.accept);
+ lookupCurrentCall();
+ if (LinphonePreferences.instance() != null && mCall != null && mCall.getRemoteParams() != null &&
+ LinphonePreferences.instance().shouldAutomaticallyAcceptVideoRequests() &&
+ mCall.getRemoteParams().videoEnabled()) {
+ accept.setImageResource(R.drawable.call_video_start);
+ }
+ decline = findViewById(R.id.decline);
+ arrow = findViewById(R.id.arrow_hangup);
+ accept.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
- decline.setVisibility(View.GONE);
- acceptUnlock.setVisibility(View.VISIBLE);
+ decline.setVisibility(View.GONE);
+ acceptUnlock.setVisibility(View.VISIBLE);
- }
- });
+ }
+ });
- accept.setOnTouchListener(new View.OnTouchListener() {
- @Override
- public boolean onTouch(View view, MotionEvent motionEvent) {
- float curX;
- switch (motionEvent.getAction()) {
- case MotionEvent.ACTION_DOWN:
- acceptUnlock.setVisibility(View.VISIBLE);
- decline.setVisibility(View.GONE);
- answerX = motionEvent.getX()+accept.getWidth()/2;
- begin = true;
- oldMove = 0;
- break;
- case MotionEvent.ACTION_MOVE:
- curX = motionEvent.getX();
- view.scrollBy((int) (answerX - curX), view.getScrollY());
- oldMove -= answerX - curX;
- answerX = curX;
- if (oldMove < -25)
- begin = false;
- if (curX < arrow.getWidth() && !begin) {
- answer();
- return true;
- }
- break;
- case MotionEvent.ACTION_UP:
- view.scrollTo(0, view.getScrollY());
- decline.setVisibility(View.VISIBLE);
- acceptUnlock.setVisibility(View.GONE);
- break;
- }
- return true;
- }
- });
+ accept.setOnTouchListener(new View.OnTouchListener() {
+ @Override
+ public boolean onTouch(View view, MotionEvent motionEvent) {
+ float curX;
+ switch (motionEvent.getAction()) {
+ case MotionEvent.ACTION_DOWN:
+ acceptUnlock.setVisibility(View.VISIBLE);
+ decline.setVisibility(View.GONE);
+ answerX = motionEvent.getX() + accept.getWidth() / 2;
+ begin = true;
+ oldMove = 0;
+ break;
+ case MotionEvent.ACTION_MOVE:
+ curX = motionEvent.getX();
+ view.scrollBy((int) (answerX - curX), view.getScrollY());
+ oldMove -= answerX - curX;
+ answerX = curX;
+ if (oldMove < -25)
+ begin = false;
+ if (curX < arrow.getWidth() && !begin) {
+ answer();
+ return true;
+ }
+ break;
+ case MotionEvent.ACTION_UP:
+ view.scrollTo(0, view.getScrollY());
+ decline.setVisibility(View.VISIBLE);
+ acceptUnlock.setVisibility(View.GONE);
+ break;
+ }
+ return true;
+ }
+ });
- decline.setOnTouchListener(new View.OnTouchListener() {
- @Override
- public boolean onTouch(View view, MotionEvent motionEvent) {
- float curX;
- switch (motionEvent.getAction()) {
- case MotionEvent.ACTION_DOWN:
- declineUnlock.setVisibility(View.VISIBLE);
- accept.setVisibility(View.GONE);
- declineX = motionEvent.getX();
- break;
- case MotionEvent.ACTION_MOVE:
- curX = motionEvent.getX();
- view.scrollBy((int) (declineX - curX), view.getScrollY());
- declineX = curX;
- if (curX > (screenWidth-arrow.getWidth()*4)) {
- decline();
- return true;
- }
- break;
- case MotionEvent.ACTION_UP:
- view.scrollTo(0, view.getScrollY());
- accept.setVisibility(View.VISIBLE);
- declineUnlock.setVisibility(View.GONE);
- break;
- }
- return true;
- }
- });
+ decline.setOnTouchListener(new View.OnTouchListener() {
+ @Override
+ public boolean onTouch(View view, MotionEvent motionEvent) {
+ float curX;
+ switch (motionEvent.getAction()) {
+ case MotionEvent.ACTION_DOWN:
+ declineUnlock.setVisibility(View.VISIBLE);
+ accept.setVisibility(View.GONE);
+ declineX = motionEvent.getX();
+ break;
+ case MotionEvent.ACTION_MOVE:
+ curX = motionEvent.getX();
+ view.scrollBy((int) (declineX - curX), view.getScrollY());
+ declineX = curX;
+ if (curX > (screenWidth - arrow.getWidth() * 4)) {
+ decline();
+ return true;
+ }
+ break;
+ case MotionEvent.ACTION_UP:
+ view.scrollTo(0, view.getScrollY());
+ accept.setVisibility(View.VISIBLE);
+ declineUnlock.setVisibility(View.GONE);
+ break;
+ }
+ return true;
+ }
+ });
- decline.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- accept.setVisibility(View.GONE);
- acceptUnlock.setVisibility(View.VISIBLE);
- }
- });
+ decline.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ accept.setVisibility(View.GONE);
+ acceptUnlock.setVisibility(View.VISIBLE);
+ }
+ });
- mListener = new CoreListenerStub(){
- @Override
- public void onCallStateChanged(Core lc, Call call, State state, String message) {
- if (call == mCall && State.End == state) {
- finish();
- }
- if (state == State.StreamsRunning) {
- Log.e("CallIncommingActivity - onCreate - State.StreamsRunning - speaker = "+ LinphoneManager.getInstance().isSpeakerEnabled());
- // The following should not be needed except some devices need it (e.g. Galaxy S).
- LinphoneManager.getInstance().enableSpeaker(LinphoneManager.getInstance().isSpeakerEnabled());
- }
- }
- };
+ mListener = new CoreListenerStub() {
+ @Override
+ public void onCallStateChanged(Core lc, Call call, State state, String message) {
+ if (call == mCall && State.End == state) {
+ finish();
+ }
+ if (state == State.StreamsRunning) {
+ Log.e("CallIncommingActivity - onCreate - State.StreamsRunning - speaker = " + LinphoneManager.getInstance().isSpeakerEnabled());
+ // The following should not be needed except some devices need it (e.g. Galaxy S).
+ LinphoneManager.getInstance().enableSpeaker(LinphoneManager.getInstance().isSpeakerEnabled());
+ }
+ }
+ };
- super.onCreate(savedInstanceState);
- instance = this;
- }
+ super.onCreate(savedInstanceState);
+ instance = this;
+ }
- @Override
- protected void onResume() {
- super.onResume();
- instance = this;
- Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- if (lc != null) {
- lc.addListener(mListener);
- }
+ @Override
+ protected void onResume() {
+ super.onResume();
+ instance = this;
+ Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ if (lc != null) {
+ lc.addListener(mListener);
+ }
- alreadyAcceptedOrDeniedCall = false;
- mCall = null;
+ alreadyAcceptedOrDeniedCall = false;
+ mCall = null;
- // Only one call ringing at a time is allowed
- lookupCurrentCall();
- if (mCall == null) {
- //The incoming call no longer exists.
- Log.d("Couldn't find incoming call");
- finish();
- return;
- }
+ // Only one call ringing at a time is allowed
+ lookupCurrentCall();
+ if (mCall == null) {
+ //The incoming call no longer exists.
+ Log.d("Couldn't find incoming call");
+ finish();
+ return;
+ }
- Address address = mCall.getRemoteAddress();
- LinphoneContact contact = ContactsManager.getInstance().findContactFromAddress(address);
- if (contact != null) {
- LinphoneUtils.setImagePictureFromUri(this, contactPicture, contact.getPhotoUri(), contact.getThumbnailUri());
- name.setText(contact.getFullName());
- } else {
- name.setText(LinphoneUtils.getAddressDisplayName(address));
- }
- number.setText(address.asStringUriOnly());
- }
+ Address address = mCall.getRemoteAddress();
+ LinphoneContact contact = ContactsManager.getInstance().findContactFromAddress(address);
+ if (contact != null) {
+ LinphoneUtils.setImagePictureFromUri(this, contactPicture, contact.getPhotoUri(), contact.getThumbnailUri());
+ name.setText(contact.getFullName());
+ } else {
+ name.setText(LinphoneUtils.getAddressDisplayName(address));
+ }
+ number.setText(address.asStringUriOnly());
+ }
- @Override
- protected void onStart() {
- super.onStart();
- checkAndRequestCallPermissions();
- }
+ @Override
+ protected void onStart() {
+ super.onStart();
+ checkAndRequestCallPermissions();
+ }
- @Override
- protected void onPause() {
- Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- if (lc != null) {
- lc.removeListener(mListener);
- }
- super.onPause();
- }
+ @Override
+ protected void onPause() {
+ Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ if (lc != null) {
+ lc.removeListener(mListener);
+ }
+ super.onPause();
+ }
- @Override
- protected void onDestroy() {
- super.onDestroy();
- instance = null;
- }
+ @Override
+ protected void onDestroy() {
+ super.onDestroy();
+ instance = null;
+ }
- @Override
- public boolean onKeyDown(int keyCode, KeyEvent event) {
- if (LinphoneManager.isInstanciated() && (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME)) {
- LinphoneManager.getLc().terminateCall(mCall);
- finish();
- }
- return super.onKeyDown(keyCode, event);
- }
+ @Override
+ public boolean onKeyDown(int keyCode, KeyEvent event) {
+ if (LinphoneManager.isInstanciated() && (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME)) {
+ LinphoneManager.getLc().terminateCall(mCall);
+ finish();
+ }
+ return super.onKeyDown(keyCode, event);
+ }
- private void lookupCurrentCall() {
- if (LinphoneManager.getLcIfManagerNotDestroyedOrNull() != null) {
- List calls = LinphoneUtils.getCalls(LinphoneManager.getLc());
- for (Call call : calls) {
- if (State.IncomingReceived == call.getState()) {
- mCall = call;
- break;
- }
- }
- }
- }
+ private void lookupCurrentCall() {
+ if (LinphoneManager.getLcIfManagerNotDestroyedOrNull() != null) {
+ List calls = LinphoneUtils.getCalls(LinphoneManager.getLc());
+ for (Call call : calls) {
+ if (State.IncomingReceived == call.getState()) {
+ mCall = call;
+ break;
+ }
+ }
+ }
+ }
- private void decline() {
- if (alreadyAcceptedOrDeniedCall) {
- return;
- }
- alreadyAcceptedOrDeniedCall = true;
+ private void decline() {
+ if (alreadyAcceptedOrDeniedCall) {
+ return;
+ }
+ alreadyAcceptedOrDeniedCall = true;
- LinphoneManager.getLc().terminateCall(mCall);
- finish();
- }
+ LinphoneManager.getLc().terminateCall(mCall);
+ finish();
+ }
- private void answer() {
- if (alreadyAcceptedOrDeniedCall) {
- return;
- }
- alreadyAcceptedOrDeniedCall = true;
+ private void answer() {
+ if (alreadyAcceptedOrDeniedCall) {
+ return;
+ }
+ alreadyAcceptedOrDeniedCall = true;
- CallParams params = LinphoneManager.getLc().createCallParams(mCall);
+ CallParams params = LinphoneManager.getLc().createCallParams(mCall);
- boolean isLowBandwidthConnection = !LinphoneUtils.isHighBandwidthConnection(LinphoneService.instance().getApplicationContext());
+ boolean isLowBandwidthConnection = !LinphoneUtils.isHighBandwidthConnection(LinphoneService.instance().getApplicationContext());
- if (params != null) {
- params.enableLowBandwidth(isLowBandwidthConnection);
- }else {
- Log.e("Could not create call params for call");
- }
+ if (params != null) {
+ params.enableLowBandwidth(isLowBandwidthConnection);
+ } else {
+ Log.e("Could not create call params for call");
+ }
- if (params == null || !LinphoneManager.getInstance().acceptCallWithParams(mCall, params)) {
- // the above method takes care of Samsung Galaxy S
- Toast.makeText(this, R.string.couldnt_accept_call, Toast.LENGTH_LONG).show();
- } else {
- if (!LinphoneActivity.isInstanciated()) {
- return;
- }
- LinphoneManager.getInstance().routeAudioToReceiver();
- LinphoneActivity.instance().startIncallActivity(mCall);
- }
- }
+ if (params == null || !LinphoneManager.getInstance().acceptCallWithParams(mCall, params)) {
+ // the above method takes care of Samsung Galaxy S
+ Toast.makeText(this, R.string.couldnt_accept_call, Toast.LENGTH_LONG).show();
+ } else {
+ if (!LinphoneActivity.isInstanciated()) {
+ return;
+ }
+ LinphoneManager.getInstance().routeAudioToReceiver();
+ LinphoneActivity.instance().startIncallActivity(mCall);
+ }
+ }
- private void checkAndRequestCallPermissions() {
- ArrayList permissionsList = new ArrayList();
+ private void checkAndRequestCallPermissions() {
+ ArrayList permissionsList = new ArrayList();
- int recordAudio = getPackageManager().checkPermission(Manifest.permission.RECORD_AUDIO, getPackageName());
- Log.i("[Permission] Record audio permission is " + (recordAudio == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
- int camera = getPackageManager().checkPermission(Manifest.permission.CAMERA, getPackageName());
- Log.i("[Permission] Camera permission is " + (camera == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
+ int recordAudio = getPackageManager().checkPermission(Manifest.permission.RECORD_AUDIO, getPackageName());
+ Log.i("[Permission] Record audio permission is " + (recordAudio == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
+ int camera = getPackageManager().checkPermission(Manifest.permission.CAMERA, getPackageName());
+ Log.i("[Permission] Camera permission is " + (camera == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
- if (recordAudio != PackageManager.PERMISSION_GRANTED) {
- if (LinphonePreferences.instance().firstTimeAskingForPermission(Manifest.permission.RECORD_AUDIO) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO)) {
- Log.i("[Permission] Asking for record audio");
- permissionsList.add(Manifest.permission.RECORD_AUDIO);
- }
- }
- if (LinphonePreferences.instance().shouldInitiateVideoCall() || LinphonePreferences.instance().shouldAutomaticallyAcceptVideoRequests()) {
- if (camera != PackageManager.PERMISSION_GRANTED) {
- if (LinphonePreferences.instance().firstTimeAskingForPermission(Manifest.permission.CAMERA) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
- Log.i("[Permission] Asking for camera");
- permissionsList.add(Manifest.permission.CAMERA);
- }
- }
- }
+ if (recordAudio != PackageManager.PERMISSION_GRANTED) {
+ if (LinphonePreferences.instance().firstTimeAskingForPermission(Manifest.permission.RECORD_AUDIO) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO)) {
+ Log.i("[Permission] Asking for record audio");
+ permissionsList.add(Manifest.permission.RECORD_AUDIO);
+ }
+ }
+ if (LinphonePreferences.instance().shouldInitiateVideoCall() || LinphonePreferences.instance().shouldAutomaticallyAcceptVideoRequests()) {
+ if (camera != PackageManager.PERMISSION_GRANTED) {
+ if (LinphonePreferences.instance().firstTimeAskingForPermission(Manifest.permission.CAMERA) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
+ Log.i("[Permission] Asking for camera");
+ permissionsList.add(Manifest.permission.CAMERA);
+ }
+ }
+ }
- if (permissionsList.size() > 0) {
- String[] permissions = new String[permissionsList.size()];
- permissions = permissionsList.toArray(permissions);
- ActivityCompat.requestPermissions(this, permissions, 0);
- }
- }
+ if (permissionsList.size() > 0) {
+ String[] permissions = new String[permissionsList.size()];
+ permissions = permissionsList.toArray(permissions);
+ ActivityCompat.requestPermissions(this, permissions, 0);
+ }
+ }
- @Override
- public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
- for (int i = 0; i < permissions.length; i++) {
- Log.i("[Permission] " + permissions[i] + " is " + (grantResults[i] == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
- }
- }
+ @Override
+ public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
+ for (int i = 0; i < permissions.length; i++) {
+ Log.i("[Permission] " + permissions[i] + " is " + (grantResults[i] == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
+ }
+ }
}
\ No newline at end of file
diff --git a/src/android/org/linphone/call/CallManager.java b/src/android/org/linphone/call/CallManager.java
index b1eefbd4c..1a868fe29 100644
--- a/src/android/org/linphone/call/CallManager.java
+++ b/src/android/org/linphone/call/CallManager.java
@@ -33,84 +33,87 @@ import org.linphone.mediastream.Log;
*/
public class CallManager {
- private static CallManager instance;
+ private static CallManager instance;
- private CallManager() {}
- public static final synchronized CallManager getInstance() {
- if (instance == null) instance = new CallManager();
- return instance;
- }
+ private CallManager() {
+ }
- private BandwidthManager bm() {
- return BandwidthManager.getInstance();
- }
+ public static final synchronized CallManager getInstance() {
+ if (instance == null) instance = new CallManager();
+ return instance;
+ }
- public void inviteAddress(Address lAddress, boolean videoEnabled, boolean lowBandwidth) throws CoreException {
- Core lc = LinphoneManager.getLc();
+ private BandwidthManager bm() {
+ return BandwidthManager.getInstance();
+ }
- CallParams params = lc.createCallParams(null);
- bm().updateWithProfileSettings(lc, params);
+ public void inviteAddress(Address lAddress, boolean videoEnabled, boolean lowBandwidth) throws CoreException {
+ Core lc = LinphoneManager.getLc();
- if (videoEnabled && params.videoEnabled()) {
- params.enableVideo(true);
- } else {
- params.enableVideo(false);
- }
+ CallParams params = lc.createCallParams(null);
+ bm().updateWithProfileSettings(lc, params);
- if (lowBandwidth) {
- params.enableLowBandwidth(true);
- Log.d("Low bandwidth enabled in call params");
- }
+ if (videoEnabled && params.videoEnabled()) {
+ params.enableVideo(true);
+ } else {
+ params.enableVideo(false);
+ }
- lc.inviteAddressWithParams(lAddress, params);
- }
+ if (lowBandwidth) {
+ params.enableLowBandwidth(true);
+ Log.d("Low bandwidth enabled in call params");
+ }
- /**
- * Add video to a currently running voice only call.
- * No re-invite is sent if the current call is already video
- * or if the bandwidth settings are too low.
- * @return if updateCall called
- */
- public boolean reinviteWithVideo() {
- Core lc = LinphoneManager.getLc();
- Call lCall = lc.getCurrentCall();
- if (lCall == null) {
- Log.e("Trying to reinviteWithVideo while not in call: doing nothing");
- return false;
- }
- CallParams params = lc.createCallParams(lCall);
+ lc.inviteAddressWithParams(lAddress, params);
+ }
- if (params.videoEnabled()) return false;
+ /**
+ * Add video to a currently running voice only call.
+ * No re-invite is sent if the current call is already video
+ * or if the bandwidth settings are too low.
+ *
+ * @return if updateCall called
+ */
+ public boolean reinviteWithVideo() {
+ Core lc = LinphoneManager.getLc();
+ Call lCall = lc.getCurrentCall();
+ if (lCall == null) {
+ Log.e("Trying to reinviteWithVideo while not in call: doing nothing");
+ return false;
+ }
+ CallParams params = lc.createCallParams(lCall);
+
+ if (params.videoEnabled()) return false;
- // Check if video possible regarding bandwidth limitations
- bm().updateWithProfileSettings(lc, params);
+ // Check if video possible regarding bandwidth limitations
+ bm().updateWithProfileSettings(lc, params);
- // Abort if not enough bandwidth...
- if (!params.videoEnabled()) {
- return false;
- }
+ // Abort if not enough bandwidth...
+ if (!params.videoEnabled()) {
+ return false;
+ }
- // Not yet in video call: try to re-invite with video
- lc.updateCall(lCall, params);
- return true;
- }
+ // Not yet in video call: try to re-invite with video
+ lc.updateCall(lCall, params);
+ return true;
+ }
- /**
- * Change the preferred video size used by linphone core. (impact landscape/portrait buffer).
- * Update current call, without reinvite.
- * The camera will be restarted when mediastreamer chain is recreated and setParameters is called.
- */
- public void updateCall() {
- Core lc = LinphoneManager.getLc();
- Call lCall = lc.getCurrentCall();
- if (lCall == null) {
- Log.e("Trying to updateCall while not in call: doing nothing");
- return;
- }
- CallParams params = lc.createCallParams(lCall);
- bm().updateWithProfileSettings(lc, params);
- lc.updateCall(lCall, null);
- }
+ /**
+ * Change the preferred video size used by linphone core. (impact landscape/portrait buffer).
+ * Update current call, without reinvite.
+ * The camera will be restarted when mediastreamer chain is recreated and setParameters is called.
+ */
+ public void updateCall() {
+ Core lc = LinphoneManager.getLc();
+ Call lCall = lc.getCurrentCall();
+ if (lCall == null) {
+ Log.e("Trying to updateCall while not in call: doing nothing");
+ return;
+ }
+ CallParams params = lc.createCallParams(lCall);
+ bm().updateWithProfileSettings(lc, params);
+ lc.updateCall(lCall, null);
+ }
}
diff --git a/src/android/org/linphone/call/CallOutgoingActivity.java b/src/android/org/linphone/call/CallOutgoingActivity.java
index 798da14a5..1f5c64298 100644
--- a/src/android/org/linphone/call/CallOutgoingActivity.java
+++ b/src/android/org/linphone/call/CallOutgoingActivity.java
@@ -19,25 +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.util.ArrayList;
-import java.util.List;
-
-import org.linphone.contacts.ContactsManager;
-import org.linphone.contacts.LinphoneContact;
-import org.linphone.LinphoneManager;
-import org.linphone.LinphonePreferences;
-import org.linphone.LinphoneUtils;
-import org.linphone.R;
-import org.linphone.activities.LinphoneActivity;
-import org.linphone.activities.LinphoneGenericActivity;
-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.Reason;
-import org.linphone.mediastream.Log;
-
import android.Manifest;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
@@ -54,258 +35,276 @@ import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
-public class CallOutgoingActivity extends LinphoneGenericActivity implements OnClickListener{
- private static CallOutgoingActivity instance;
+import org.linphone.LinphoneManager;
+import org.linphone.LinphonePreferences;
+import org.linphone.LinphoneUtils;
+import org.linphone.R;
+import org.linphone.activities.LinphoneActivity;
+import org.linphone.activities.LinphoneGenericActivity;
+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.Reason;
+import org.linphone.mediastream.Log;
- private TextView name, number;
- private ImageView contactPicture, micro, speaker, hangUp;
- private Call mCall;
- private CoreListenerStub mListener;
- private boolean isMicMuted, isSpeakerEnabled;
+import java.util.ArrayList;
+import java.util.List;
- public static CallOutgoingActivity instance() {
- return instance;
- }
+public class CallOutgoingActivity extends LinphoneGenericActivity implements OnClickListener {
+ private static CallOutgoingActivity instance;
- public static boolean isInstanciated() {
- return instance != null;
- }
+ private TextView name, number;
+ private ImageView contactPicture, micro, speaker, hangUp;
+ private Call mCall;
+ private CoreListenerStub mListener;
+ private boolean isMicMuted, isSpeakerEnabled;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
+ public static CallOutgoingActivity instance() {
+ return instance;
+ }
- if (getResources().getBoolean(R.bool.orientation_portrait_only)) {
- setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
- }
+ public static boolean isInstanciated() {
+ return instance != null;
+ }
- getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
- setContentView(R.layout.call_outgoing);
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
- name = findViewById(R.id.contact_name);
- number = findViewById(R.id.contact_number);
- contactPicture = findViewById(R.id.contact_picture);
+ if (getResources().getBoolean(R.bool.orientation_portrait_only)) {
+ setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
+ }
- isMicMuted = false;
- isSpeakerEnabled = false;
+ getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
+ setContentView(R.layout.call_outgoing);
- micro = findViewById(R.id.micro);
- micro.setOnClickListener(this);
- speaker = findViewById(R.id.speaker);
- speaker.setOnClickListener(this);
+ name = findViewById(R.id.contact_name);
+ number = findViewById(R.id.contact_number);
+ contactPicture = findViewById(R.id.contact_picture);
- // set this flag so this activity will stay in front of the keyguard
- int flags = WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON;
- getWindow().addFlags(flags);
+ isMicMuted = false;
+ isSpeakerEnabled = false;
- hangUp = findViewById(R.id.outgoing_hang_up);
- hangUp.setOnClickListener(this);
+ micro = findViewById(R.id.micro);
+ micro.setOnClickListener(this);
+ speaker = findViewById(R.id.speaker);
+ speaker.setOnClickListener(this);
- mListener = new CoreListenerStub(){
- @Override
- public void onCallStateChanged(Core lc, Call call, Call.State state, String message) {
- if (call == mCall && State.Connected == state) {
- if (!LinphoneActivity.isInstanciated()) {
- return;
- }
- LinphoneActivity.instance().startIncallActivity(mCall);
- finish();
- return;
- } else if (state == State.Error) {
- // Convert Core message for internalization
- if (call.getErrorInfo().getReason() == Reason.Declined) {
- displayCustomToast(getString(R.string.error_call_declined), Toast.LENGTH_SHORT);
- decline();
- } else if (call.getErrorInfo().getReason() == Reason.NotFound) {
- displayCustomToast(getString(R.string.error_user_not_found), Toast.LENGTH_SHORT);
- decline();
- } else if (call.getErrorInfo().getReason() == Reason.NotAcceptable) {
- displayCustomToast(getString(R.string.error_incompatible_media), Toast.LENGTH_SHORT);
- decline();
- } else if (call.getErrorInfo().getReason() == Reason.Busy) {
- displayCustomToast(getString(R.string.error_user_busy), Toast.LENGTH_SHORT);
- decline();
- } else if (message != null) {
- displayCustomToast(getString(R.string.error_unknown) + " - " + message, Toast.LENGTH_SHORT);
- decline();
- }
- }else if (state == State.End) {
- // Convert Core message for internalization
- if (call.getErrorInfo().getReason() == Reason.Declined) {
- displayCustomToast(getString(R.string.error_call_declined), Toast.LENGTH_SHORT);
- decline();
- }
- }
+ // set this flag so this activity will stay in front of the keyguard
+ int flags = WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON;
+ getWindow().addFlags(flags);
- if (LinphoneManager.getLc().getCallsNb() == 0) {
- finish();
- return;
- }
- }
- };
- instance = this;
- }
+ hangUp = findViewById(R.id.outgoing_hang_up);
+ hangUp.setOnClickListener(this);
- @Override
- protected void onResume() {
- super.onResume();
- instance = this;
- Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- if (lc != null) {
- lc.addListener(mListener);
- }
+ mListener = new CoreListenerStub() {
+ @Override
+ public void onCallStateChanged(Core lc, Call call, Call.State state, String message) {
+ if (call == mCall && State.Connected == state) {
+ if (!LinphoneActivity.isInstanciated()) {
+ return;
+ }
+ LinphoneActivity.instance().startIncallActivity(mCall);
+ finish();
+ return;
+ } else if (state == State.Error) {
+ // Convert Core message for internalization
+ if (call.getErrorInfo().getReason() == Reason.Declined) {
+ displayCustomToast(getString(R.string.error_call_declined), Toast.LENGTH_SHORT);
+ decline();
+ } else if (call.getErrorInfo().getReason() == Reason.NotFound) {
+ displayCustomToast(getString(R.string.error_user_not_found), Toast.LENGTH_SHORT);
+ decline();
+ } else if (call.getErrorInfo().getReason() == Reason.NotAcceptable) {
+ displayCustomToast(getString(R.string.error_incompatible_media), Toast.LENGTH_SHORT);
+ decline();
+ } else if (call.getErrorInfo().getReason() == Reason.Busy) {
+ displayCustomToast(getString(R.string.error_user_busy), Toast.LENGTH_SHORT);
+ decline();
+ } else if (message != null) {
+ displayCustomToast(getString(R.string.error_unknown) + " - " + message, Toast.LENGTH_SHORT);
+ decline();
+ }
+ } else if (state == State.End) {
+ // Convert Core message for internalization
+ if (call.getErrorInfo().getReason() == Reason.Declined) {
+ displayCustomToast(getString(R.string.error_call_declined), Toast.LENGTH_SHORT);
+ decline();
+ }
+ }
- mCall = null;
+ if (LinphoneManager.getLc().getCallsNb() == 0) {
+ finish();
+ return;
+ }
+ }
+ };
+ instance = this;
+ }
- // Only one call ringing at a time is allowed
- if (LinphoneManager.getLcIfManagerNotDestroyedOrNull() != null) {
- List calls = LinphoneUtils.getCalls(LinphoneManager.getLc());
- for (Call call : calls) {
- State cstate = call.getState();
- if (State.OutgoingInit == cstate || State.OutgoingProgress == cstate
- || State.OutgoingRinging == cstate || State.OutgoingEarlyMedia == cstate) {
- mCall = call;
- break;
- }
- if (State.StreamsRunning == cstate) {
- if (!LinphoneActivity.isInstanciated()) {
- return;
- }
- LinphoneActivity.instance().startIncallActivity(mCall);
- finish();
- return;
- }
- }
- }
- if (mCall == null) {
- Log.e("Couldn't find outgoing call");
- finish();
- return;
- }
+ @Override
+ protected void onResume() {
+ super.onResume();
+ instance = this;
+ Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ if (lc != null) {
+ lc.addListener(mListener);
+ }
- Address address = mCall.getRemoteAddress();
- LinphoneContact contact = ContactsManager.getInstance().findContactFromAddress(address);
- if (contact != null) {
- LinphoneUtils.setImagePictureFromUri(this, contactPicture, contact.getPhotoUri(), contact.getThumbnailUri());
- name.setText(contact.getFullName());
- } else {
- name.setText(LinphoneUtils.getAddressDisplayName(address));
- }
- number.setText(address.asStringUriOnly());
- }
+ mCall = null;
- @Override
- protected void onStart() {
- super.onStart();
- checkAndRequestCallPermissions();
- }
+ // Only one call ringing at a time is allowed
+ if (LinphoneManager.getLcIfManagerNotDestroyedOrNull() != null) {
+ List calls = LinphoneUtils.getCalls(LinphoneManager.getLc());
+ for (Call call : calls) {
+ State cstate = call.getState();
+ if (State.OutgoingInit == cstate || State.OutgoingProgress == cstate
+ || State.OutgoingRinging == cstate || State.OutgoingEarlyMedia == cstate) {
+ mCall = call;
+ break;
+ }
+ if (State.StreamsRunning == cstate) {
+ if (!LinphoneActivity.isInstanciated()) {
+ return;
+ }
+ LinphoneActivity.instance().startIncallActivity(mCall);
+ finish();
+ return;
+ }
+ }
+ }
+ if (mCall == null) {
+ Log.e("Couldn't find outgoing call");
+ finish();
+ return;
+ }
- @Override
- protected void onPause() {
- Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- if (lc != null) {
- lc.removeListener(mListener);
- }
- super.onPause();
- }
+ Address address = mCall.getRemoteAddress();
+ LinphoneContact contact = ContactsManager.getInstance().findContactFromAddress(address);
+ if (contact != null) {
+ LinphoneUtils.setImagePictureFromUri(this, contactPicture, contact.getPhotoUri(), contact.getThumbnailUri());
+ name.setText(contact.getFullName());
+ } else {
+ name.setText(LinphoneUtils.getAddressDisplayName(address));
+ }
+ number.setText(address.asStringUriOnly());
+ }
- @Override
- protected void onDestroy() {
- super.onDestroy();
- instance = null;
- }
+ @Override
+ protected void onStart() {
+ super.onStart();
+ checkAndRequestCallPermissions();
+ }
- @Override
- public void onClick(View v) {
- int id = v.getId();
+ @Override
+ protected void onPause() {
+ Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ if (lc != null) {
+ lc.removeListener(mListener);
+ }
+ super.onPause();
+ }
- if (id == R.id.micro) {
- isMicMuted = !isMicMuted;
- if(isMicMuted) {
- micro.setImageResource(R.drawable.micro_selected);
- } else {
- micro.setImageResource(R.drawable.micro_default);
- }
- LinphoneManager.getLc().enableMic(!isMicMuted);
- }
- if (id == R.id.speaker) {
- isSpeakerEnabled = !isSpeakerEnabled;
- if(isSpeakerEnabled) {
- speaker.setImageResource(R.drawable.speaker_selected);
- } else {
- speaker.setImageResource(R.drawable.speaker_default);
- }
- LinphoneManager.getInstance().enableSpeaker(isSpeakerEnabled);
- }
- if (id == R.id.outgoing_hang_up) {
- decline();
- }
- }
+ @Override
+ protected void onDestroy() {
+ super.onDestroy();
+ instance = null;
+ }
- @Override
- public boolean onKeyDown(int keyCode, KeyEvent event) {
- if (LinphoneManager.isInstanciated() && (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME)) {
- LinphoneManager.getLc().terminateCall(mCall);
- finish();
- }
- return super.onKeyDown(keyCode, event);
- }
+ @Override
+ public void onClick(View v) {
+ int id = v.getId();
- public void displayCustomToast(final String message, final int duration) {
- LayoutInflater inflater = getLayoutInflater();
- View layout = inflater.inflate(R.layout.toast, (ViewGroup) findViewById(R.id.toastRoot));
+ if (id == R.id.micro) {
+ isMicMuted = !isMicMuted;
+ if (isMicMuted) {
+ micro.setImageResource(R.drawable.micro_selected);
+ } else {
+ micro.setImageResource(R.drawable.micro_default);
+ }
+ LinphoneManager.getLc().enableMic(!isMicMuted);
+ }
+ if (id == R.id.speaker) {
+ isSpeakerEnabled = !isSpeakerEnabled;
+ if (isSpeakerEnabled) {
+ speaker.setImageResource(R.drawable.speaker_selected);
+ } else {
+ speaker.setImageResource(R.drawable.speaker_default);
+ }
+ LinphoneManager.getInstance().enableSpeaker(isSpeakerEnabled);
+ }
+ if (id == R.id.outgoing_hang_up) {
+ decline();
+ }
+ }
- TextView toastText = layout.findViewById(R.id.toastMessage);
- toastText.setText(message);
+ @Override
+ public boolean onKeyDown(int keyCode, KeyEvent event) {
+ if (LinphoneManager.isInstanciated() && (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME)) {
+ LinphoneManager.getLc().terminateCall(mCall);
+ finish();
+ }
+ return super.onKeyDown(keyCode, event);
+ }
- final Toast toast = new Toast(getApplicationContext());
- toast.setGravity(Gravity.CENTER, 0, 0);
- toast.setDuration(duration);
- toast.setView(layout);
- toast.show();
- }
+ public void displayCustomToast(final String message, final int duration) {
+ LayoutInflater inflater = getLayoutInflater();
+ View layout = inflater.inflate(R.layout.toast, (ViewGroup) findViewById(R.id.toastRoot));
- private void decline() {
- LinphoneManager.getLc().terminateCall(mCall);
- finish();
- }
+ TextView toastText = layout.findViewById(R.id.toastMessage);
+ toastText.setText(message);
+
+ final Toast toast = new Toast(getApplicationContext());
+ toast.setGravity(Gravity.CENTER, 0, 0);
+ toast.setDuration(duration);
+ toast.setView(layout);
+ toast.show();
+ }
+
+ private void decline() {
+ LinphoneManager.getLc().terminateCall(mCall);
+ finish();
+ }
+ private void checkAndRequestCallPermissions() {
+ ArrayList permissionsList = new ArrayList();
- private void checkAndRequestCallPermissions() {
- ArrayList permissionsList = new ArrayList();
+ int recordAudio = getPackageManager().checkPermission(Manifest.permission.RECORD_AUDIO, getPackageName());
+ Log.i("[Permission] Record audio permission is " + (recordAudio == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
+ int camera = getPackageManager().checkPermission(Manifest.permission.CAMERA, getPackageName());
+ Log.i("[Permission] Camera permission is " + (camera == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
- int recordAudio = getPackageManager().checkPermission(Manifest.permission.RECORD_AUDIO, getPackageName());
- Log.i("[Permission] Record audio permission is " + (recordAudio == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
- int camera = getPackageManager().checkPermission(Manifest.permission.CAMERA, getPackageName());
- Log.i("[Permission] Camera permission is " + (camera == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
+ if (recordAudio != PackageManager.PERMISSION_GRANTED) {
+ if (LinphonePreferences.instance().firstTimeAskingForPermission(Manifest.permission.RECORD_AUDIO) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO)) {
+ Log.i("[Permission] Asking for record audio");
+ permissionsList.add(Manifest.permission.RECORD_AUDIO);
+ }
+ }
+ if (LinphonePreferences.instance().shouldInitiateVideoCall() || LinphonePreferences.instance().shouldAutomaticallyAcceptVideoRequests()) {
+ if (camera != PackageManager.PERMISSION_GRANTED) {
+ if (LinphonePreferences.instance().firstTimeAskingForPermission(Manifest.permission.CAMERA) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
+ Log.i("[Permission] Asking for camera");
+ permissionsList.add(Manifest.permission.CAMERA);
+ }
+ }
+ }
- if (recordAudio != PackageManager.PERMISSION_GRANTED) {
- if (LinphonePreferences.instance().firstTimeAskingForPermission(Manifest.permission.RECORD_AUDIO) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO)) {
- Log.i("[Permission] Asking for record audio");
- permissionsList.add(Manifest.permission.RECORD_AUDIO);
- }
- }
- if (LinphonePreferences.instance().shouldInitiateVideoCall() || LinphonePreferences.instance().shouldAutomaticallyAcceptVideoRequests()) {
- if (camera != PackageManager.PERMISSION_GRANTED) {
- if (LinphonePreferences.instance().firstTimeAskingForPermission(Manifest.permission.CAMERA) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
- Log.i("[Permission] Asking for camera");
- permissionsList.add(Manifest.permission.CAMERA);
- }
- }
- }
+ if (permissionsList.size() > 0) {
+ String[] permissions = new String[permissionsList.size()];
+ permissions = permissionsList.toArray(permissions);
+ ActivityCompat.requestPermissions(this, permissions, 0);
+ }
+ }
- if (permissionsList.size() > 0) {
- String[] permissions = new String[permissionsList.size()];
- permissions = permissionsList.toArray(permissions);
- ActivityCompat.requestPermissions(this, permissions, 0);
- }
- }
-
- @Override
- public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
- for (int i = 0; i < permissions.length; i++) {
- Log.i("[Permission] " + permissions[i] + " is " + (grantResults[i] == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
- }
- }
+ @Override
+ public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
+ for (int i = 0; i < permissions.length; i++) {
+ Log.i("[Permission] " + permissions[i] + " is " + (grantResults[i] == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
+ }
+ }
}
diff --git a/src/android/org/linphone/call/CallVideoFragment.java b/src/android/org/linphone/call/CallVideoFragment.java
index 6e77652ab..83bbbc6f0 100644
--- a/src/android/org/linphone/call/CallVideoFragment.java
+++ b/src/android/org/linphone/call/CallVideoFragment.java
@@ -19,20 +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 org.linphone.LinphoneManager;
-import org.linphone.LinphonePreferences;
-import org.linphone.LinphoneService;
-import org.linphone.LinphoneUtils;
-import org.linphone.R;
-import org.linphone.compatibility.Compatibility;
-import org.linphone.compatibility.CompatibilityScaleGestureDetector;
-import org.linphone.compatibility.CompatibilityScaleGestureListener;
-import org.linphone.core.Call;
-import org.linphone.core.Core;
-import org.linphone.core.VideoDefinition;
-import org.linphone.mediastream.Log;
-import org.linphone.mediastream.video.AndroidVideoWindowImpl;
-
import android.app.Fragment;
import android.os.Bundle;
import android.util.DisplayMetrics;
@@ -48,346 +34,360 @@ import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
+import org.linphone.LinphoneManager;
+import org.linphone.LinphonePreferences;
+import org.linphone.LinphoneService;
+import org.linphone.LinphoneUtils;
+import org.linphone.R;
+import org.linphone.compatibility.Compatibility;
+import org.linphone.compatibility.CompatibilityScaleGestureDetector;
+import org.linphone.compatibility.CompatibilityScaleGestureListener;
+import org.linphone.core.Call;
+import org.linphone.core.Core;
+import org.linphone.core.VideoDefinition;
+import org.linphone.mediastream.Log;
+import org.linphone.mediastream.video.AndroidVideoWindowImpl;
+
public class CallVideoFragment extends Fragment implements OnGestureListener, OnDoubleTapListener, CompatibilityScaleGestureListener {
- private SurfaceView mVideoView;
- private SurfaceView mCaptureView;
- private AndroidVideoWindowImpl androidVideoWindowImpl;
- private GestureDetector mGestureDetector;
- private float mZoomFactor = 1.f;
- private float mZoomCenterX, mZoomCenterY;
- private CompatibilityScaleGestureDetector mScaleDetector;
- private CallActivity inCallActivity;
- private int previewX, previewY;
+ private SurfaceView mVideoView;
+ private SurfaceView mCaptureView;
+ private AndroidVideoWindowImpl androidVideoWindowImpl;
+ private GestureDetector mGestureDetector;
+ private float mZoomFactor = 1.f;
+ private float mZoomCenterX, mZoomCenterY;
+ private CompatibilityScaleGestureDetector mScaleDetector;
+ private CallActivity inCallActivity;
+ private int previewX, previewY;
- @SuppressWarnings("deprecation") // Warning useless because value is ignored and automatically set by new APIs.
- @Override
+ @SuppressWarnings("deprecation")
+ // Warning useless because value is ignored and automatically set by new APIs.
+ @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- View view;
- if (LinphoneManager.getLc().hasCrappyOpengl()) {
- view = inflater.inflate(R.layout.video_no_opengl, container, false);
- } else {
- view = inflater.inflate(R.layout.video, container, false);
- }
+ Bundle savedInstanceState) {
+ View view;
+ if (LinphoneManager.getLc().hasCrappyOpengl()) {
+ view = inflater.inflate(R.layout.video_no_opengl, container, false);
+ } else {
+ view = inflater.inflate(R.layout.video, container, false);
+ }
- mVideoView = view.findViewById(R.id.videoSurface);
- mCaptureView = view.findViewById(R.id.videoCaptureSurface);
- mCaptureView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); // Warning useless because value is ignored and automatically set by new APIs.
+ mVideoView = view.findViewById(R.id.videoSurface);
+ mCaptureView = view.findViewById(R.id.videoCaptureSurface);
+ mCaptureView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); // Warning useless because value is ignored and automatically set by new APIs.
- fixZOrder(mVideoView, mCaptureView);
+ fixZOrder(mVideoView, mCaptureView);
- androidVideoWindowImpl = new AndroidVideoWindowImpl(mVideoView, mCaptureView, new AndroidVideoWindowImpl.VideoWindowListener() {
- public void onVideoRenderingSurfaceReady(AndroidVideoWindowImpl vw, SurfaceView surface) {
- mVideoView = surface;
- LinphoneManager.getLc().setNativeVideoWindowId(vw);
- }
+ androidVideoWindowImpl = new AndroidVideoWindowImpl(mVideoView, mCaptureView, new AndroidVideoWindowImpl.VideoWindowListener() {
+ public void onVideoRenderingSurfaceReady(AndroidVideoWindowImpl vw, SurfaceView surface) {
+ mVideoView = surface;
+ LinphoneManager.getLc().setNativeVideoWindowId(vw);
+ }
- public void onVideoRenderingSurfaceDestroyed(AndroidVideoWindowImpl vw) {
+ public void onVideoRenderingSurfaceDestroyed(AndroidVideoWindowImpl vw) {
- }
+ }
- public void onVideoPreviewSurfaceReady(AndroidVideoWindowImpl vw, SurfaceView surface) {
- mCaptureView = surface;
- LinphoneManager.getLc().setNativePreviewWindowId(mCaptureView);
- resizePreview();
- }
+ public void onVideoPreviewSurfaceReady(AndroidVideoWindowImpl vw, SurfaceView surface) {
+ mCaptureView = surface;
+ LinphoneManager.getLc().setNativePreviewWindowId(mCaptureView);
+ resizePreview();
+ }
- public void onVideoPreviewSurfaceDestroyed(AndroidVideoWindowImpl vw) {
+ public void onVideoPreviewSurfaceDestroyed(AndroidVideoWindowImpl vw) {
- }
- });
+ }
+ });
- mVideoView.setOnTouchListener(new OnTouchListener() {
- public boolean onTouch(View v, MotionEvent event) {
- if (mScaleDetector != null) {
- mScaleDetector.onTouchEvent(event);
- }
+ mVideoView.setOnTouchListener(new OnTouchListener() {
+ public boolean onTouch(View v, MotionEvent event) {
+ if (mScaleDetector != null) {
+ mScaleDetector.onTouchEvent(event);
+ }
- mGestureDetector.onTouchEvent(event);
- if (inCallActivity != null) {
- inCallActivity.displayVideoCallControlsIfHidden();
- }
- return true;
- }
- });
+ mGestureDetector.onTouchEvent(event);
+ if (inCallActivity != null) {
+ inCallActivity.displayVideoCallControlsIfHidden();
+ }
+ return true;
+ }
+ });
- mCaptureView.setOnTouchListener(new OnTouchListener() {
- @Override
- public boolean onTouch(View view, MotionEvent motionEvent) {
- switch (motionEvent.getAction()) {
- case MotionEvent.ACTION_DOWN:
- previewX = (int) motionEvent.getX();
- previewY = (int) motionEvent.getY();
- break;
- case MotionEvent.ACTION_MOVE:
- int x = (int) motionEvent.getX();
- int y = (int) motionEvent.getY();
- RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams)mCaptureView.getLayoutParams();
- lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 0); // Clears the rule, as there is no removeRule until API 17.
- lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 0);
- int left = lp.leftMargin + (x - previewX);
- int top = lp.topMargin + (y - previewY);
- lp.leftMargin = left;
- lp.topMargin = top;
- view.setLayoutParams(lp);
- break;
- }
- return true;
- }
- });
- return view;
+ mCaptureView.setOnTouchListener(new OnTouchListener() {
+ @Override
+ public boolean onTouch(View view, MotionEvent motionEvent) {
+ switch (motionEvent.getAction()) {
+ case MotionEvent.ACTION_DOWN:
+ previewX = (int) motionEvent.getX();
+ previewY = (int) motionEvent.getY();
+ break;
+ case MotionEvent.ACTION_MOVE:
+ int x = (int) motionEvent.getX();
+ int y = (int) motionEvent.getY();
+ RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mCaptureView.getLayoutParams();
+ lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 0); // Clears the rule, as there is no removeRule until API 17.
+ lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 0);
+ int left = lp.leftMargin + (x - previewX);
+ int top = lp.topMargin + (y - previewY);
+ lp.leftMargin = left;
+ lp.topMargin = top;
+ view.setLayoutParams(lp);
+ break;
+ }
+ return true;
+ }
+ });
+ return view;
}
- @Override
- public void onStart() {
- super.onStart();
- inCallActivity = (CallActivity) getActivity();
- if (inCallActivity != null) {
- inCallActivity.bindVideoFragment(this);
- }
- }
+ @Override
+ public void onStart() {
+ super.onStart();
+ inCallActivity = (CallActivity) getActivity();
+ if (inCallActivity != null) {
+ inCallActivity.bindVideoFragment(this);
+ }
+ }
- private void resizePreview() {
- Core lc = LinphoneManager.getLc();
- if (lc.getCallsNb() > 0) {
- Call call = lc.getCurrentCall();
- if (call == null) {
- call = lc.getCalls()[0];
- }
- if (call == null) return;
+ private void resizePreview() {
+ Core lc = LinphoneManager.getLc();
+ if (lc.getCallsNb() > 0) {
+ Call call = lc.getCurrentCall();
+ if (call == null) {
+ call = lc.getCalls()[0];
+ }
+ if (call == null) return;
- DisplayMetrics metrics = new DisplayMetrics();
- getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
- int screenHeight = metrics.heightPixels;
- int maxHeight = screenHeight / 4; // Let's take at most 1/4 of the screen for the camera preview
+ DisplayMetrics metrics = new DisplayMetrics();
+ getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
+ int screenHeight = metrics.heightPixels;
+ int maxHeight = screenHeight / 4; // Let's take at most 1/4 of the screen for the camera preview
- VideoDefinition videoSize = call.getCurrentParams().getSentVideoDefinition(); // It already takes care of rotation
- if (videoSize.getWidth() == 0 || videoSize.getHeight() == 0) {
- Log.w("Couldn't get sent video definition, using default video definition");
- videoSize = lc.getPreferredVideoDefinition();
- }
- int width = videoSize.getWidth();
- int height = videoSize.getHeight();
+ VideoDefinition videoSize = call.getCurrentParams().getSentVideoDefinition(); // It already takes care of rotation
+ if (videoSize.getWidth() == 0 || videoSize.getHeight() == 0) {
+ Log.w("Couldn't get sent video definition, using default video definition");
+ videoSize = lc.getPreferredVideoDefinition();
+ }
+ int width = videoSize.getWidth();
+ int height = videoSize.getHeight();
- Log.d("Video height is " + height + ", width is " + width);
- width = width * maxHeight / height;
- height = maxHeight;
+ Log.d("Video height is " + height + ", width is " + width);
+ width = width * maxHeight / height;
+ height = maxHeight;
- if (mCaptureView == null) {
- Log.e("mCaptureView is null !");
- return;
- }
- mCaptureView.getHolder().setFixedSize(width, height);
- Log.d("Video preview size set to " + width + "x" + height);
- }
- }
+ if (mCaptureView == null) {
+ Log.e("mCaptureView is null !");
+ return;
+ }
+ mCaptureView.getHolder().setFixedSize(width, height);
+ Log.d("Video preview size set to " + width + "x" + height);
+ }
+ }
- private void fixZOrder(SurfaceView video, SurfaceView preview) {
- video.setZOrderOnTop(false);
- preview.setZOrderOnTop(true);
- preview.setZOrderMediaOverlay(true); // Needed to be able to display control layout over
- }
+ private void fixZOrder(SurfaceView video, SurfaceView preview) {
+ video.setZOrderOnTop(false);
+ preview.setZOrderOnTop(true);
+ preview.setZOrderMediaOverlay(true); // Needed to be able to display control layout over
+ }
- public void switchCamera() {
- try {
- String currentDevice = LinphoneManager.getLc().getVideoDevice();
- String[] devices = LinphoneManager.getLc().getVideoDevicesList();
- int index = 0;
- for (String d : devices) {
- if (d.equals(currentDevice)) {
- break;
- }
- index++;
- }
+ public void switchCamera() {
+ try {
+ String currentDevice = LinphoneManager.getLc().getVideoDevice();
+ String[] devices = LinphoneManager.getLc().getVideoDevicesList();
+ int index = 0;
+ for (String d : devices) {
+ if (d.equals(currentDevice)) {
+ break;
+ }
+ index++;
+ }
- String newDevice;
- if (index == 1)
- newDevice = devices[0];
- else if (devices.length > 1)
- newDevice = devices[1];
- else
- newDevice = devices[index];
- LinphoneManager.getLc().setVideoDevice(newDevice);
+ String newDevice;
+ if (index == 1)
+ newDevice = devices[0];
+ else if (devices.length > 1)
+ newDevice = devices[1];
+ else
+ newDevice = devices[index];
+ LinphoneManager.getLc().setVideoDevice(newDevice);
- CallManager.getInstance().updateCall();
- } catch (ArithmeticException ae) {
- Log.e("Cannot swtich camera : no camera");
- }
- }
+ CallManager.getInstance().updateCall();
+ } catch (ArithmeticException ae) {
+ Log.e("Cannot swtich camera : no camera");
+ }
+ }
- @Override
- public void onResume() {
- super.onResume();
+ @Override
+ public void onResume() {
+ super.onResume();
- if (LinphonePreferences.instance().isOverlayEnabled()) {
- LinphoneService.instance().destroyOverlay();
- }
- if (androidVideoWindowImpl != null) {
- synchronized (androidVideoWindowImpl) {
- LinphoneManager.getLc().setNativeVideoWindowId(androidVideoWindowImpl);
- }
- }
+ if (LinphonePreferences.instance().isOverlayEnabled()) {
+ LinphoneService.instance().destroyOverlay();
+ }
+ if (androidVideoWindowImpl != null) {
+ synchronized (androidVideoWindowImpl) {
+ LinphoneManager.getLc().setNativeVideoWindowId(androidVideoWindowImpl);
+ }
+ }
- mGestureDetector = new GestureDetector(inCallActivity, this);
- mScaleDetector = Compatibility.getScaleGestureDetector(inCallActivity, this);
+ mGestureDetector = new GestureDetector(inCallActivity, this);
+ mScaleDetector = Compatibility.getScaleGestureDetector(inCallActivity, this);
- resizePreview();
- }
+ resizePreview();
+ }
- @Override
- public void onPause() {
- if (androidVideoWindowImpl != null) {
- synchronized (androidVideoWindowImpl) {
- /*
- * this call will destroy native opengl renderer which is used by
- * androidVideoWindowImpl
- */
- LinphoneManager.getLc().setNativeVideoWindowId(null);
- }
- }
- if (LinphonePreferences.instance().isOverlayEnabled()) {
- LinphoneService.instance().createOverlay();
- }
+ @Override
+ public void onPause() {
+ if (androidVideoWindowImpl != null) {
+ synchronized (androidVideoWindowImpl) {
+ /*
+ * this call will destroy native opengl renderer which is used by
+ * androidVideoWindowImpl
+ */
+ LinphoneManager.getLc().setNativeVideoWindowId(null);
+ }
+ }
+ if (LinphonePreferences.instance().isOverlayEnabled()) {
+ LinphoneService.instance().createOverlay();
+ }
- super.onPause();
- }
+ super.onPause();
+ }
public boolean onScale(CompatibilityScaleGestureDetector detector) {
- mZoomFactor *= detector.getScaleFactor();
+ mZoomFactor *= detector.getScaleFactor();
// Don't let the object get too small or too large.
- // Zoom to make the video fill the screen vertically
- float portraitZoomFactor = ((float) mVideoView.getHeight()) / (float) ((3 * mVideoView.getWidth()) / 4);
- // Zoom to make the video fill the screen horizontally
- float landscapeZoomFactor = ((float) mVideoView.getWidth()) / (float) ((3 * mVideoView.getHeight()) / 4);
- mZoomFactor = Math.max(0.1f, Math.min(mZoomFactor, Math.max(portraitZoomFactor, landscapeZoomFactor)));
+ // Zoom to make the video fill the screen vertically
+ float portraitZoomFactor = ((float) mVideoView.getHeight()) / (float) ((3 * mVideoView.getWidth()) / 4);
+ // Zoom to make the video fill the screen horizontally
+ float landscapeZoomFactor = ((float) mVideoView.getWidth()) / (float) ((3 * mVideoView.getHeight()) / 4);
+ mZoomFactor = Math.max(0.1f, Math.min(mZoomFactor, Math.max(portraitZoomFactor, landscapeZoomFactor)));
- Call currentCall = LinphoneManager.getLc().getCurrentCall();
- if (currentCall != null) {
- currentCall.zoom(mZoomFactor, mZoomCenterX, mZoomCenterY);
+ Call currentCall = LinphoneManager.getLc().getCurrentCall();
+ if (currentCall != null) {
+ currentCall.zoom(mZoomFactor, mZoomCenterX, mZoomCenterY);
return true;
- }
+ }
return false;
}
- @Override
- public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
- if (LinphoneUtils.isCallEstablished(LinphoneManager.getLc().getCurrentCall())) {
- if (mZoomFactor > 1) {
- // Video is zoomed, slide is used to change center of zoom
- if (distanceX > 0 && mZoomCenterX < 1) {
- mZoomCenterX += 0.01;
- } else if(distanceX < 0 && mZoomCenterX > 0) {
- mZoomCenterX -= 0.01;
- }
- if (distanceY < 0 && mZoomCenterY < 1) {
- mZoomCenterY += 0.01;
- } else if(distanceY > 0 && mZoomCenterY > 0) {
- mZoomCenterY -= 0.01;
- }
+ @Override
+ public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
+ if (LinphoneUtils.isCallEstablished(LinphoneManager.getLc().getCurrentCall())) {
+ if (mZoomFactor > 1) {
+ // Video is zoomed, slide is used to change center of zoom
+ if (distanceX > 0 && mZoomCenterX < 1) {
+ mZoomCenterX += 0.01;
+ } else if (distanceX < 0 && mZoomCenterX > 0) {
+ mZoomCenterX -= 0.01;
+ }
+ if (distanceY < 0 && mZoomCenterY < 1) {
+ mZoomCenterY += 0.01;
+ } else if (distanceY > 0 && mZoomCenterY > 0) {
+ mZoomCenterY -= 0.01;
+ }
- if (mZoomCenterX > 1)
- mZoomCenterX = 1;
- if (mZoomCenterX < 0)
- mZoomCenterX = 0;
- if (mZoomCenterY > 1)
- mZoomCenterY = 1;
- if (mZoomCenterY < 0)
- mZoomCenterY = 0;
+ if (mZoomCenterX > 1)
+ mZoomCenterX = 1;
+ if (mZoomCenterX < 0)
+ mZoomCenterX = 0;
+ if (mZoomCenterY > 1)
+ mZoomCenterY = 1;
+ if (mZoomCenterY < 0)
+ mZoomCenterY = 0;
- LinphoneManager.getLc().getCurrentCall().zoom(mZoomFactor, mZoomCenterX, mZoomCenterY);
- return true;
- }
- }
+ LinphoneManager.getLc().getCurrentCall().zoom(mZoomFactor, mZoomCenterX, mZoomCenterY);
+ return true;
+ }
+ }
- return false;
- }
+ return false;
+ }
- @Override
- public boolean onDoubleTap(MotionEvent e) {
- if (LinphoneUtils.isCallEstablished(LinphoneManager.getLc().getCurrentCall())) {
- if (mZoomFactor == 1.f) {
- // Zoom to make the video fill the screen vertically
- float portraitZoomFactor = ((float) mVideoView.getHeight()) / (float) ((3 * mVideoView.getWidth()) / 4);
- // Zoom to make the video fill the screen horizontally
- float landscapeZoomFactor = ((float) mVideoView.getWidth()) / (float) ((3 * mVideoView.getHeight()) / 4);
+ @Override
+ public boolean onDoubleTap(MotionEvent e) {
+ if (LinphoneUtils.isCallEstablished(LinphoneManager.getLc().getCurrentCall())) {
+ if (mZoomFactor == 1.f) {
+ // Zoom to make the video fill the screen vertically
+ float portraitZoomFactor = ((float) mVideoView.getHeight()) / (float) ((3 * mVideoView.getWidth()) / 4);
+ // Zoom to make the video fill the screen horizontally
+ float landscapeZoomFactor = ((float) mVideoView.getWidth()) / (float) ((3 * mVideoView.getHeight()) / 4);
- mZoomFactor = Math.max(portraitZoomFactor, landscapeZoomFactor);
- }
- else {
- resetZoom();
- }
+ mZoomFactor = Math.max(portraitZoomFactor, landscapeZoomFactor);
+ } else {
+ resetZoom();
+ }
- LinphoneManager.getLc().getCurrentCall().zoom(mZoomFactor, mZoomCenterX, mZoomCenterY);
- return true;
- }
+ LinphoneManager.getLc().getCurrentCall().zoom(mZoomFactor, mZoomCenterX, mZoomCenterY);
+ return true;
+ }
- return false;
- }
+ return false;
+ }
- private void resetZoom() {
- mZoomFactor = 1.f;
- mZoomCenterX = mZoomCenterY = 0.5f;
- }
+ private void resetZoom() {
+ mZoomFactor = 1.f;
+ mZoomCenterX = mZoomCenterY = 0.5f;
+ }
- @Override
- public void onDestroy() {
- inCallActivity = null;
+ @Override
+ public void onDestroy() {
+ inCallActivity = null;
- mCaptureView = null;
- if (mVideoView != null) {
- mVideoView.setOnTouchListener(null);
- mVideoView = null;
- }
- if (androidVideoWindowImpl != null) {
- // Prevent linphone from crashing if correspondent hang up while you are rotating
- androidVideoWindowImpl.release();
- androidVideoWindowImpl = null;
- }
- if (mGestureDetector != null) {
- mGestureDetector.setOnDoubleTapListener(null);
- mGestureDetector = null;
- }
- if (mScaleDetector != null) {
- mScaleDetector.destroy();
- mScaleDetector = null;
- }
+ mCaptureView = null;
+ if (mVideoView != null) {
+ mVideoView.setOnTouchListener(null);
+ mVideoView = null;
+ }
+ if (androidVideoWindowImpl != null) {
+ // Prevent linphone from crashing if correspondent hang up while you are rotating
+ androidVideoWindowImpl.release();
+ androidVideoWindowImpl = null;
+ }
+ if (mGestureDetector != null) {
+ mGestureDetector.setOnDoubleTapListener(null);
+ mGestureDetector = null;
+ }
+ if (mScaleDetector != null) {
+ mScaleDetector.destroy();
+ mScaleDetector = null;
+ }
- super.onDestroy();
- }
+ super.onDestroy();
+ }
- @Override
- public boolean onDown(MotionEvent e) {
- return true; // Needed to make the GestureDetector working
- }
+ @Override
+ public boolean onDown(MotionEvent e) {
+ return true; // Needed to make the GestureDetector working
+ }
- @Override
- public boolean onDoubleTapEvent(MotionEvent e) {
- return false;
- }
+ @Override
+ public boolean onDoubleTapEvent(MotionEvent e) {
+ return false;
+ }
- @Override
- public boolean onSingleTapConfirmed(MotionEvent e) {
- return false;
- }
+ @Override
+ public boolean onSingleTapConfirmed(MotionEvent e) {
+ return false;
+ }
- @Override
- public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
- float velocityY) {
- return false;
- }
+ @Override
+ public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
+ float velocityY) {
+ return false;
+ }
- @Override
- public void onLongPress(MotionEvent e) {
+ @Override
+ public void onLongPress(MotionEvent e) {
- }
+ }
- @Override
- public void onShowPress(MotionEvent e) {
+ @Override
+ public void onShowPress(MotionEvent e) {
- }
+ }
- @Override
- public boolean onSingleTapUp(MotionEvent e) {
- return false;
- }
+ @Override
+ public boolean onSingleTapUp(MotionEvent e) {
+ return false;
+ }
}
diff --git a/src/android/org/linphone/chat/ChatBubbleViewHolder.java b/src/android/org/linphone/chat/ChatBubbleViewHolder.java
index 8ff2e27bb..bec7155b2 100644
--- a/src/android/org/linphone/chat/ChatBubbleViewHolder.java
+++ b/src/android/org/linphone/chat/ChatBubbleViewHolder.java
@@ -33,115 +33,117 @@ import android.widget.TextView;
import org.linphone.R;
import org.linphone.core.ChatMessage;
-public class ChatBubbleViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
- public String messageId;
- public Context mContext;
+public class ChatBubbleViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
+ public String messageId;
+ public Context mContext;
public ChatMessage message;
- public LinearLayout eventLayout;
- public TextView eventMessage;
+ public LinearLayout eventLayout;
+ public TextView eventMessage;
- public RelativeLayout bubbleLayout;
- public LinearLayout separatorLayout;
- public LinearLayout background;
- public ImageView contactPicture;
- public ImageView contactPictureMask;
- public TextView contactName;
+ public RelativeLayout bubbleLayout;
+ public LinearLayout separatorLayout;
+ public LinearLayout background;
+ public ImageView contactPicture;
+ public ImageView contactPictureMask;
+ public TextView contactName;
- public ImageView messageStatus;
- public ProgressBar messageSendingInProgress;
- public LinearLayout imdmLayout;
- public ImageView imdmIcon;
- public TextView imdmLabel;
+ public ImageView messageStatus;
+ public ProgressBar messageSendingInProgress;
+ public LinearLayout imdmLayout;
+ public ImageView imdmIcon;
+ public TextView imdmLabel;
- public TextView messageText;
- public ImageView messageImage;
+ public TextView messageText;
+ public ImageView messageImage;
- public RelativeLayout fileTransferLayout;
- public ProgressBar fileTransferProgressBar;
- public Button fileTransferAction;
+ public RelativeLayout fileTransferLayout;
+ public ProgressBar fileTransferProgressBar;
+ public Button fileTransferAction;
- public TextView fileName;
- public Button openFileButton;
+ public TextView fileName;
+ public Button openFileButton;
- public CheckBox delete;
- private ClickListener mListener;
+ public CheckBox delete;
+ private ClickListener mListener;
- public ChatBubbleViewHolder(Context context, View view, ClickListener listener) {
- super(view);
- mContext = context;
+ public ChatBubbleViewHolder(Context context, View view, ClickListener listener) {
+ super(view);
+ mContext = context;
- eventLayout = view.findViewById(R.id.event);
- //eventTime = view.findViewById(R.id.event_date);
- eventMessage = view.findViewById(R.id.event_text);
+ eventLayout = view.findViewById(R.id.event);
+ //eventTime = view.findViewById(R.id.event_date);
+ eventMessage = view.findViewById(R.id.event_text);
- bubbleLayout = view.findViewById(R.id.bubble);
- background = view.findViewById(R.id.background);
- contactPicture = view.findViewById(R.id.contact_picture);
- contactPictureMask = view.findViewById(R.id.mask);
- contactName = view.findViewById(R.id.contact_header);
+ bubbleLayout = view.findViewById(R.id.bubble);
+ background = view.findViewById(R.id.background);
+ contactPicture = view.findViewById(R.id.contact_picture);
+ contactPictureMask = view.findViewById(R.id.mask);
+ contactName = view.findViewById(R.id.contact_header);
- messageStatus = view.findViewById(R.id.status);
- messageSendingInProgress = view.findViewById(R.id.inprogress);
- imdmLayout = view.findViewById(R.id.imdmLayout);
- imdmIcon = view.findViewById(R.id.imdmIcon);
- imdmLabel = view.findViewById(R.id.imdmText);
+ messageStatus = view.findViewById(R.id.status);
+ messageSendingInProgress = view.findViewById(R.id.inprogress);
+ imdmLayout = view.findViewById(R.id.imdmLayout);
+ imdmIcon = view.findViewById(R.id.imdmIcon);
+ imdmLabel = view.findViewById(R.id.imdmText);
- messageText = view.findViewById(R.id.message);
- messageImage = view.findViewById(R.id.image);
- separatorLayout = view.findViewById(R.id.separator);
+ messageText = view.findViewById(R.id.message);
+ messageImage = view.findViewById(R.id.image);
+ separatorLayout = view.findViewById(R.id.separator);
- fileTransferLayout = view.findViewById(R.id.file_transfer_layout);
- fileTransferProgressBar = view.findViewById(R.id.progress_bar);
- fileTransferAction = view.findViewById(R.id.file_transfer_action);
+ fileTransferLayout = view.findViewById(R.id.file_transfer_layout);
+ fileTransferProgressBar = view.findViewById(R.id.progress_bar);
+ fileTransferAction = view.findViewById(R.id.file_transfer_action);
- fileName = view.findViewById(R.id.file_name);
- openFileButton = view.findViewById(R.id.open_file);
+ fileName = view.findViewById(R.id.file_name);
+ openFileButton = view.findViewById(R.id.open_file);
- delete = view.findViewById(R.id.delete_message);
+ delete = view.findViewById(R.id.delete_message);
- mListener = listener;
+ mListener = listener;
- view.setOnClickListener(this);
- }
- public ChatBubbleViewHolder(View view) {
- super(view);
- eventLayout = view.findViewById(R.id.event);
- //eventTime = view.findViewById(R.id.event_date);
- eventMessage = view.findViewById(R.id.event_text);
+ view.setOnClickListener(this);
+ }
- bubbleLayout = view.findViewById(R.id.bubble);
- background = view.findViewById(R.id.background);
- contactPicture = view.findViewById(R.id.contact_picture);
- contactPictureMask = view.findViewById(R.id.mask);
- contactName = view.findViewById(R.id.contact_header);
+ public ChatBubbleViewHolder(View view) {
+ super(view);
+ eventLayout = view.findViewById(R.id.event);
+ //eventTime = view.findViewById(R.id.event_date);
+ eventMessage = view.findViewById(R.id.event_text);
- messageStatus = view.findViewById(R.id.status);
- messageSendingInProgress = view.findViewById(R.id.inprogress);
- imdmLayout = view.findViewById(R.id.imdmLayout);
- imdmIcon = view.findViewById(R.id.imdmIcon);
- imdmLabel = view.findViewById(R.id.imdmText);
+ bubbleLayout = view.findViewById(R.id.bubble);
+ background = view.findViewById(R.id.background);
+ contactPicture = view.findViewById(R.id.contact_picture);
+ contactPictureMask = view.findViewById(R.id.mask);
+ contactName = view.findViewById(R.id.contact_header);
- messageText = view.findViewById(R.id.message);
- messageImage = view.findViewById(R.id.image);
- separatorLayout = view.findViewById(R.id.separator);
+ messageStatus = view.findViewById(R.id.status);
+ messageSendingInProgress = view.findViewById(R.id.inprogress);
+ imdmLayout = view.findViewById(R.id.imdmLayout);
+ imdmIcon = view.findViewById(R.id.imdmIcon);
+ imdmLabel = view.findViewById(R.id.imdmText);
- fileTransferLayout = view.findViewById(R.id.file_transfer_layout);
- fileTransferProgressBar = view.findViewById(R.id.progress_bar);
- fileTransferAction = view.findViewById(R.id.file_transfer_action);
+ messageText = view.findViewById(R.id.message);
+ messageImage = view.findViewById(R.id.image);
+ separatorLayout = view.findViewById(R.id.separator);
- fileName = view.findViewById(R.id.file_name);
- openFileButton = view.findViewById(R.id.open_file);
+ fileTransferLayout = view.findViewById(R.id.file_transfer_layout);
+ fileTransferProgressBar = view.findViewById(R.id.progress_bar);
+ fileTransferAction = view.findViewById(R.id.file_transfer_action);
- delete = view.findViewById(R.id.delete_message);
- }
- @Override
- public void onClick(View v) {
- if (mListener != null) {
- mListener.onItemClicked(getAdapterPosition());
- }
- }
+ fileName = view.findViewById(R.id.file_name);
+ openFileButton = view.findViewById(R.id.open_file);
- public interface ClickListener {
- void onItemClicked(int position);
- }
+ delete = view.findViewById(R.id.delete_message);
+ }
+
+ @Override
+ public void onClick(View v) {
+ if (mListener != null) {
+ mListener.onItemClicked(getAdapterPosition());
+ }
+ }
+
+ public interface ClickListener {
+ void onItemClicked(int position);
+ }
}
\ No newline at end of file
diff --git a/src/android/org/linphone/chat/ChatCreationFragment.java b/src/android/org/linphone/chat/ChatCreationFragment.java
index 90751c593..76e082a6c 100644
--- a/src/android/org/linphone/chat/ChatCreationFragment.java
+++ b/src/android/org/linphone/chat/ChatCreationFragment.java
@@ -59,380 +59,380 @@ import java.util.List;
import static android.content.Context.INPUT_METHOD_SERVICE;
-public class ChatCreationFragment extends Fragment implements View.OnClickListener ,SearchContactsListAdapter.ViewHolder.ClickListener, ContactsUpdatedListener {
- private RecyclerView mContactsList;
- private LinearLayout mContactsSelectedLayout;
- private HorizontalScrollView mContactsSelectLayout;
- private ArrayList mContactsSelected;
- private ImageView mAllContactsButton, mLinphoneContactsButton, mClearSearchFieldButton, mBackButton, mNextButton;
- private boolean mOnlyDisplayLinphoneContacts;
- private View mAllContactsSelected, mLinphoneContactsSelected;
- private RelativeLayout mSearchLayout, mWaitLayout;
- private EditText mSearchField;
- private ProgressBar mContactsFetchInProgress;
- private SearchContactsListAdapter mSearchAdapter;
- private String mChatRoomSubject, mChatRoomAddress;
- private ChatRoom mChatRoom;
- private ChatRoomListenerStub mChatRoomCreationListener;
- private Bundle mShareInfos;
+public class ChatCreationFragment extends Fragment implements View.OnClickListener, SearchContactsListAdapter.ViewHolder.ClickListener, ContactsUpdatedListener {
+ private RecyclerView mContactsList;
+ private LinearLayout mContactsSelectedLayout;
+ private HorizontalScrollView mContactsSelectLayout;
+ private ArrayList mContactsSelected;
+ private ImageView mAllContactsButton, mLinphoneContactsButton, mClearSearchFieldButton, mBackButton, mNextButton;
+ private boolean mOnlyDisplayLinphoneContacts;
+ private View mAllContactsSelected, mLinphoneContactsSelected;
+ private RelativeLayout mSearchLayout, mWaitLayout;
+ private EditText mSearchField;
+ private ProgressBar mContactsFetchInProgress;
+ private SearchContactsListAdapter mSearchAdapter;
+ private String mChatRoomSubject, mChatRoomAddress;
+ private ChatRoom mChatRoom;
+ private ChatRoomListenerStub mChatRoomCreationListener;
+ private Bundle mShareInfos;
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- View view = inflater.inflate(R.layout.chat_create, container, false);
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ View view = inflater.inflate(R.layout.chat_create, container, false);
- mContactsSelected = new ArrayList<>();
- mChatRoomSubject = null;
- mChatRoomAddress = null;
- if (getArguments() != null) {
- if (getArguments().getSerializable("selectedContacts") != null) {
- mContactsSelected = (ArrayList) getArguments().getSerializable("selectedContacts");
- }
- mChatRoomSubject = getArguments().getString("subject");
- mChatRoomAddress = getArguments().getString("groupChatRoomAddress");
- }
+ mContactsSelected = new ArrayList<>();
+ mChatRoomSubject = null;
+ mChatRoomAddress = null;
+ if (getArguments() != null) {
+ if (getArguments().getSerializable("selectedContacts") != null) {
+ mContactsSelected = (ArrayList) getArguments().getSerializable("selectedContacts");
+ }
+ mChatRoomSubject = getArguments().getString("subject");
+ mChatRoomAddress = getArguments().getString("groupChatRoomAddress");
+ }
- mWaitLayout = view.findViewById(R.id.waitScreen);
- mWaitLayout.setVisibility(View.GONE);
+ mWaitLayout = view.findViewById(R.id.waitScreen);
+ mWaitLayout.setVisibility(View.GONE);
- mContactsList = view.findViewById(R.id.contactsList);
- mContactsSelectedLayout = view.findViewById(R.id.contactsSelected);
- mContactsSelectLayout = view.findViewById(R.id.layoutContactsSelected);
+ mContactsList = view.findViewById(R.id.contactsList);
+ mContactsSelectedLayout = view.findViewById(R.id.contactsSelected);
+ mContactsSelectLayout = view.findViewById(R.id.layoutContactsSelected);
- mAllContactsButton = view.findViewById(R.id.all_contacts);
- mAllContactsButton.setOnClickListener(this);
+ mAllContactsButton = view.findViewById(R.id.all_contacts);
+ mAllContactsButton.setOnClickListener(this);
- mLinphoneContactsButton = view.findViewById(R.id.linphone_contacts);
- mLinphoneContactsButton.setOnClickListener(this);
+ mLinphoneContactsButton = view.findViewById(R.id.linphone_contacts);
+ mLinphoneContactsButton.setOnClickListener(this);
- mAllContactsSelected = view.findViewById(R.id.all_contacts_select);
- mLinphoneContactsSelected = view.findViewById(R.id.linphone_contacts_select);
+ mAllContactsSelected = view.findViewById(R.id.all_contacts_select);
+ mLinphoneContactsSelected = view.findViewById(R.id.linphone_contacts_select);
- mBackButton = view.findViewById(R.id.back);
- mBackButton.setOnClickListener(this);
+ mBackButton = view.findViewById(R.id.back);
+ mBackButton.setOnClickListener(this);
- mNextButton = view.findViewById(R.id.next);
- mNextButton.setOnClickListener(this);
- mNextButton.setEnabled(false);
- mSearchLayout = view.findViewById(R.id.layoutSearchField);
+ mNextButton = view.findViewById(R.id.next);
+ mNextButton.setOnClickListener(this);
+ mNextButton.setEnabled(false);
+ mSearchLayout = view.findViewById(R.id.layoutSearchField);
- mClearSearchFieldButton = view.findViewById(R.id.clearSearchField);
- mClearSearchFieldButton.setOnClickListener(this);
+ mClearSearchFieldButton = view.findViewById(R.id.clearSearchField);
+ mClearSearchFieldButton.setOnClickListener(this);
- mContactsFetchInProgress = view.findViewById(R.id.contactsFetchInProgress);
- mContactsFetchInProgress.setVisibility(View.VISIBLE);
+ mContactsFetchInProgress = view.findViewById(R.id.contactsFetchInProgress);
+ mContactsFetchInProgress.setVisibility(View.VISIBLE);
- mSearchAdapter = new SearchContactsListAdapter(null, mContactsFetchInProgress, this);
+ mSearchAdapter = new SearchContactsListAdapter(null, mContactsFetchInProgress, this);
- mSearchField = view.findViewById(R.id.searchField);
- mSearchField.addTextChangedListener(new TextWatcher() {
- @Override
- public void onTextChanged(CharSequence s, int start, int before, int count) {
- if (before > count) {
- ContactsManager.getInstance().getMagicSearch().resetSearchCache();
- }
- }
+ mSearchField = view.findViewById(R.id.searchField);
+ mSearchField.addTextChangedListener(new TextWatcher() {
+ @Override
+ public void onTextChanged(CharSequence s, int start, int before, int count) {
+ if (before > count) {
+ ContactsManager.getInstance().getMagicSearch().resetSearchCache();
+ }
+ }
- @Override
- public void beforeTextChanged(CharSequence s, int start, int count, int after) {
+ @Override
+ public void beforeTextChanged(CharSequence s, int start, int count, int after) {
- }
+ }
- @Override
- public void afterTextChanged(Editable s) {
- mSearchAdapter.searchContacts(mSearchField.getText().toString(), mContactsList);
- }
- });
+ @Override
+ public void afterTextChanged(Editable s) {
+ mSearchAdapter.searchContacts(mSearchField.getText().toString(), mContactsList);
+ }
+ });
- LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
+ LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
- mContactsList.setAdapter(mSearchAdapter);
+ mContactsList.setAdapter(mSearchAdapter);
- DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(mContactsList.getContext(),
- layoutManager.getOrientation());
- dividerItemDecoration.setDrawable(getActivity().getApplicationContext().getResources().getDrawable(R.drawable.divider));
- mContactsList.addItemDecoration(dividerItemDecoration);
+ DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(mContactsList.getContext(),
+ layoutManager.getOrientation());
+ dividerItemDecoration.setDrawable(getActivity().getApplicationContext().getResources().getDrawable(R.drawable.divider));
+ mContactsList.addItemDecoration(dividerItemDecoration);
- mContactsList.setLayoutManager(layoutManager);
+ mContactsList.setLayoutManager(layoutManager);
- if (savedInstanceState != null && savedInstanceState.getStringArrayList("mContactsSelected") != null) {
- mContactsSelectedLayout.removeAllViews();
- // We need to get all contacts not only sip
- for (String uri : savedInstanceState.getStringArrayList("mContactsSelected")) {
- for (ContactAddress ca : mSearchAdapter.getContactsList()) {
- if (ca.getAddressAsDisplayableString().compareTo(uri) == 0) {
- ca.setView(null);
- addSelectedContactAddress(ca);
- break;
- }
- }
- }
- updateList();
- updateListSelected();
- }
+ if (savedInstanceState != null && savedInstanceState.getStringArrayList("mContactsSelected") != null) {
+ mContactsSelectedLayout.removeAllViews();
+ // We need to get all contacts not only sip
+ for (String uri : savedInstanceState.getStringArrayList("mContactsSelected")) {
+ for (ContactAddress ca : mSearchAdapter.getContactsList()) {
+ if (ca.getAddressAsDisplayableString().compareTo(uri) == 0) {
+ ca.setView(null);
+ addSelectedContactAddress(ca);
+ break;
+ }
+ }
+ }
+ updateList();
+ updateListSelected();
+ }
- mOnlyDisplayLinphoneContacts = ContactsManager.getInstance().getSIPContacts().size() > 0 ? true : false;
- if (savedInstanceState != null ) {
- mOnlyDisplayLinphoneContacts = savedInstanceState.getBoolean("onlySipContact", true);
- }
- mSearchAdapter.setOnlySipContact(mOnlyDisplayLinphoneContacts);
- updateList();
+ mOnlyDisplayLinphoneContacts = ContactsManager.getInstance().getSIPContacts().size() > 0 ? true : false;
+ if (savedInstanceState != null) {
+ mOnlyDisplayLinphoneContacts = savedInstanceState.getBoolean("onlySipContact", true);
+ }
+ mSearchAdapter.setOnlySipContact(mOnlyDisplayLinphoneContacts);
+ updateList();
- displayChatCreation();
+ displayChatCreation();
- mChatRoomCreationListener = new ChatRoomListenerStub() {
- @Override
- public void onStateChanged(ChatRoom cr, ChatRoom.State newState) {
- if (newState == ChatRoom.State.Created) {
- mWaitLayout.setVisibility(View.GONE);
- LinphoneActivity.instance().goToChat(cr.getPeerAddress().asStringUriOnly(), mShareInfos);
- } else if (newState == ChatRoom.State.CreationFailed) {
- mWaitLayout.setVisibility(View.GONE);
- LinphoneActivity.instance().displayChatRoomError();
- Log.e("Group chat room for address " + cr.getPeerAddress() + " has failed !");
- }
- }
- };
+ mChatRoomCreationListener = new ChatRoomListenerStub() {
+ @Override
+ public void onStateChanged(ChatRoom cr, ChatRoom.State newState) {
+ if (newState == ChatRoom.State.Created) {
+ mWaitLayout.setVisibility(View.GONE);
+ LinphoneActivity.instance().goToChat(cr.getPeerAddress().asStringUriOnly(), mShareInfos);
+ } else if (newState == ChatRoom.State.CreationFailed) {
+ mWaitLayout.setVisibility(View.GONE);
+ LinphoneActivity.instance().displayChatRoomError();
+ Log.e("Group chat room for address " + cr.getPeerAddress() + " has failed !");
+ }
+ }
+ };
- if (getArguments() != null) {
- String fileSharedUri = getArguments().getString("fileSharedUri");
- String messageDraft = getArguments().getString("messageDraft");
+ if (getArguments() != null) {
+ String fileSharedUri = getArguments().getString("fileSharedUri");
+ String messageDraft = getArguments().getString("messageDraft");
- if (fileSharedUri != null || messageDraft != null)
- mShareInfos = new Bundle();
+ if (fileSharedUri != null || messageDraft != null)
+ mShareInfos = new Bundle();
- if (fileSharedUri != null) {
- LinphoneActivity.instance().checkAndRequestPermissionsToSendImage();
- mShareInfos.putString("fileSharedUri", fileSharedUri);
- }
+ if (fileSharedUri != null) {
+ LinphoneActivity.instance().checkAndRequestPermissionsToSendImage();
+ mShareInfos.putString("fileSharedUri", fileSharedUri);
+ }
- if (messageDraft != null)
- mShareInfos.putString("messageDraft", messageDraft);
- }
+ if (messageDraft != null)
+ mShareInfos.putString("messageDraft", messageDraft);
+ }
- return view;
- }
+ return view;
+ }
- @Override
- public void onResume() {
- ContactsManager.addContactsListener(this);
- super.onResume();
+ @Override
+ public void onResume() {
+ ContactsManager.addContactsListener(this);
+ super.onResume();
- InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(INPUT_METHOD_SERVICE);
- if (getActivity().getCurrentFocus() != null) {
- inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
- }
- }
+ InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(INPUT_METHOD_SERVICE);
+ if (getActivity().getCurrentFocus() != null) {
+ inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
+ }
+ }
- @Override
- public void onPause() {
- if (mChatRoom != null) {
- mChatRoom.removeListener(mChatRoomCreationListener);
- }
- ContactsManager.removeContactsListener(this);
- super.onPause();
- }
+ @Override
+ public void onPause() {
+ if (mChatRoom != null) {
+ mChatRoom.removeListener(mChatRoomCreationListener);
+ }
+ ContactsManager.removeContactsListener(this);
+ super.onPause();
+ }
- private void displayChatCreation() {
- mNextButton.setVisibility(View.VISIBLE);
- mNextButton.setEnabled(mContactsSelected.size() > 0);
+ private void displayChatCreation() {
+ mNextButton.setVisibility(View.VISIBLE);
+ mNextButton.setEnabled(mContactsSelected.size() > 0);
- mContactsList.setVisibility(View.VISIBLE);
- mSearchLayout.setVisibility(View.VISIBLE);
- mAllContactsButton.setVisibility(View.VISIBLE);
- mLinphoneContactsButton.setVisibility(View.VISIBLE);
- if (mOnlyDisplayLinphoneContacts) {
- mAllContactsSelected.setVisibility(View.INVISIBLE);
- mLinphoneContactsSelected.setVisibility(View.VISIBLE);
- } else {
- mAllContactsSelected.setVisibility(View.VISIBLE);
- mLinphoneContactsSelected.setVisibility(View.INVISIBLE);
- }
+ mContactsList.setVisibility(View.VISIBLE);
+ mSearchLayout.setVisibility(View.VISIBLE);
+ mAllContactsButton.setVisibility(View.VISIBLE);
+ mLinphoneContactsButton.setVisibility(View.VISIBLE);
+ if (mOnlyDisplayLinphoneContacts) {
+ mAllContactsSelected.setVisibility(View.INVISIBLE);
+ mLinphoneContactsSelected.setVisibility(View.VISIBLE);
+ } else {
+ mAllContactsSelected.setVisibility(View.VISIBLE);
+ mLinphoneContactsSelected.setVisibility(View.INVISIBLE);
+ }
- mAllContactsButton.setEnabled(mOnlyDisplayLinphoneContacts);
- mLinphoneContactsButton.setEnabled(!mAllContactsButton.isEnabled());
+ mAllContactsButton.setEnabled(mOnlyDisplayLinphoneContacts);
+ mLinphoneContactsButton.setEnabled(!mAllContactsButton.isEnabled());
- mContactsSelectedLayout.removeAllViews();
- if (mContactsSelected.size() > 0) {
- mSearchAdapter.setContactsSelectedList(mContactsSelected);
- for (ContactAddress ca : mContactsSelected) {
- addSelectedContactAddress(ca);
- }
- }
- }
+ mContactsSelectedLayout.removeAllViews();
+ if (mContactsSelected.size() > 0) {
+ mSearchAdapter.setContactsSelectedList(mContactsSelected);
+ for (ContactAddress ca : mContactsSelected) {
+ addSelectedContactAddress(ca);
+ }
+ }
+ }
- private void updateList() {
- mSearchAdapter.searchContacts(mSearchField.getText().toString(), mContactsList);
- mSearchAdapter.notifyDataSetChanged();
- }
+ private void updateList() {
+ mSearchAdapter.searchContacts(mSearchField.getText().toString(), mContactsList);
+ mSearchAdapter.notifyDataSetChanged();
+ }
- private void updateListSelected() {
- if (mContactsSelected.size() > 0) {
- mContactsSelectLayout.invalidate();
- mNextButton.setEnabled(true);
- } else {
- mNextButton.setEnabled(false);
- }
- }
+ private void updateListSelected() {
+ if (mContactsSelected.size() > 0) {
+ mContactsSelectLayout.invalidate();
+ mNextButton.setEnabled(true);
+ } else {
+ mNextButton.setEnabled(false);
+ }
+ }
- private int getIndexOfCa(ContactAddress ca, List caList) {
- for (int i = 0 ; i < caList.size() ; i++) {
- if (ca.getAddress() != null && ca.getAddress().getUsername() != null) {
- if (caList.get(i).getAddressAsDisplayableString().compareTo(ca.getAddressAsDisplayableString()) == 0)
- return i;
- } else if (ca.getPhoneNumber() != null && caList.get(i).getPhoneNumber() !=null) {
- if (ca.getPhoneNumber().compareTo(caList.get(i).getPhoneNumber()) == 0)
- return i;
- }
- }
- return -1;
- }
+ private int getIndexOfCa(ContactAddress ca, List caList) {
+ for (int i = 0; i < caList.size(); i++) {
+ if (ca.getAddress() != null && ca.getAddress().getUsername() != null) {
+ if (caList.get(i).getAddressAsDisplayableString().compareTo(ca.getAddressAsDisplayableString()) == 0)
+ return i;
+ } else if (ca.getPhoneNumber() != null && caList.get(i).getPhoneNumber() != null) {
+ if (ca.getPhoneNumber().compareTo(caList.get(i).getPhoneNumber()) == 0)
+ return i;
+ }
+ }
+ return -1;
+ }
- private void resetAndResearch() {
- ContactsManager.getInstance().getMagicSearch().resetSearchCache();
- mSearchAdapter.searchContacts(mSearchField.getText().toString(), mContactsList);
- }
+ private void resetAndResearch() {
+ ContactsManager.getInstance().getMagicSearch().resetSearchCache();
+ mSearchAdapter.searchContacts(mSearchField.getText().toString(), mContactsList);
+ }
- private void addSelectedContactAddress(ContactAddress ca) {
- View viewContact = LayoutInflater.from(LinphoneActivity.instance()).inflate(R.layout.contact_selected, null);
- if (ca.getContact() != null) {
- String name = (ca.getContact().getFullName() != null && !ca.getContact().getFullName().isEmpty()) ?
- ca.getContact().getFullName() : (ca.getDisplayName() != null) ?
- ca.getDisplayName() : (ca.getUsername() != null) ?
- ca.getUsername() : "";
- ((TextView) viewContact.findViewById(R.id.sipUri)).setText(name);
- } else {
- ((TextView) viewContact.findViewById(R.id.sipUri)).setText(ca.getAddressAsDisplayableString());
- }
- View removeContact = viewContact.findViewById(R.id.contactChatDelete);
- removeContact.setTag(ca);
- removeContact.setOnClickListener(this);
- viewContact.setOnClickListener(this);
- ca.setView(viewContact);
- mContactsSelectedLayout.addView(viewContact);
- mContactsSelectedLayout.invalidate();
- }
+ private void addSelectedContactAddress(ContactAddress ca) {
+ View viewContact = LayoutInflater.from(LinphoneActivity.instance()).inflate(R.layout.contact_selected, null);
+ if (ca.getContact() != null) {
+ String name = (ca.getContact().getFullName() != null && !ca.getContact().getFullName().isEmpty()) ?
+ ca.getContact().getFullName() : (ca.getDisplayName() != null) ?
+ ca.getDisplayName() : (ca.getUsername() != null) ?
+ ca.getUsername() : "";
+ ((TextView) viewContact.findViewById(R.id.sipUri)).setText(name);
+ } else {
+ ((TextView) viewContact.findViewById(R.id.sipUri)).setText(ca.getAddressAsDisplayableString());
+ }
+ View removeContact = viewContact.findViewById(R.id.contactChatDelete);
+ removeContact.setTag(ca);
+ removeContact.setOnClickListener(this);
+ viewContact.setOnClickListener(this);
+ ca.setView(viewContact);
+ mContactsSelectedLayout.addView(viewContact);
+ mContactsSelectedLayout.invalidate();
+ }
- private void updateContactsClick(ContactAddress ca, List caSelectedList) {
- ca.setSelect((getIndexOfCa(ca, caSelectedList) == -1));
- if (ca.isSelect()) {
- ContactSelectView csv = new ContactSelectView(LinphoneActivity.instance());
- csv.setListener(this);
- csv.setContactName(ca);
- mContactsSelected.add(ca);
- addSelectedContactAddress(ca);
- } else {
- mContactsSelected.remove(getIndexOfCa(ca, mContactsSelected));
- mContactsSelectedLayout.removeAllViews();
- for (ContactAddress contactAddress : mContactsSelected) {
- if (contactAddress.getView() != null)
- mContactsSelectedLayout.addView(contactAddress.getView());
- }
- }
- mSearchAdapter.setContactsSelectedList(mContactsSelected);
- mContactsSelectedLayout.invalidate();
+ private void updateContactsClick(ContactAddress ca, List caSelectedList) {
+ ca.setSelect((getIndexOfCa(ca, caSelectedList) == -1));
+ if (ca.isSelect()) {
+ ContactSelectView csv = new ContactSelectView(LinphoneActivity.instance());
+ csv.setListener(this);
+ csv.setContactName(ca);
+ mContactsSelected.add(ca);
+ addSelectedContactAddress(ca);
+ } else {
+ mContactsSelected.remove(getIndexOfCa(ca, mContactsSelected));
+ mContactsSelectedLayout.removeAllViews();
+ for (ContactAddress contactAddress : mContactsSelected) {
+ if (contactAddress.getView() != null)
+ mContactsSelectedLayout.addView(contactAddress.getView());
+ }
+ }
+ mSearchAdapter.setContactsSelectedList(mContactsSelected);
+ mContactsSelectedLayout.invalidate();
- }
+ }
- private void removeContactFromSelection(ContactAddress ca) {
- updateContactsClick(ca, mSearchAdapter.getContactsSelectedList());
- mSearchAdapter.notifyDataSetChanged();
- updateListSelected();
- }
+ private void removeContactFromSelection(ContactAddress ca) {
+ updateContactsClick(ca, mSearchAdapter.getContactsSelectedList());
+ mSearchAdapter.notifyDataSetChanged();
+ updateListSelected();
+ }
- @Override
- public void onSaveInstanceState(Bundle outState) {
- if (mContactsSelected != null && mContactsSelected.size() > 0) {
- ArrayList listUri = new ArrayList();
- for (ContactAddress ca : mContactsSelected) {
- listUri.add(ca.getAddressAsDisplayableString());
- }
- outState.putStringArrayList("mContactsSelected", listUri);
- }
+ @Override
+ public void onSaveInstanceState(Bundle outState) {
+ if (mContactsSelected != null && mContactsSelected.size() > 0) {
+ ArrayList listUri = new ArrayList();
+ for (ContactAddress ca : mContactsSelected) {
+ listUri.add(ca.getAddressAsDisplayableString());
+ }
+ outState.putStringArrayList("mContactsSelected", listUri);
+ }
- outState.putBoolean("onlySipContact", mOnlyDisplayLinphoneContacts);
+ outState.putBoolean("onlySipContact", mOnlyDisplayLinphoneContacts);
- super.onSaveInstanceState(outState);
- }
+ super.onSaveInstanceState(outState);
+ }
- @Override
- public void onClick(View view) {
- int id = view.getId();
- if (id == R.id.all_contacts) {
- mSearchAdapter.setOnlySipContact(mOnlyDisplayLinphoneContacts = false);
- mAllContactsSelected.setVisibility(View.VISIBLE);
- mAllContactsButton.setEnabled(false);
- mLinphoneContactsButton.setEnabled(true);
- mLinphoneContactsSelected.setVisibility(View.INVISIBLE);
- updateList();
- resetAndResearch();
- } else if (id == R.id.linphone_contacts) {
- mSearchAdapter.setOnlySipContact(true);
- mLinphoneContactsSelected.setVisibility(View.VISIBLE);
- mLinphoneContactsButton.setEnabled(false);
- mAllContactsButton.setEnabled(mOnlyDisplayLinphoneContacts = true);
- mAllContactsSelected.setVisibility(View.INVISIBLE);
- updateList();
- resetAndResearch();
- } else if (id == R.id.back) {
- if (LinphoneActivity.instance().isTablet()) {
- LinphoneActivity.instance().goToChatList();
- } else {
- mContactsSelectedLayout.removeAllViews();
- LinphoneActivity.instance().popBackStack();
- }
- } else if (id == R.id.next) {
- if (mChatRoomAddress == null && mChatRoomSubject == null) {
- if (mContactsSelected.size() == 1) {
- mContactsSelectedLayout.removeAllViews();
- mWaitLayout.setVisibility(View.VISIBLE);
- Core lc = LinphoneManager.getLc();
- Address participant = mContactsSelected.get(0).getAddress();
- ChatRoom chatRoom = lc.findOneToOneChatRoom(lc.getDefaultProxyConfig().getContact(), participant);
- if (chatRoom == null) {
- ProxyConfig lpc = lc.getDefaultProxyConfig();
- if (lpc != null && lpc.getConferenceFactoryUri() != null && !LinphonePreferences.instance().useBasicChatRoomFor1To1()) {
- mChatRoom = lc.createClientGroupChatRoom(getString(R.string.dummy_group_chat_subject), true);
- mChatRoom.addListener(mChatRoomCreationListener);
- mChatRoom.addParticipant(participant);
- } else {
- chatRoom = lc.getChatRoom(participant);
- LinphoneActivity.instance().goToChat(chatRoom.getPeerAddress().asStringUriOnly(), mShareInfos);
- }
- } else {
- LinphoneActivity.instance().goToChat(chatRoom.getPeerAddress().asStringUriOnly(), mShareInfos);
- }
- } else {
- mContactsSelectedLayout.removeAllViews();
- LinphoneActivity.instance().goToChatGroupInfos(null, mContactsSelected, null, true, false, mShareInfos);
- }
- } else {
- LinphoneActivity.instance().goToChatGroupInfos(mChatRoomAddress, mContactsSelected, mChatRoomSubject, true, true, mShareInfos);
- }
- } else if (id == R.id.clearSearchField) {
- mSearchField.setText("");
- mSearchAdapter.searchContacts("", mContactsList);
- } else if (id == R.id.contactChatDelete) {
- ContactAddress ca = (ContactAddress) view.getTag();
- removeContactFromSelection(ca);
- }
- }
+ @Override
+ public void onClick(View view) {
+ int id = view.getId();
+ if (id == R.id.all_contacts) {
+ mSearchAdapter.setOnlySipContact(mOnlyDisplayLinphoneContacts = false);
+ mAllContactsSelected.setVisibility(View.VISIBLE);
+ mAllContactsButton.setEnabled(false);
+ mLinphoneContactsButton.setEnabled(true);
+ mLinphoneContactsSelected.setVisibility(View.INVISIBLE);
+ updateList();
+ resetAndResearch();
+ } else if (id == R.id.linphone_contacts) {
+ mSearchAdapter.setOnlySipContact(true);
+ mLinphoneContactsSelected.setVisibility(View.VISIBLE);
+ mLinphoneContactsButton.setEnabled(false);
+ mAllContactsButton.setEnabled(mOnlyDisplayLinphoneContacts = true);
+ mAllContactsSelected.setVisibility(View.INVISIBLE);
+ updateList();
+ resetAndResearch();
+ } else if (id == R.id.back) {
+ if (LinphoneActivity.instance().isTablet()) {
+ LinphoneActivity.instance().goToChatList();
+ } else {
+ mContactsSelectedLayout.removeAllViews();
+ LinphoneActivity.instance().popBackStack();
+ }
+ } else if (id == R.id.next) {
+ if (mChatRoomAddress == null && mChatRoomSubject == null) {
+ if (mContactsSelected.size() == 1) {
+ mContactsSelectedLayout.removeAllViews();
+ mWaitLayout.setVisibility(View.VISIBLE);
+ Core lc = LinphoneManager.getLc();
+ Address participant = mContactsSelected.get(0).getAddress();
+ ChatRoom chatRoom = lc.findOneToOneChatRoom(lc.getDefaultProxyConfig().getContact(), participant);
+ if (chatRoom == null) {
+ ProxyConfig lpc = lc.getDefaultProxyConfig();
+ if (lpc != null && lpc.getConferenceFactoryUri() != null && !LinphonePreferences.instance().useBasicChatRoomFor1To1()) {
+ mChatRoom = lc.createClientGroupChatRoom(getString(R.string.dummy_group_chat_subject), true);
+ mChatRoom.addListener(mChatRoomCreationListener);
+ mChatRoom.addParticipant(participant);
+ } else {
+ chatRoom = lc.getChatRoom(participant);
+ LinphoneActivity.instance().goToChat(chatRoom.getPeerAddress().asStringUriOnly(), mShareInfos);
+ }
+ } else {
+ LinphoneActivity.instance().goToChat(chatRoom.getPeerAddress().asStringUriOnly(), mShareInfos);
+ }
+ } else {
+ mContactsSelectedLayout.removeAllViews();
+ LinphoneActivity.instance().goToChatGroupInfos(null, mContactsSelected, null, true, false, mShareInfos);
+ }
+ } else {
+ LinphoneActivity.instance().goToChatGroupInfos(mChatRoomAddress, mContactsSelected, mChatRoomSubject, true, true, mShareInfos);
+ }
+ } else if (id == R.id.clearSearchField) {
+ mSearchField.setText("");
+ mSearchAdapter.searchContacts("", mContactsList);
+ } else if (id == R.id.contactChatDelete) {
+ ContactAddress ca = (ContactAddress) view.getTag();
+ removeContactFromSelection(ca);
+ }
+ }
- @Override
- public void onItemClicked(int position) {
- ContactAddress ca = mSearchAdapter.getContacts().get(position);
- Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- ProxyConfig lpc = lc.getDefaultProxyConfig();
- if (lpc == null || lpc.getConferenceFactoryUri() == null) {
- ChatRoom chatRoom = lc.getChatRoom(ca.getAddress());
- LinphoneActivity.instance().goToChat(chatRoom.getPeerAddress().asStringUriOnly(), mShareInfos);
- } else {
- removeContactFromSelection(ca);
- }
- }
+ @Override
+ public void onItemClicked(int position) {
+ ContactAddress ca = mSearchAdapter.getContacts().get(position);
+ Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ ProxyConfig lpc = lc.getDefaultProxyConfig();
+ if (lpc == null || lpc.getConferenceFactoryUri() == null) {
+ ChatRoom chatRoom = lc.getChatRoom(ca.getAddress());
+ LinphoneActivity.instance().goToChat(chatRoom.getPeerAddress().asStringUriOnly(), mShareInfos);
+ } else {
+ removeContactFromSelection(ca);
+ }
+ }
- @Override
- public void onContactsUpdated() {
- updateList();
- }
+ @Override
+ public void onContactsUpdated() {
+ updateList();
+ }
}
diff --git a/src/android/org/linphone/chat/ChatEventsAdapter.java b/src/android/org/linphone/chat/ChatEventsAdapter.java
index a9ef0ec66..efeacf0db 100644
--- a/src/android/org/linphone/chat/ChatEventsAdapter.java
+++ b/src/android/org/linphone/chat/ChatEventsAdapter.java
@@ -75,357 +75,357 @@ import static android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION;
public class ChatEventsAdapter extends SelectableAdapter {
- private static int MARGIN_BETWEEN_MESSAGES = 10;
- private static int SIDE_MARGIN = 100;
- private Context mContext;
+ private static int MARGIN_BETWEEN_MESSAGES = 10;
+ private static int SIDE_MARGIN = 100;
+ private Context mContext;
private List mHistory;
- private List mParticipants;
- private int mItemResource;
- private Bitmap mDefaultBitmap;
- private GroupChatFragment mFragment;
- private ChatMessageListenerStub mListener;
+ private List mParticipants;
+ private int mItemResource;
+ private Bitmap mDefaultBitmap;
+ private GroupChatFragment mFragment;
+ private ChatMessageListenerStub mListener;
- private ChatBubbleViewHolder.ClickListener mClickListener;
+ private ChatBubbleViewHolder.ClickListener mClickListener;
public ChatEventsAdapter(GroupChatFragment fragment, SelectableHelper helper, int itemResource, EventLog[] history, ArrayList participants, ChatBubbleViewHolder.ClickListener clickListener) {
- super(helper);
- mFragment = fragment;
- mContext = mFragment.getActivity();
- mItemResource = itemResource;
- mHistory = new ArrayList<>(Arrays.asList(history));
- mParticipants = participants;
- mClickListener = clickListener;
- mListener = new ChatMessageListenerStub() {
- @Override
- public void onFileTransferProgressIndication(ChatMessage message, Content content, int offset, int total) {
- ChatBubbleViewHolder holder = (ChatBubbleViewHolder)message.getUserData();
- if (holder == null) return;
+ super(helper);
+ mFragment = fragment;
+ mContext = mFragment.getActivity();
+ mItemResource = itemResource;
+ mHistory = new ArrayList<>(Arrays.asList(history));
+ mParticipants = participants;
+ mClickListener = clickListener;
+ mListener = new ChatMessageListenerStub() {
+ @Override
+ public void onFileTransferProgressIndication(ChatMessage message, Content content, int offset, int total) {
+ ChatBubbleViewHolder holder = (ChatBubbleViewHolder) message.getUserData();
+ if (holder == null) return;
- if (offset == total) {
- holder.fileTransferProgressBar.setVisibility(View.GONE);
- holder.fileTransferAction.setVisibility(View.GONE);
- holder.fileTransferLayout.setVisibility(View.GONE);
+ if (offset == total) {
+ holder.fileTransferProgressBar.setVisibility(View.GONE);
+ holder.fileTransferAction.setVisibility(View.GONE);
+ holder.fileTransferLayout.setVisibility(View.GONE);
- displayAttachedFile(message, holder);
- } else {
- holder.fileTransferProgressBar.setVisibility(View.VISIBLE);
- holder.fileTransferProgressBar.setProgress(offset * 100 / total);
- }
- }
+ displayAttachedFile(message, holder);
+ } else {
+ holder.fileTransferProgressBar.setVisibility(View.VISIBLE);
+ holder.fileTransferProgressBar.setProgress(offset * 100 / total);
+ }
+ }
- @Override
- public void onMsgStateChanged(ChatMessage message, ChatMessage.State state) {
- if (state == ChatMessage.State.FileTransferDone) {
- if (!message.isOutgoing()) {
- message.setAppdata(message.getFileTransferFilepath());
- }
- message.setFileTransferFilepath(null); // Not needed anymore, will help differenciate between InProgress states for file transfer / message sending
- }
- notifyDataSetChanged();
- }
- };
+ @Override
+ public void onMsgStateChanged(ChatMessage message, ChatMessage.State state) {
+ if (state == ChatMessage.State.FileTransferDone) {
+ if (!message.isOutgoing()) {
+ message.setAppdata(message.getFileTransferFilepath());
+ }
+ message.setFileTransferFilepath(null); // Not needed anymore, will help differenciate between InProgress states for file transfer / message sending
+ }
+ notifyDataSetChanged();
+ }
+ };
}
@Override
public ChatBubbleViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
- .inflate(mItemResource, parent, false);
- ChatBubbleViewHolder VH = new ChatBubbleViewHolder(mContext,v, mClickListener);
+ .inflate(mItemResource, parent, false);
+ ChatBubbleViewHolder VH = new ChatBubbleViewHolder(mContext, v, mClickListener);
- //Allows onLongClick ContextMenu on bubbles
- mFragment.registerForContextMenu(v);
- v.setTag(VH);
- return VH;
+ //Allows onLongClick ContextMenu on bubbles
+ mFragment.registerForContextMenu(v);
+ v.setTag(VH);
+ return VH;
}
@Override
public void onBindViewHolder(@NonNull ChatBubbleViewHolder holder, int position) {
- final EventLog event = mHistory.get(position);
- holder.eventLayout.setVisibility(View.GONE);
- holder.bubbleLayout.setVisibility(View.GONE);
- holder.delete.setVisibility(isEditionEnabled() ? View.VISIBLE : View.GONE);
- holder.messageText.setVisibility(View.GONE);
- holder.messageImage.setVisibility(View.GONE);
- holder.fileTransferLayout.setVisibility(View.GONE);
- holder.fileTransferProgressBar.setProgress(0);
- holder.fileTransferAction.setEnabled(true);
- holder.fileName.setVisibility(View.GONE);
- holder.openFileButton.setVisibility(View.GONE);
- holder.messageStatus.setVisibility(View.INVISIBLE);
- holder.messageSendingInProgress.setVisibility(View.GONE);
- holder.imdmLayout.setVisibility(View.INVISIBLE);
- holder.contactPicture.setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap());
+ final EventLog event = mHistory.get(position);
+ holder.eventLayout.setVisibility(View.GONE);
+ holder.bubbleLayout.setVisibility(View.GONE);
+ holder.delete.setVisibility(isEditionEnabled() ? View.VISIBLE : View.GONE);
+ holder.messageText.setVisibility(View.GONE);
+ holder.messageImage.setVisibility(View.GONE);
+ holder.fileTransferLayout.setVisibility(View.GONE);
+ holder.fileTransferProgressBar.setProgress(0);
+ holder.fileTransferAction.setEnabled(true);
+ holder.fileName.setVisibility(View.GONE);
+ holder.openFileButton.setVisibility(View.GONE);
+ holder.messageStatus.setVisibility(View.INVISIBLE);
+ holder.messageSendingInProgress.setVisibility(View.GONE);
+ holder.imdmLayout.setVisibility(View.INVISIBLE);
+ holder.contactPicture.setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap());
- if (isEditionEnabled()) {
- holder.delete.setOnCheckedChangeListener(null);
- holder.delete.setChecked(isSelected(position));
- holder.delete.setTag(position);
- }
+ if (isEditionEnabled()) {
+ holder.delete.setOnCheckedChangeListener(null);
+ holder.delete.setChecked(isSelected(position));
+ holder.delete.setTag(position);
+ }
- if (event.getType() == EventLog.Type.ConferenceChatMessage) {
- holder.bubbleLayout.setVisibility(View.VISIBLE);
- final ChatMessage message = event.getChatMessage();
+ if (event.getType() == EventLog.Type.ConferenceChatMessage) {
+ holder.bubbleLayout.setVisibility(View.VISIBLE);
+ final ChatMessage message = event.getChatMessage();
- if (position > 0 && mContext.getResources().getBoolean(R.bool.lower_space_between_chat_bubbles_if_same_person)) {
- EventLog previousEvent = (EventLog)getItem(position-1);
- if (previousEvent.getType() == EventLog.Type.ConferenceChatMessage) {
- ChatMessage previousMessage = previousEvent.getChatMessage();
- if (previousMessage.getFromAddress().weakEqual(message.getFromAddress())) {
- holder.separatorLayout.setVisibility(View.GONE);
- }
- } else {
- // No separator if previous event is not a message
- holder.separatorLayout.setVisibility(View.GONE);
- }
- }
+ if (position > 0 && mContext.getResources().getBoolean(R.bool.lower_space_between_chat_bubbles_if_same_person)) {
+ EventLog previousEvent = (EventLog) getItem(position - 1);
+ if (previousEvent.getType() == EventLog.Type.ConferenceChatMessage) {
+ ChatMessage previousMessage = previousEvent.getChatMessage();
+ if (previousMessage.getFromAddress().weakEqual(message.getFromAddress())) {
+ holder.separatorLayout.setVisibility(View.GONE);
+ }
+ } else {
+ // No separator if previous event is not a message
+ holder.separatorLayout.setVisibility(View.GONE);
+ }
+ }
- holder.messageId = message.getMessageId();
- message.setUserData(holder);
+ holder.messageId = message.getMessageId();
+ message.setUserData(holder);
- RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
+ RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
- ChatMessage.State status = message.getState();
- Address remoteSender = message.getFromAddress();
- String displayName;
+ ChatMessage.State status = message.getState();
+ Address remoteSender = message.getFromAddress();
+ String displayName;
- LinphoneContact contact = null;
- if (message.isOutgoing()) {
- message.setListener(mListener);
+ LinphoneContact contact = null;
+ if (message.isOutgoing()) {
+ message.setListener(mListener);
- if (status == ChatMessage.State.InProgress) {
- holder.messageSendingInProgress.setVisibility(View.VISIBLE);
- }
+ if (status == ChatMessage.State.InProgress) {
+ holder.messageSendingInProgress.setVisibility(View.VISIBLE);
+ }
- if (!message.isSecured() && LinphoneManager.getLc().limeEnabled() == LimeState.Mandatory && status != ChatMessage.State.InProgress) {
- holder.messageStatus.setVisibility(View.VISIBLE);
- holder.messageStatus.setImageResource(R.drawable.chat_unsecure);
- }
+ if (!message.isSecured() && LinphoneManager.getLc().limeEnabled() == LimeState.Mandatory && status != ChatMessage.State.InProgress) {
+ holder.messageStatus.setVisibility(View.VISIBLE);
+ holder.messageStatus.setImageResource(R.drawable.chat_unsecure);
+ }
- if (status == ChatMessage.State.Delivered) {
+ if (status == ChatMessage.State.Delivered) {
/*holder.imdmLayout.setVisibility(View.VISIBLE);
holder.imdmLabel.setText(R.string.sent);
holder.imdmIcon.setImageResource(R.drawable.chat_delivered);
holder.imdmLabel.setTextColor(mContext.getResources().getColor(R.color.colorD));*/
- } else if (status == ChatMessage.State.DeliveredToUser) {
- holder.imdmLayout.setVisibility(View.VISIBLE);
- holder.imdmIcon.setImageResource(R.drawable.chat_delivered);
- holder.imdmLabel.setText(R.string.delivered);
- holder.imdmLabel.setTextColor(mContext.getResources().getColor(R.color.colorD));
- } else if (status == ChatMessage.State.Displayed) {
- holder.imdmLayout.setVisibility(View.VISIBLE);
- holder.imdmIcon.setImageResource(R.drawable.chat_read);
- holder.imdmLabel.setText(R.string.displayed);
- holder.imdmLabel.setTextColor(mContext.getResources().getColor(R.color.colorK));
- } else if (status == ChatMessage.State.NotDelivered) {
- holder.imdmLayout.setVisibility(View.VISIBLE);
- holder.imdmIcon.setImageResource(R.drawable.chat_error);
- holder.imdmLabel.setText(R.string.error);
- holder.imdmLabel.setTextColor(mContext.getResources().getColor(R.color.colorI));
- } else if (status == ChatMessage.State.FileTransferError) {
- holder.imdmLayout.setVisibility(View.VISIBLE);
- holder.imdmIcon.setImageResource(R.drawable.chat_error);
- holder.imdmLabel.setText(R.string.file_transfer_error);
- holder.imdmLabel.setTextColor(mContext.getResources().getColor(R.color.colorI));
- }
+ } else if (status == ChatMessage.State.DeliveredToUser) {
+ holder.imdmLayout.setVisibility(View.VISIBLE);
+ holder.imdmIcon.setImageResource(R.drawable.chat_delivered);
+ holder.imdmLabel.setText(R.string.delivered);
+ holder.imdmLabel.setTextColor(mContext.getResources().getColor(R.color.colorD));
+ } else if (status == ChatMessage.State.Displayed) {
+ holder.imdmLayout.setVisibility(View.VISIBLE);
+ holder.imdmIcon.setImageResource(R.drawable.chat_read);
+ holder.imdmLabel.setText(R.string.displayed);
+ holder.imdmLabel.setTextColor(mContext.getResources().getColor(R.color.colorK));
+ } else if (status == ChatMessage.State.NotDelivered) {
+ holder.imdmLayout.setVisibility(View.VISIBLE);
+ holder.imdmIcon.setImageResource(R.drawable.chat_error);
+ holder.imdmLabel.setText(R.string.error);
+ holder.imdmLabel.setTextColor(mContext.getResources().getColor(R.color.colorI));
+ } else if (status == ChatMessage.State.FileTransferError) {
+ holder.imdmLayout.setVisibility(View.VISIBLE);
+ holder.imdmIcon.setImageResource(R.drawable.chat_error);
+ holder.imdmLabel.setText(R.string.file_transfer_error);
+ holder.imdmLabel.setTextColor(mContext.getResources().getColor(R.color.colorI));
+ }
- //layoutParams allow bubbles alignment during selection mode
- if (isEditionEnabled()) {
- layoutParams.addRule(RelativeLayout.LEFT_OF, holder.delete.getId());
- layoutParams.setMargins(SIDE_MARGIN, MARGIN_BETWEEN_MESSAGES/2, 0, MARGIN_BETWEEN_MESSAGES/2);
- } else {
- layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
- layoutParams.setMargins(SIDE_MARGIN, MARGIN_BETWEEN_MESSAGES/2, 0, MARGIN_BETWEEN_MESSAGES/2);
- }
+ //layoutParams allow bubbles alignment during selection mode
+ if (isEditionEnabled()) {
+ layoutParams.addRule(RelativeLayout.LEFT_OF, holder.delete.getId());
+ layoutParams.setMargins(SIDE_MARGIN, MARGIN_BETWEEN_MESSAGES / 2, 0, MARGIN_BETWEEN_MESSAGES / 2);
+ } else {
+ layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
+ layoutParams.setMargins(SIDE_MARGIN, MARGIN_BETWEEN_MESSAGES / 2, 0, MARGIN_BETWEEN_MESSAGES / 2);
+ }
- holder.background.setBackgroundResource(R.drawable.resizable_chat_bubble_outgoing);
- Compatibility.setTextAppearance(holder.contactName, mContext, R.style.font3);
- Compatibility.setTextAppearance(holder.fileTransferAction, mContext, R.style.font15);
- holder.fileTransferAction.setBackgroundResource(R.drawable.resizable_confirm_delete_button);
- holder.contactPictureMask.setImageResource(R.drawable.avatar_chat_mask_outgoing);
- } else {
- for (LinphoneContact c : mParticipants) {
- if (c != null && c.hasAddress(remoteSender.asStringUriOnly())) {
- contact = c;
- break;
- }
- }
+ holder.background.setBackgroundResource(R.drawable.resizable_chat_bubble_outgoing);
+ Compatibility.setTextAppearance(holder.contactName, mContext, R.style.font3);
+ Compatibility.setTextAppearance(holder.fileTransferAction, mContext, R.style.font15);
+ holder.fileTransferAction.setBackgroundResource(R.drawable.resizable_confirm_delete_button);
+ holder.contactPictureMask.setImageResource(R.drawable.avatar_chat_mask_outgoing);
+ } else {
+ for (LinphoneContact c : mParticipants) {
+ if (c != null && c.hasAddress(remoteSender.asStringUriOnly())) {
+ contact = c;
+ break;
+ }
+ }
- if (isEditionEnabled()) {
- layoutParams.addRule(RelativeLayout.LEFT_OF, holder.delete.getId());
- layoutParams.setMargins(SIDE_MARGIN, MARGIN_BETWEEN_MESSAGES/2, 0, MARGIN_BETWEEN_MESSAGES/2);
- } else {
- layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
- layoutParams.setMargins(0, MARGIN_BETWEEN_MESSAGES/2, SIDE_MARGIN, MARGIN_BETWEEN_MESSAGES/2);
- }
+ if (isEditionEnabled()) {
+ layoutParams.addRule(RelativeLayout.LEFT_OF, holder.delete.getId());
+ layoutParams.setMargins(SIDE_MARGIN, MARGIN_BETWEEN_MESSAGES / 2, 0, MARGIN_BETWEEN_MESSAGES / 2);
+ } else {
+ layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
+ layoutParams.setMargins(0, MARGIN_BETWEEN_MESSAGES / 2, SIDE_MARGIN, MARGIN_BETWEEN_MESSAGES / 2);
+ }
- holder.background.setBackgroundResource(R.drawable.resizable_chat_bubble_incoming);
- Compatibility.setTextAppearance(holder.contactName, mContext, R.style.font9);
- Compatibility.setTextAppearance(holder.fileTransferAction, mContext, R.style.font8);
- holder.fileTransferAction.setBackgroundResource(R.drawable.resizable_assistant_button);
- holder.contactPictureMask.setImageResource(R.drawable.avatar_chat_mask);
- }
+ holder.background.setBackgroundResource(R.drawable.resizable_chat_bubble_incoming);
+ Compatibility.setTextAppearance(holder.contactName, mContext, R.style.font9);
+ Compatibility.setTextAppearance(holder.fileTransferAction, mContext, R.style.font8);
+ holder.fileTransferAction.setBackgroundResource(R.drawable.resizable_assistant_button);
+ holder.contactPictureMask.setImageResource(R.drawable.avatar_chat_mask);
+ }
- if (contact == null) {
- contact = ContactsManager.getInstance().findContactFromAddress(remoteSender);
- }
- if (contact != null) {
- if (contact.getFullName() != null) {
- displayName = contact.getFullName();
- } else {
- displayName = LinphoneUtils.getAddressDisplayName(remoteSender);
- }
+ if (contact == null) {
+ contact = ContactsManager.getInstance().findContactFromAddress(remoteSender);
+ }
+ if (contact != null) {
+ if (contact.getFullName() != null) {
+ displayName = contact.getFullName();
+ } else {
+ displayName = LinphoneUtils.getAddressDisplayName(remoteSender);
+ }
- holder.contactPicture.setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap());
- if (contact.hasPhoto()) {
- LinphoneUtils.setThumbnailPictureFromUri(LinphoneActivity.instance(), holder.contactPicture, contact.getThumbnailUri());
- }
- } else {
- displayName = LinphoneUtils.getAddressDisplayName(remoteSender);
- holder.contactPicture.setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap());
- }
- holder.contactName.setText(LinphoneUtils.timestampToHumanDate(mContext, message.getTime(), R.string.messages_date_format) + " - " + displayName);
+ holder.contactPicture.setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap());
+ if (contact.hasPhoto()) {
+ LinphoneUtils.setThumbnailPictureFromUri(LinphoneActivity.instance(), holder.contactPicture, contact.getThumbnailUri());
+ }
+ } else {
+ displayName = LinphoneUtils.getAddressDisplayName(remoteSender);
+ holder.contactPicture.setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap());
+ }
+ holder.contactName.setText(LinphoneUtils.timestampToHumanDate(mContext, message.getTime(), R.string.messages_date_format) + " - " + displayName);
- if (message.hasTextContent()) {
- String msg = message.getTextContent();
- Spanned text = LinphoneUtils.getTextWithHttpLinks(msg);
- holder.messageText.setText(text);
- holder.messageText.setMovementMethod(LinkMovementMethod.getInstance());
- holder.messageText.setVisibility(View.VISIBLE);
- }
+ if (message.hasTextContent()) {
+ String msg = message.getTextContent();
+ Spanned text = LinphoneUtils.getTextWithHttpLinks(msg);
+ holder.messageText.setText(text);
+ holder.messageText.setMovementMethod(LinkMovementMethod.getInstance());
+ holder.messageText.setVisibility(View.VISIBLE);
+ }
- String externalBodyUrl = message.getExternalBodyUrl();
- Content fileTransferContent = message.getFileTransferInformation();
+ String externalBodyUrl = message.getExternalBodyUrl();
+ Content fileTransferContent = message.getFileTransferInformation();
- if (message.getAppdata() != null) { // Something to display
- displayAttachedFile(message, holder);
- }
+ if (message.getAppdata() != null) { // Something to display
+ displayAttachedFile(message, holder);
+ }
- if (externalBodyUrl != null) { // Incoming file transfer not yet downloaded
- holder.fileName.setVisibility(View.VISIBLE);
- holder.fileName.setText(fileTransferContent.getName());
+ if (externalBodyUrl != null) { // Incoming file transfer not yet downloaded
+ holder.fileName.setVisibility(View.VISIBLE);
+ holder.fileName.setText(fileTransferContent.getName());
- holder.fileTransferLayout.setVisibility(View.VISIBLE);
- holder.fileTransferProgressBar.setVisibility(View.GONE);
- if (message.isFileTransferInProgress()) { // Incoming file transfer in progress
- holder.fileTransferAction.setVisibility(View.GONE);
- } else {
- holder.fileTransferAction.setText(mContext.getString(R.string.accept));
- holder.fileTransferAction.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- if (mContext.getPackageManager().checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, mContext.getPackageName()) == PackageManager.PERMISSION_GRANTED) {
- v.setEnabled(false);
- String filename = message.getFileTransferInformation().getName();
- File file = new File(Environment.getExternalStorageDirectory(), filename);
- int prefix = 1;
- while (file.exists()) {
- file = new File(Environment.getExternalStorageDirectory(), prefix + "_" + filename);
- Log.w("File with that name already exists, renamed to " + prefix + "_" + filename);
- prefix += 1;
- }
- message.setListener(mListener);
- message.setFileTransferFilepath(file.getPath());
- message.downloadFile();
+ holder.fileTransferLayout.setVisibility(View.VISIBLE);
+ holder.fileTransferProgressBar.setVisibility(View.GONE);
+ if (message.isFileTransferInProgress()) { // Incoming file transfer in progress
+ holder.fileTransferAction.setVisibility(View.GONE);
+ } else {
+ holder.fileTransferAction.setText(mContext.getString(R.string.accept));
+ holder.fileTransferAction.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (mContext.getPackageManager().checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, mContext.getPackageName()) == PackageManager.PERMISSION_GRANTED) {
+ v.setEnabled(false);
+ String filename = message.getFileTransferInformation().getName();
+ File file = new File(Environment.getExternalStorageDirectory(), filename);
+ int prefix = 1;
+ while (file.exists()) {
+ file = new File(Environment.getExternalStorageDirectory(), prefix + "_" + filename);
+ Log.w("File with that name already exists, renamed to " + prefix + "_" + filename);
+ prefix += 1;
+ }
+ message.setListener(mListener);
+ message.setFileTransferFilepath(file.getPath());
+ message.downloadFile();
- } else {
- Log.w("WRITE_EXTERNAL_STORAGE permission not granted, won't be able to store the downloaded file");
- LinphoneActivity.instance().checkAndRequestExternalStoragePermission();
- }
- }
- });
- }
- } else if (message.isFileTransferInProgress()) { // Outgoing file transfer in progress
- message.setListener(mListener); // add the listener for file upload progress display
- holder.messageSendingInProgress.setVisibility(View.GONE);
- holder.fileTransferLayout.setVisibility(View.VISIBLE);
- holder.fileTransferAction.setText(mContext.getString(R.string.cancel));
- holder.fileTransferAction.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- message.cancelFileTransfer();
- notifyDataSetChanged();
- }
- });
- }
+ } else {
+ Log.w("WRITE_EXTERNAL_STORAGE permission not granted, won't be able to store the downloaded file");
+ LinphoneActivity.instance().checkAndRequestExternalStoragePermission();
+ }
+ }
+ });
+ }
+ } else if (message.isFileTransferInProgress()) { // Outgoing file transfer in progress
+ message.setListener(mListener); // add the listener for file upload progress display
+ holder.messageSendingInProgress.setVisibility(View.GONE);
+ holder.fileTransferLayout.setVisibility(View.VISIBLE);
+ holder.fileTransferAction.setText(mContext.getString(R.string.cancel));
+ holder.fileTransferAction.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ message.cancelFileTransfer();
+ notifyDataSetChanged();
+ }
+ });
+ }
- holder.bubbleLayout.setLayoutParams(layoutParams);
- } else { // Event is not chat message
- holder.eventLayout.setVisibility(View.VISIBLE);
+ holder.bubbleLayout.setLayoutParams(layoutParams);
+ } else { // Event is not chat message
+ holder.eventLayout.setVisibility(View.VISIBLE);
- Address address = event.getParticipantAddress();
- String displayName = null;
- if (address != null) {
- LinphoneContact contact = ContactsManager.getInstance().findContactFromAddress(address);
- if (contact != null) {
- displayName = contact.getFullName();
- } else {
- displayName = LinphoneUtils.getAddressDisplayName(address);
- }
- }
+ Address address = event.getParticipantAddress();
+ String displayName = null;
+ if (address != null) {
+ LinphoneContact contact = ContactsManager.getInstance().findContactFromAddress(address);
+ if (contact != null) {
+ displayName = contact.getFullName();
+ } else {
+ displayName = LinphoneUtils.getAddressDisplayName(address);
+ }
+ }
- switch (event.getType()) {
- case ConferenceCreated:
- holder.eventMessage.setText(mContext.getString(R.string.conference_created));
- break;
- case ConferenceTerminated:
- holder.eventMessage.setText(mContext.getString(R.string.conference_destroyed));
- break;
- case ConferenceParticipantAdded:
- holder.eventMessage.setText(mContext.getString(R.string.participant_added).replace("%s", displayName));
- break;
- case ConferenceParticipantRemoved:
- holder.eventMessage.setText(mContext.getString(R.string.participant_removed).replace("%s", displayName));
- break;
- case ConferenceSubjectChanged:
- holder.eventMessage.setText(mContext.getString(R.string.subject_changed).replace("%s", event.getSubject()));
- break;
- case ConferenceParticipantSetAdmin:
- holder.eventMessage.setText(mContext.getString(R.string.admin_set).replace("%s", displayName));
- break;
- case ConferenceParticipantUnsetAdmin:
- holder.eventMessage.setText(mContext.getString(R.string.admin_unset).replace("%s", displayName));
- break;
- case ConferenceParticipantDeviceAdded:
- holder.eventMessage.setText(mContext.getString(R.string.device_added).replace("%s", displayName));
- break;
- case ConferenceParticipantDeviceRemoved:
- holder.eventMessage.setText(mContext.getString(R.string.device_removed).replace("%s", displayName));
- break;
- case None:
- default:
- //TODO
- break;
- }
- }
+ switch (event.getType()) {
+ case ConferenceCreated:
+ holder.eventMessage.setText(mContext.getString(R.string.conference_created));
+ break;
+ case ConferenceTerminated:
+ holder.eventMessage.setText(mContext.getString(R.string.conference_destroyed));
+ break;
+ case ConferenceParticipantAdded:
+ holder.eventMessage.setText(mContext.getString(R.string.participant_added).replace("%s", displayName));
+ break;
+ case ConferenceParticipantRemoved:
+ holder.eventMessage.setText(mContext.getString(R.string.participant_removed).replace("%s", displayName));
+ break;
+ case ConferenceSubjectChanged:
+ holder.eventMessage.setText(mContext.getString(R.string.subject_changed).replace("%s", event.getSubject()));
+ break;
+ case ConferenceParticipantSetAdmin:
+ holder.eventMessage.setText(mContext.getString(R.string.admin_set).replace("%s", displayName));
+ break;
+ case ConferenceParticipantUnsetAdmin:
+ holder.eventMessage.setText(mContext.getString(R.string.admin_unset).replace("%s", displayName));
+ break;
+ case ConferenceParticipantDeviceAdded:
+ holder.eventMessage.setText(mContext.getString(R.string.device_added).replace("%s", displayName));
+ break;
+ case ConferenceParticipantDeviceRemoved:
+ holder.eventMessage.setText(mContext.getString(R.string.device_removed).replace("%s", displayName));
+ break;
+ case None:
+ default:
+ //TODO
+ break;
+ }
+ }
}
@Override
public int getItemCount() {
- return mHistory.size();
+ return mHistory.size();
}
public void addToHistory(EventLog log) {
- mHistory.add(log);
- notifyDataSetChanged();
+ mHistory.add(log);
+ notifyDataSetChanged();
}
public void setContacts(ArrayList participants) {
- mParticipants = participants;
+ mParticipants = participants;
}
public void refresh(EventLog[] history) {
- mHistory = new ArrayList<>(Arrays.asList(history));
- notifyDataSetChanged();
+ mHistory = new ArrayList<>(Arrays.asList(history));
+ notifyDataSetChanged();
}
public void clear() {
- for (EventLog event : mHistory) {
- if (event.getType() == EventLog.Type.ConferenceChatMessage) {
- ChatMessage message = event.getChatMessage();
- message.setListener(null);
- }
- }
- mHistory.clear();
+ for (EventLog event : mHistory) {
+ if (event.getType() == EventLog.Type.ConferenceChatMessage) {
+ ChatMessage message = event.getChatMessage();
+ message.setListener(null);
+ }
+ }
+ mHistory.clear();
}
public int getCount() {
@@ -436,209 +436,209 @@ public class ChatEventsAdapter extends SelectableAdapter {
return mHistory.get(i);
}
- public void removeItem(int i) {
- mHistory.remove(i);
- notifyDataSetChanged();
+ public void removeItem(int i) {
+ mHistory.remove(i);
+ notifyDataSetChanged();
}
- private void loadBitmap(String path, ImageView imageView) {
- if (cancelPotentialWork(path, imageView)) {
- if (LinphoneUtils.isExtensionImage(path)) {
- mDefaultBitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.chat_attachment_over);
- } else {
- mDefaultBitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.chat_attachment);
- }
+ private void loadBitmap(String path, ImageView imageView) {
+ if (cancelPotentialWork(path, imageView)) {
+ if (LinphoneUtils.isExtensionImage(path)) {
+ mDefaultBitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.chat_attachment_over);
+ } else {
+ mDefaultBitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.chat_attachment);
+ }
- BitmapWorkerTask task = new BitmapWorkerTask(imageView);
- final AsyncBitmap asyncBitmap = new AsyncBitmap(mContext.getResources(), mDefaultBitmap, task);
- imageView.setImageDrawable(asyncBitmap);
- task.execute(path);
- }
- }
+ BitmapWorkerTask task = new BitmapWorkerTask(imageView);
+ final AsyncBitmap asyncBitmap = new AsyncBitmap(mContext.getResources(), mDefaultBitmap, task);
+ imageView.setImageDrawable(asyncBitmap);
+ task.execute(path);
+ }
+ }
- private void openFile(String path) {
- Intent intent = new Intent(Intent.ACTION_VIEW);
- File file = null;
- Uri contentUri = null;
- if (path.startsWith("file://")) {
- path = path.substring("file://".length());
- file = new File(path);
- contentUri = FileProvider.getUriForFile(mContext, "org.linphone.provider", file);
- } else if (path.startsWith("content://")) {
- contentUri = Uri.parse(path);
- } else {
- file = new File(path);
- try {
- contentUri = FileProvider.getUriForFile(mContext, "org.linphone.provider", file);
- } catch (Exception e) {
- contentUri = Uri.parse(path);
- }
- }
- String type = null;
- String extension = MimeTypeMap.getFileExtensionFromUrl(contentUri.toString());
- if (extension != null) {
- type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
- }
- if (type != null) {
- intent.setDataAndType(contentUri, type);
- } else {
- intent.setDataAndType(contentUri, "*/*");
- }
- intent.addFlags(FLAG_GRANT_READ_URI_PERMISSION);
- mContext.startActivity(intent);
- }
+ private void openFile(String path) {
+ Intent intent = new Intent(Intent.ACTION_VIEW);
+ File file = null;
+ Uri contentUri = null;
+ if (path.startsWith("file://")) {
+ path = path.substring("file://".length());
+ file = new File(path);
+ contentUri = FileProvider.getUriForFile(mContext, "org.linphone.provider", file);
+ } else if (path.startsWith("content://")) {
+ contentUri = Uri.parse(path);
+ } else {
+ file = new File(path);
+ try {
+ contentUri = FileProvider.getUriForFile(mContext, "org.linphone.provider", file);
+ } catch (Exception e) {
+ contentUri = Uri.parse(path);
+ }
+ }
+ String type = null;
+ String extension = MimeTypeMap.getFileExtensionFromUrl(contentUri.toString());
+ if (extension != null) {
+ type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
+ }
+ if (type != null) {
+ intent.setDataAndType(contentUri, type);
+ } else {
+ intent.setDataAndType(contentUri, "*/*");
+ }
+ intent.addFlags(FLAG_GRANT_READ_URI_PERMISSION);
+ mContext.startActivity(intent);
+ }
- private void displayAttachedFile(ChatMessage message, ChatBubbleViewHolder holder) {
- holder.fileName.setVisibility(View.VISIBLE);
+ private void displayAttachedFile(ChatMessage message, ChatBubbleViewHolder holder) {
+ holder.fileName.setVisibility(View.VISIBLE);
- String appData = message.getAppdata();
- if (appData != null) {
- holder.fileName.setText(LinphoneUtils.getNameFromFilePath(appData));
- if (LinphoneUtils.isExtensionImage(appData)) {
- holder.messageImage.setVisibility(View.VISIBLE);
- loadBitmap(appData, holder.messageImage);
- holder.messageImage.setTag(appData);
- } else {
- holder.openFileButton.setVisibility(View.VISIBLE);
- holder.openFileButton.setTag(appData);
- holder.openFileButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- openFile((String) v.getTag());
- }
- });
- }
- }
- }
+ String appData = message.getAppdata();
+ if (appData != null) {
+ holder.fileName.setText(LinphoneUtils.getNameFromFilePath(appData));
+ if (LinphoneUtils.isExtensionImage(appData)) {
+ holder.messageImage.setVisibility(View.VISIBLE);
+ loadBitmap(appData, holder.messageImage);
+ holder.messageImage.setTag(appData);
+ } else {
+ holder.openFileButton.setVisibility(View.VISIBLE);
+ holder.openFileButton.setTag(appData);
+ holder.openFileButton.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ openFile((String) v.getTag());
+ }
+ });
+ }
+ }
+ }
- /*
- * Bitmap related classes and methods
- */
+ /*
+ * Bitmap related classes and methods
+ */
- private class BitmapWorkerTask extends AsyncTask {
- private static final int SIZE_SMALL = 500;
- private final WeakReference imageViewReference;
- public String path;
+ private class BitmapWorkerTask extends AsyncTask {
+ private static final int SIZE_SMALL = 500;
+ private final WeakReference imageViewReference;
+ public String path;
- public BitmapWorkerTask(ImageView imageView) {
- path = null;
- // Use a WeakReference to ensure the ImageView can be garbage collected
- imageViewReference = new WeakReference(imageView);
- }
+ public BitmapWorkerTask(ImageView imageView) {
+ path = null;
+ // Use a WeakReference to ensure the ImageView can be garbage collected
+ imageViewReference = new WeakReference(imageView);
+ }
- // Decode image in background.
- @Override
- protected Bitmap doInBackground(String... params) {
- path = params[0];
- Bitmap bm = null;
- Bitmap thumbnail = null;
- if (LinphoneUtils.isExtensionImage(path)) {
- if (path.startsWith("content")) {
- try {
- bm = MediaStore.Images.Media.getBitmap(mContext.getContentResolver(), Uri.parse(path));
- } catch (FileNotFoundException e) {
- Log.e(e);
- } catch (IOException e) {
- Log.e(e);
- }
- } else {
- bm = BitmapFactory.decodeFile(path);
- }
+ // Decode image in background.
+ @Override
+ protected Bitmap doInBackground(String... params) {
+ path = params[0];
+ Bitmap bm = null;
+ Bitmap thumbnail = null;
+ if (LinphoneUtils.isExtensionImage(path)) {
+ if (path.startsWith("content")) {
+ try {
+ bm = MediaStore.Images.Media.getBitmap(mContext.getContentResolver(), Uri.parse(path));
+ } catch (FileNotFoundException e) {
+ Log.e(e);
+ } catch (IOException e) {
+ Log.e(e);
+ }
+ } else {
+ bm = BitmapFactory.decodeFile(path);
+ }
- // Rotate the bitmap if possible/needed, using EXIF data
- try {
- Bitmap bm_tmp;
- ExifInterface exif = new ExifInterface(path);
- int pictureOrientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
- Matrix matrix = new Matrix();
- if (pictureOrientation == 6) {
- matrix.postRotate(90);
- } else if (pictureOrientation == 3) {
- matrix.postRotate(180);
- } else if (pictureOrientation == 8) {
- matrix.postRotate(270);
- }
- bm_tmp = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
- if (bm_tmp != bm) {
- bm.recycle();
- bm = bm_tmp;
- }
- } catch (Exception e) {
- Log.e(e);
- }
+ // Rotate the bitmap if possible/needed, using EXIF data
+ try {
+ Bitmap bm_tmp;
+ ExifInterface exif = new ExifInterface(path);
+ int pictureOrientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
+ Matrix matrix = new Matrix();
+ if (pictureOrientation == 6) {
+ matrix.postRotate(90);
+ } else if (pictureOrientation == 3) {
+ matrix.postRotate(180);
+ } else if (pictureOrientation == 8) {
+ matrix.postRotate(270);
+ }
+ bm_tmp = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
+ if (bm_tmp != bm) {
+ bm.recycle();
+ bm = bm_tmp;
+ }
+ } catch (Exception e) {
+ Log.e(e);
+ }
- if (bm != null) {
- thumbnail = ThumbnailUtils.extractThumbnail(bm, SIZE_SMALL, SIZE_SMALL);
- bm.recycle();
- }
- return thumbnail;
- } else {
- return mDefaultBitmap;
- }
- }
+ if (bm != null) {
+ thumbnail = ThumbnailUtils.extractThumbnail(bm, SIZE_SMALL, SIZE_SMALL);
+ bm.recycle();
+ }
+ return thumbnail;
+ } else {
+ return mDefaultBitmap;
+ }
+ }
- // Once complete, see if ImageView is still around and set bitmap.
- @Override
- protected void onPostExecute(Bitmap bitmap) {
- if (isCancelled()) {
- bitmap = null;
- }
- if (imageViewReference != null && bitmap != null) {
- final ImageView imageView = imageViewReference.get();
- final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
- if (this == bitmapWorkerTask && imageView != null) {
- imageView.setImageBitmap(bitmap);
- imageView.setTag(path);
- imageView.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- openFile((String)v.getTag());
- }
- });
- }
- }
- }
- }
+ // Once complete, see if ImageView is still around and set bitmap.
+ @Override
+ protected void onPostExecute(Bitmap bitmap) {
+ if (isCancelled()) {
+ bitmap = null;
+ }
+ if (imageViewReference != null && bitmap != null) {
+ final ImageView imageView = imageViewReference.get();
+ final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
+ if (this == bitmapWorkerTask && imageView != null) {
+ imageView.setImageBitmap(bitmap);
+ imageView.setTag(path);
+ imageView.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ openFile((String) v.getTag());
+ }
+ });
+ }
+ }
+ }
+ }
- class AsyncBitmap extends BitmapDrawable {
- private final WeakReference bitmapWorkerTaskReference;
+ class AsyncBitmap extends BitmapDrawable {
+ private final WeakReference bitmapWorkerTaskReference;
- public AsyncBitmap(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) {
- super(res, bitmap);
- bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
- }
+ public AsyncBitmap(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) {
+ super(res, bitmap);
+ bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
+ }
- public BitmapWorkerTask getBitmapWorkerTask() {
- return bitmapWorkerTaskReference.get();
- }
- }
+ public BitmapWorkerTask getBitmapWorkerTask() {
+ return bitmapWorkerTaskReference.get();
+ }
+ }
- private boolean cancelPotentialWork(String path, ImageView imageView) {
- final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
+ private boolean cancelPotentialWork(String path, ImageView imageView) {
+ final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
- if (bitmapWorkerTask != null) {
- final String bitmapData = bitmapWorkerTask.path;
- // If bitmapData is not yet set or it differs from the new data
- if (bitmapData == null || bitmapData != path) {
- // Cancel previous task
- bitmapWorkerTask.cancel(true);
- } else {
- // The same work is already in progress
- return false;
- }
- }
- // No task associated with the ImageView, or an existing task was cancelled
- return true;
- }
+ if (bitmapWorkerTask != null) {
+ final String bitmapData = bitmapWorkerTask.path;
+ // If bitmapData is not yet set or it differs from the new data
+ if (bitmapData == null || bitmapData != path) {
+ // Cancel previous task
+ bitmapWorkerTask.cancel(true);
+ } else {
+ // The same work is already in progress
+ return false;
+ }
+ }
+ // No task associated with the ImageView, or an existing task was cancelled
+ return true;
+ }
- private BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
- if (imageView != null) {
- final Drawable drawable = imageView.getDrawable();
- if (drawable instanceof AsyncBitmap) {
- final AsyncBitmap asyncDrawable = (AsyncBitmap) drawable;
- return asyncDrawable.getBitmapWorkerTask();
- }
- }
- return null;
- }
+ private BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
+ if (imageView != null) {
+ final Drawable drawable = imageView.getDrawable();
+ if (drawable instanceof AsyncBitmap) {
+ final AsyncBitmap asyncDrawable = (AsyncBitmap) drawable;
+ return asyncDrawable.getBitmapWorkerTask();
+ }
+ }
+ return null;
+ }
}
diff --git a/src/android/org/linphone/chat/ChatListFragment.java b/src/android/org/linphone/chat/ChatListFragment.java
index 2f3a0277f..e9db9f8b6 100644
--- a/src/android/org/linphone/chat/ChatListFragment.java
+++ b/src/android/org/linphone/chat/ChatListFragment.java
@@ -54,201 +54,201 @@ import static org.linphone.fragments.FragmentsAvailable.CHAT_LIST;
public class ChatListFragment extends Fragment implements ContactsUpdatedListener, ChatRoomViewHolder.ClickListener, SelectableHelper.DeleteListener {
- private RecyclerView mChatRoomsList;
- private ImageView mNewDiscussionButton, mBackToCallButton;
- private ChatRoomsAdapter mChatRoomsAdapter;
- private CoreListenerStub mListener;
- private RelativeLayout mWaitLayout;
- private int mChatRoomDeletionPendingCount;
- private ChatRoomListenerStub mChatRoomListener;
- private Context mContext;
- public List mRooms;
- private SelectableHelper mSelectionHelper;
+ private RecyclerView mChatRoomsList;
+ private ImageView mNewDiscussionButton, mBackToCallButton;
+ private ChatRoomsAdapter mChatRoomsAdapter;
+ private CoreListenerStub mListener;
+ private RelativeLayout mWaitLayout;
+ private int mChatRoomDeletionPendingCount;
+ private ChatRoomListenerStub mChatRoomListener;
+ private Context mContext;
+ public List mRooms;
+ private SelectableHelper mSelectionHelper;
- @Override
- public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ @Override
+ public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- mRooms = new ArrayList<>(Arrays.asList(LinphoneManager.getLc().getChatRooms()));
+ super.onCreate(savedInstanceState);
+ mRooms = new ArrayList<>(Arrays.asList(LinphoneManager.getLc().getChatRooms()));
- mContext = getActivity().getApplicationContext();
- View view = inflater.inflate(R.layout.chatlist, container, false);
+ mContext = getActivity().getApplicationContext();
+ View view = inflater.inflate(R.layout.chatlist, container, false);
- mChatRoomsList = view.findViewById(R.id.chatList);
- mWaitLayout = view.findViewById(R.id.waitScreen);
- mNewDiscussionButton = view.findViewById(R.id.new_discussion);
- mBackToCallButton = view.findViewById(R.id.back_in_call);
+ mChatRoomsList = view.findViewById(R.id.chatList);
+ mWaitLayout = view.findViewById(R.id.waitScreen);
+ mNewDiscussionButton = view.findViewById(R.id.new_discussion);
+ mBackToCallButton = view.findViewById(R.id.back_in_call);
- mSelectionHelper = new SelectableHelper(view, this);
- mChatRoomsAdapter = new ChatRoomsAdapter(mContext, R.layout.chatlist_cell, mRooms,this, mSelectionHelper);
+ mSelectionHelper = new SelectableHelper(view, this);
+ mChatRoomsAdapter = new ChatRoomsAdapter(mContext, R.layout.chatlist_cell, mRooms, this, mSelectionHelper);
- mChatRoomsList.setAdapter(mChatRoomsAdapter);
- mSelectionHelper.setAdapter(mChatRoomsAdapter);
- mSelectionHelper.setDialogMessage(R.string.chat_room_delete_dialog);
+ mChatRoomsList.setAdapter(mChatRoomsAdapter);
+ mSelectionHelper.setAdapter(mChatRoomsAdapter);
+ mSelectionHelper.setDialogMessage(R.string.chat_room_delete_dialog);
- RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(mContext);
- mChatRoomsList.setLayoutManager(layoutManager);
+ RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(mContext);
+ mChatRoomsList.setLayoutManager(layoutManager);
- DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(mChatRoomsList.getContext(),
- ((LinearLayoutManager) layoutManager).getOrientation());
- dividerItemDecoration.setDrawable(getActivity().getApplicationContext().getResources().getDrawable(R.drawable.divider));
- mChatRoomsList.addItemDecoration(dividerItemDecoration);
+ DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(mChatRoomsList.getContext(),
+ ((LinearLayoutManager) layoutManager).getOrientation());
+ dividerItemDecoration.setDrawable(getActivity().getApplicationContext().getResources().getDrawable(R.drawable.divider));
+ mChatRoomsList.addItemDecoration(dividerItemDecoration);
- mWaitLayout.setVisibility(View.GONE);
+ mWaitLayout.setVisibility(View.GONE);
- mNewDiscussionButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- LinphoneActivity.instance().goToChatCreator(null, null, null, false, null);
- }
- });
+ mNewDiscussionButton.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ LinphoneActivity.instance().goToChatCreator(null, null, null, false, null);
+ }
+ });
- mBackToCallButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- LinphoneActivity.instance().resetClassicMenuLayoutAndGoBackToCallIfStillRunning();
- }
- });
+ mBackToCallButton.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ LinphoneActivity.instance().resetClassicMenuLayoutAndGoBackToCallIfStillRunning();
+ }
+ });
- mListener = new CoreListenerStub() {
- @Override
- public void onMessageReceived(Core lc, ChatRoom cr, ChatMessage message) {
- refreshChatRoomsList();
- }
+ mListener = new CoreListenerStub() {
+ @Override
+ public void onMessageReceived(Core lc, ChatRoom cr, ChatMessage message) {
+ refreshChatRoomsList();
+ }
- @Override
- public void onChatRoomStateChanged(Core lc, ChatRoom cr, ChatRoom.State state) {
- if (state == ChatRoom.State.Created) {
- refreshChatRoomsList();
- }
- }
- };
+ @Override
+ public void onChatRoomStateChanged(Core lc, ChatRoom cr, ChatRoom.State state) {
+ if (state == ChatRoom.State.Created) {
+ refreshChatRoomsList();
+ }
+ }
+ };
- mChatRoomListener = new ChatRoomListenerStub() {
- @Override
- public void onStateChanged(ChatRoom room, ChatRoom.State state) {
- super.onStateChanged(room, state);
- if (state == ChatRoom.State.Deleted || state == ChatRoom.State.TerminationFailed) {
- mChatRoomDeletionPendingCount -= 1;
+ mChatRoomListener = new ChatRoomListenerStub() {
+ @Override
+ public void onStateChanged(ChatRoom room, ChatRoom.State state) {
+ super.onStateChanged(room, state);
+ if (state == ChatRoom.State.Deleted || state == ChatRoom.State.TerminationFailed) {
+ mChatRoomDeletionPendingCount -= 1;
- if (state == ChatRoom.State.TerminationFailed) {
- //TODO error message
- }
+ if (state == ChatRoom.State.TerminationFailed) {
+ //TODO error message
+ }
- if (mChatRoomDeletionPendingCount == 0) {
- mWaitLayout.setVisibility(View.GONE);
- refreshChatRoomsList();
- }
- }
- }
- };
- return view;
- }
+ if (mChatRoomDeletionPendingCount == 0) {
+ mWaitLayout.setVisibility(View.GONE);
+ refreshChatRoomsList();
+ }
+ }
+ }
+ };
+ return view;
+ }
- @Override
- public void onItemClicked(int position) {
- if (mChatRoomsAdapter.isEditionEnabled()) {
- mChatRoomsAdapter.toggleSelection(position);
- } else {
- ChatRoom room = (ChatRoom) mChatRoomsAdapter.getItem(position);
- LinphoneActivity.instance().goToChat(room.getPeerAddress().asString(),null);
- }
- }
+ @Override
+ public void onItemClicked(int position) {
+ if (mChatRoomsAdapter.isEditionEnabled()) {
+ mChatRoomsAdapter.toggleSelection(position);
+ } else {
+ ChatRoom room = (ChatRoom) mChatRoomsAdapter.getItem(position);
+ LinphoneActivity.instance().goToChat(room.getPeerAddress().asString(), null);
+ }
+ }
- @Override
- public boolean onItemLongClicked(int position) {
- if (!mChatRoomsAdapter.isEditionEnabled()) {
- mSelectionHelper.enterEditionMode();
- }
- mChatRoomsAdapter.toggleSelection(position);
- return true;
- }
+ @Override
+ public boolean onItemLongClicked(int position) {
+ if (!mChatRoomsAdapter.isEditionEnabled()) {
+ mSelectionHelper.enterEditionMode();
+ }
+ mChatRoomsAdapter.toggleSelection(position);
+ return true;
+ }
- private void refreshChatRoomsList() {
- mChatRoomsAdapter.refresh();
- //mNoChatHistory.setVisibility(mChatRoomsAdapter.getItemCount() == 0 ? View.VISIBLE : View.GONE);
- }
+ private void refreshChatRoomsList() {
+ mChatRoomsAdapter.refresh();
+ //mNoChatHistory.setVisibility(mChatRoomsAdapter.getItemCount() == 0 ? View.VISIBLE : View.GONE);
+ }
- public void displayFirstChat() {
- ChatRoomsAdapter adapter = (ChatRoomsAdapter)mChatRoomsList.getAdapter();
- if (adapter != null && adapter.getItemCount() > 0) {
- ChatRoom room = (ChatRoom) adapter.getItem(0);
- LinphoneActivity.instance().goToChat(room.getPeerAddress().asStringUriOnly(), null);
- } else {
- LinphoneActivity.instance().displayEmptyFragment();
- }
- }
+ public void displayFirstChat() {
+ ChatRoomsAdapter adapter = (ChatRoomsAdapter) mChatRoomsList.getAdapter();
+ if (adapter != null && adapter.getItemCount() > 0) {
+ ChatRoom room = (ChatRoom) adapter.getItem(0);
+ LinphoneActivity.instance().goToChat(room.getPeerAddress().asStringUriOnly(), null);
+ } else {
+ LinphoneActivity.instance().displayEmptyFragment();
+ }
+ }
- @Override
- public void onResume() {
- super.onResume();
- ContactsManager.addContactsListener(this);
+ @Override
+ public void onResume() {
+ super.onResume();
+ ContactsManager.addContactsListener(this);
- if (LinphoneManager.getLc().getCallsNb() > 0) {
- mBackToCallButton.setVisibility(View.VISIBLE);
- } else {
- mBackToCallButton.setVisibility(View.GONE);
- }
+ if (LinphoneManager.getLc().getCallsNb() > 0) {
+ mBackToCallButton.setVisibility(View.VISIBLE);
+ } else {
+ mBackToCallButton.setVisibility(View.GONE);
+ }
- if (LinphoneActivity.isInstanciated()) {
- LinphoneActivity.instance().selectMenu(FragmentsAvailable.CHAT_LIST);
- LinphoneActivity.instance().hideTabBar(false);
- }
+ if (LinphoneActivity.isInstanciated()) {
+ LinphoneActivity.instance().selectMenu(FragmentsAvailable.CHAT_LIST);
+ LinphoneActivity.instance().hideTabBar(false);
+ }
- Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- if (lc != null) {
- lc.addListener(mListener);
- }
+ Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ if (lc != null) {
+ lc.addListener(mListener);
+ }
- refreshChatRoomsList();
- }
+ refreshChatRoomsList();
+ }
- @Override
- public void onPause() {
- Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- if (lc != null) {
- lc.removeListener(mListener);
- }
- ContactsManager.removeContactsListener(this);
- mChatRoomsAdapter.clear();
- super.onPause();
- }
+ @Override
+ public void onPause() {
+ Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ if (lc != null) {
+ lc.removeListener(mListener);
+ }
+ ContactsManager.removeContactsListener(this);
+ mChatRoomsAdapter.clear();
+ super.onPause();
+ }
- @Override
- public void onDeleteSelection(Object[] objectsToDelete) {
- Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- mChatRoomDeletionPendingCount = objectsToDelete.length;
- for (Object obj : objectsToDelete) {
- ChatRoom room = (ChatRoom)obj;
+ @Override
+ public void onDeleteSelection(Object[] objectsToDelete) {
+ Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ mChatRoomDeletionPendingCount = objectsToDelete.length;
+ for (Object obj : objectsToDelete) {
+ ChatRoom room = (ChatRoom) obj;
- for (EventLog eventLog : room.getHistoryEvents(0)) {
- if (eventLog.getType() == EventLog.Type.ConferenceChatMessage) {
- ChatMessage message = eventLog.getChatMessage();
- if (message.getAppdata() != null && !message.isOutgoing()) {
- File file = new File(message.getAppdata());
- if (file.exists()) {
- file.delete(); // Delete downloaded file from incoming message that will be deleted
- }
- }
- }
- }
+ for (EventLog eventLog : room.getHistoryEvents(0)) {
+ if (eventLog.getType() == EventLog.Type.ConferenceChatMessage) {
+ ChatMessage message = eventLog.getChatMessage();
+ if (message.getAppdata() != null && !message.isOutgoing()) {
+ File file = new File(message.getAppdata());
+ if (file.exists()) {
+ file.delete(); // Delete downloaded file from incoming message that will be deleted
+ }
+ }
+ }
+ }
- room.addListener(mChatRoomListener);
- lc.deleteChatRoom(room);
- }
- if (mChatRoomDeletionPendingCount > 0) {
- mWaitLayout.setVisibility(View.VISIBLE);
- }
- }
+ room.addListener(mChatRoomListener);
+ lc.deleteChatRoom(room);
+ }
+ if (mChatRoomDeletionPendingCount > 0) {
+ mWaitLayout.setVisibility(View.VISIBLE);
+ }
+ }
- @Override
- public void onContactsUpdated() {
- if (!LinphoneActivity.isInstanciated() || LinphoneActivity.instance().getCurrentFragment() != CHAT_LIST)
- return;
+ @Override
+ public void onContactsUpdated() {
+ if (!LinphoneActivity.isInstanciated() || LinphoneActivity.instance().getCurrentFragment() != CHAT_LIST)
+ return;
- ChatRoomsAdapter adapter = (ChatRoomsAdapter) mChatRoomsList.getAdapter();
- if (adapter != null) {
- adapter.notifyDataSetChanged();
- }
- }
+ ChatRoomsAdapter adapter = (ChatRoomsAdapter) mChatRoomsList.getAdapter();
+ if (adapter != null) {
+ adapter.notifyDataSetChanged();
+ }
+ }
}
\ No newline at end of file
diff --git a/src/android/org/linphone/chat/ChatRoomViewHolder.java b/src/android/org/linphone/chat/ChatRoomViewHolder.java
index ab3d5c78f..4dc034cc0 100644
--- a/src/android/org/linphone/chat/ChatRoomViewHolder.java
+++ b/src/android/org/linphone/chat/ChatRoomViewHolder.java
@@ -53,7 +53,7 @@ public class ChatRoomViewHolder extends RecyclerView.ViewHolder implements View.
public ChatRoom mRoom;
private ClickListener mListener;
- public ChatRoomViewHolder(Context context,View itemView, ClickListener listener) {
+ public ChatRoomViewHolder(Context context, View itemView, ClickListener listener) {
super(itemView);
mDefaultBitmap = ContactsManager.getInstance().getDefaultAvatarBitmap();
@@ -76,7 +76,7 @@ public class ChatRoomViewHolder extends RecyclerView.ViewHolder implements View.
public void bindChatRoom(ChatRoom room) {
mRoom = room;
lastMessageSenderView.setText(getSender(mRoom));
- lastMessageView.setText(mRoom.getLastMessageInHistory() != null ? mRoom.getLastMessageInHistory().getTextContent(): "");
+ lastMessageView.setText(mRoom.getLastMessageInHistory() != null ? mRoom.getLastMessageInHistory().getTextContent() : "");
date.setText(mRoom.getLastMessageInHistory() != null ? LinphoneUtils.timestampToHumanDate(mContext, mRoom.getLastUpdateTime(), R.string.messages_list_date_format) : "");
displayName.setText(getContact(mRoom));
unreadMessages.setText(String.valueOf(LinphoneManager.getInstance().getUnreadCountForChatRoom(mRoom)));
@@ -96,13 +96,13 @@ public class ChatRoomViewHolder extends RecyclerView.ViewHolder implements View.
return false;
}
- public String getSender(ChatRoom mRoom){
+ public String getSender(ChatRoom mRoom) {
if (mRoom.getLastMessageInHistory() != null) {
LinphoneContact contact = ContactsManager.getInstance().findContactFromAddress(mRoom.getLastMessageInHistory().getFromAddress());
if (contact != null) {
return (contact.getFullName() + mContext.getString(R.string.separator));
}
- return (LinphoneUtils.getAddressDisplayName(mRoom.getLastMessageInHistory().getFromAddress()) + mContext.getString(R.string.separator));
+ return (LinphoneUtils.getAddressDisplayName(mRoom.getLastMessageInHistory().getFromAddress()) + mContext.getString(R.string.separator));
}
return null;
}
@@ -146,6 +146,7 @@ public class ChatRoomViewHolder extends RecyclerView.ViewHolder implements View.
public interface ClickListener {
void onItemClicked(int position);
+
boolean onItemLongClicked(int position);
}
}
\ No newline at end of file
diff --git a/src/android/org/linphone/chat/ChatRoomsAdapter.java b/src/android/org/linphone/chat/ChatRoomsAdapter.java
index 0489c79cc..7653da095 100644
--- a/src/android/org/linphone/chat/ChatRoomsAdapter.java
+++ b/src/android/org/linphone/chat/ChatRoomsAdapter.java
@@ -36,69 +36,69 @@ import java.util.Comparator;
import java.util.List;
public class ChatRoomsAdapter extends SelectableAdapter {
- private Context mContext;
- public List mRooms;
- private int mItemResource;
- private ChatRoomViewHolder.ClickListener mClickListener;
+ private Context mContext;
+ public List mRooms;
+ private int mItemResource;
+ private ChatRoomViewHolder.ClickListener mClickListener;
- public ChatRoomsAdapter(Context context, int itemResource, List rooms, ChatRoomViewHolder.ClickListener clickListener, SelectableHelper helper) {
- super(helper);
- mClickListener = clickListener;
- mRooms = rooms;
- mContext = context;
- mItemResource = itemResource;
- }
+ public ChatRoomsAdapter(Context context, int itemResource, List rooms, ChatRoomViewHolder.ClickListener clickListener, SelectableHelper helper) {
+ super(helper);
+ mClickListener = clickListener;
+ mRooms = rooms;
+ mContext = context;
+ mItemResource = itemResource;
+ }
- @Override
- public ChatRoomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
- View view = LayoutInflater.from(parent.getContext())
- .inflate(mItemResource, parent, false);
- return new ChatRoomViewHolder(mContext, view, mClickListener);
- }
+ @Override
+ public ChatRoomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
+ View view = LayoutInflater.from(parent.getContext())
+ .inflate(mItemResource, parent, false);
+ return new ChatRoomViewHolder(mContext, view, mClickListener);
+ }
- @Override
- public void onBindViewHolder(ChatRoomViewHolder holder, int position) {
- ChatRoom room = mRooms.get(position);
- holder.delete.setVisibility(isEditionEnabled() ? View.VISIBLE : View.INVISIBLE);
- holder.unreadMessages.setVisibility(isEditionEnabled() ? View.INVISIBLE : (room.getUnreadMessagesCount() > 0 ? View.VISIBLE : View.INVISIBLE));
- holder.delete.setChecked(isSelected(position));
- holder.bindChatRoom(room);
- }
+ @Override
+ public void onBindViewHolder(ChatRoomViewHolder holder, int position) {
+ ChatRoom room = mRooms.get(position);
+ holder.delete.setVisibility(isEditionEnabled() ? View.VISIBLE : View.INVISIBLE);
+ holder.unreadMessages.setVisibility(isEditionEnabled() ? View.INVISIBLE : (room.getUnreadMessagesCount() > 0 ? View.VISIBLE : View.INVISIBLE));
+ holder.delete.setChecked(isSelected(position));
+ holder.bindChatRoom(room);
+ }
- public void refresh() {
- mRooms = new ArrayList<>(Arrays.asList(LinphoneManager.getLc().getChatRooms()));
- Collections.sort(mRooms, new Comparator() {
- public int compare(ChatRoom cr1, ChatRoom cr2) {
- long timeDiff = cr1.getLastUpdateTime() - cr2.getLastUpdateTime();
- if (timeDiff > 0) return -1;
- else if (timeDiff == 0) return 0;
- return 1;
- }
- });
- notifyDataSetChanged();
- }
+ public void refresh() {
+ mRooms = new ArrayList<>(Arrays.asList(LinphoneManager.getLc().getChatRooms()));
+ Collections.sort(mRooms, new Comparator() {
+ public int compare(ChatRoom cr1, ChatRoom cr2) {
+ long timeDiff = cr1.getLastUpdateTime() - cr2.getLastUpdateTime();
+ if (timeDiff > 0) return -1;
+ else if (timeDiff == 0) return 0;
+ return 1;
+ }
+ });
+ notifyDataSetChanged();
+ }
- public void clear() {
- mRooms.clear();
- notifyDataSetChanged();
- }
+ public void clear() {
+ mRooms.clear();
+ notifyDataSetChanged();
+ }
- /**
- * Adapter's methods
- */
+ /**
+ * Adapter's methods
+ */
- @Override
- public int getItemCount() {
- return mRooms.size();
- }
+ @Override
+ public int getItemCount() {
+ return mRooms.size();
+ }
- @Override
- public Object getItem(int position) {
- return mRooms.get(position);
- }
+ @Override
+ public Object getItem(int position) {
+ return mRooms.get(position);
+ }
- @Override
- public long getItemId(int position) {
- return position;
- }
+ @Override
+ public long getItemId(int position) {
+ return position;
+ }
}
diff --git a/src/android/org/linphone/chat/GroupChatFragment.java b/src/android/org/linphone/chat/GroupChatFragment.java
index defc4a294..40a83b2e5 100644
--- a/src/android/org/linphone/chat/GroupChatFragment.java
+++ b/src/android/org/linphone/chat/GroupChatFragment.java
@@ -85,852 +85,856 @@ import java.util.List;
import static android.content.Context.INPUT_METHOD_SERVICE;
import static org.linphone.fragments.FragmentsAvailable.CHAT;
-public class GroupChatFragment extends Fragment implements ChatRoomListener, ContactsUpdatedListener, ChatBubbleViewHolder.ClickListener ,SelectableHelper.DeleteListener {
- private static final int ADD_PHOTO = 1337;
+public class GroupChatFragment extends Fragment implements ChatRoomListener, ContactsUpdatedListener, ChatBubbleViewHolder.ClickListener, SelectableHelper.DeleteListener {
+ private static final int ADD_PHOTO = 1337;
- private ImageView mBackButton, mCallButton, mBackToCallButton, mGroupInfosButton;
- private ImageView mAttachImageButton, mSendMessageButton;
- private TextView mRoomLabel, mParticipantsLabel, mRemoteComposing;
- private EditText mMessageTextToSend;
- private LayoutInflater mInflater;
- private RecyclerView mChatEventsList;
- private LinearLayout mFilesUploadLayout;
- private SelectableHelper mSelectionHelper;
- private Context mContext;
- private ViewTreeObserver.OnGlobalLayoutListener mKeyboardListener;
- private Uri mImageToUploadUri;
- private ChatEventsAdapter mEventsAdapter;
- private String mRemoteSipUri;
- private Address mRemoteSipAddress, mRemoteParticipantAddress;
- private ChatRoom mChatRoom;
- private ArrayList mParticipants;
- private LinearLayoutManager layoutManager;
- private int mContextMenuMessagePosition;
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- // Retain the fragment across configuration changes
- setRetainInstance(true);
+ private ImageView mBackButton, mCallButton, mBackToCallButton, mGroupInfosButton;
+ private ImageView mAttachImageButton, mSendMessageButton;
+ private TextView mRoomLabel, mParticipantsLabel, mRemoteComposing;
+ private EditText mMessageTextToSend;
+ private LayoutInflater mInflater;
+ private RecyclerView mChatEventsList;
+ private LinearLayout mFilesUploadLayout;
+ private SelectableHelper mSelectionHelper;
+ private Context mContext;
+ private ViewTreeObserver.OnGlobalLayoutListener mKeyboardListener;
+ private Uri mImageToUploadUri;
+ private ChatEventsAdapter mEventsAdapter;
+ private String mRemoteSipUri;
+ private Address mRemoteSipAddress, mRemoteParticipantAddress;
+ private ChatRoom mChatRoom;
+ private ArrayList mParticipants;
+ private LinearLayoutManager layoutManager;
+ private int mContextMenuMessagePosition;
- if (getArguments() != null && getArguments().getString("SipUri") != null) {
- mRemoteSipUri = getArguments().getString("SipUri");
- mRemoteSipAddress = LinphoneManager.getLc().createAddress(mRemoteSipUri);
- }
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ // Retain the fragment across configuration changes
+ setRetainInstance(true);
- mContext = getActivity().getApplicationContext();
- View view = inflater.inflate(R.layout.chat, container, false);
+ if (getArguments() != null && getArguments().getString("SipUri") != null) {
+ mRemoteSipUri = getArguments().getString("SipUri");
+ mRemoteSipAddress = LinphoneManager.getLc().createAddress(mRemoteSipUri);
+ }
+
+ mContext = getActivity().getApplicationContext();
+ View view = inflater.inflate(R.layout.chat, container, false);
- mBackButton = view.findViewById(R.id.back);
- mBackButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- LinphoneActivity.instance().goToChatList();
- }
- });
+ mBackButton = view.findViewById(R.id.back);
+ mBackButton.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ LinphoneActivity.instance().goToChatList();
+ }
+ });
- mCallButton = view.findViewById(R.id.start_call);
- mCallButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- LinphoneActivity.instance().setAddresGoToDialerAndCall(mRemoteParticipantAddress.asString(), null, null);
- }
- });
+ mCallButton = view.findViewById(R.id.start_call);
+ mCallButton.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ LinphoneActivity.instance().setAddresGoToDialerAndCall(mRemoteParticipantAddress.asString(), null, null);
+ }
+ });
- mBackToCallButton = view.findViewById(R.id.back_to_call);
- mBackToCallButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- LinphoneActivity.instance().resetClassicMenuLayoutAndGoBackToCallIfStillRunning();
- }
- });
+ mBackToCallButton = view.findViewById(R.id.back_to_call);
+ mBackToCallButton.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ LinphoneActivity.instance().resetClassicMenuLayoutAndGoBackToCallIfStillRunning();
+ }
+ });
- mGroupInfosButton = view.findViewById(R.id.group_infos);
- mGroupInfosButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- if (mChatRoom == null) return;
- ArrayList participants = new ArrayList<>();
- for (Participant p : mChatRoom.getParticipants()) {
- Address a = p.getAddress();
- LinphoneContact c = ContactsManager.getInstance().findContactFromAddress(a);
- if (c == null) {
- c = new LinphoneContact();
- String displayName = LinphoneUtils.getAddressDisplayName(a);
- c.setFullName(displayName);
- }
- ContactAddress ca = new ContactAddress(c, a.asString(), "", c.isFriend(), p.isAdmin());
- participants.add(ca);
- }
- LinphoneActivity.instance().goToChatGroupInfos(mRemoteSipAddress.asString(), participants, mChatRoom.getSubject(), mChatRoom.getMe() != null ? mChatRoom.getMe().isAdmin() : false, false, null);
- }
- });
+ mGroupInfosButton = view.findViewById(R.id.group_infos);
+ mGroupInfosButton.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ if (mChatRoom == null) return;
+ ArrayList participants = new ArrayList<>();
+ for (Participant p : mChatRoom.getParticipants()) {
+ Address a = p.getAddress();
+ LinphoneContact c = ContactsManager.getInstance().findContactFromAddress(a);
+ if (c == null) {
+ c = new LinphoneContact();
+ String displayName = LinphoneUtils.getAddressDisplayName(a);
+ c.setFullName(displayName);
+ }
+ ContactAddress ca = new ContactAddress(c, a.asString(), "", c.isFriend(), p.isAdmin());
+ participants.add(ca);
+ }
+ LinphoneActivity.instance().goToChatGroupInfos(mRemoteSipAddress.asString(), participants, mChatRoom.getSubject(), mChatRoom.getMe() != null ? mChatRoom.getMe().isAdmin() : false, false, null);
+ }
+ });
- mRoomLabel = view.findViewById(R.id.subject);
- mParticipantsLabel = view.findViewById(R.id.participants);
+ mRoomLabel = view.findViewById(R.id.subject);
+ mParticipantsLabel = view.findViewById(R.id.participants);
- mFilesUploadLayout = view.findViewById(R.id.file_upload_layout);
+ mFilesUploadLayout = view.findViewById(R.id.file_upload_layout);
- mAttachImageButton = view.findViewById(R.id.send_picture);
- mAttachImageButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- LinphoneActivity.instance().checkAndRequestPermissionsToSendImage();
- pickFile();
- }
- });
+ mAttachImageButton = view.findViewById(R.id.send_picture);
+ mAttachImageButton.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ LinphoneActivity.instance().checkAndRequestPermissionsToSendImage();
+ pickFile();
+ }
+ });
- mSendMessageButton = view.findViewById(R.id.send_message);
- mSendMessageButton.setEnabled(false);
- mSendMessageButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- sendMessage();
- }
- });
+ mSendMessageButton = view.findViewById(R.id.send_message);
+ mSendMessageButton.setEnabled(false);
+ mSendMessageButton.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ sendMessage();
+ }
+ });
- mMessageTextToSend = view.findViewById(R.id.message);
- mMessageTextToSend.addTextChangedListener(new TextWatcher() {
- @Override
- public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { }
+ mMessageTextToSend = view.findViewById(R.id.message);
+ mMessageTextToSend.addTextChangedListener(new TextWatcher() {
+ @Override
+ public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
+ }
- @Override
- public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
- mSendMessageButton.setEnabled(mMessageTextToSend.getText().length() > 0 || mFilesUploadLayout.getChildCount() > 0);
- if (mChatRoom != null && mMessageTextToSend.getText().length() > 0) {
- mAttachImageButton.setEnabled(false);
- mChatRoom.compose();
- } else {
- mAttachImageButton.setEnabled(true);
- }
- }
+ @Override
+ public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
+ mSendMessageButton.setEnabled(mMessageTextToSend.getText().length() > 0 || mFilesUploadLayout.getChildCount() > 0);
+ if (mChatRoom != null && mMessageTextToSend.getText().length() > 0) {
+ mAttachImageButton.setEnabled(false);
+ mChatRoom.compose();
+ } else {
+ mAttachImageButton.setEnabled(true);
+ }
+ }
- @Override
- public void afterTextChanged(Editable editable) { }
- });
- mMessageTextToSend.clearFocus();
+ @Override
+ public void afterTextChanged(Editable editable) {
+ }
+ });
+ mMessageTextToSend.clearFocus();
- mRemoteComposing = view.findViewById(R.id.remote_composing);
+ mRemoteComposing = view.findViewById(R.id.remote_composing);
- mChatEventsList = view.findViewById(R.id.chat_message_list);
- mSelectionHelper = new SelectableHelper(view, this);
- layoutManager = new LinearLayoutManager(mContext);
- mChatEventsList.setLayoutManager(layoutManager);
+ mChatEventsList = view.findViewById(R.id.chat_message_list);
+ mSelectionHelper = new SelectableHelper(view, this);
+ layoutManager = new LinearLayoutManager(mContext);
+ mChatEventsList.setLayoutManager(layoutManager);
- if (getArguments() != null) {
- String fileSharedUri = getArguments().getString("fileSharedUri");
- if (fileSharedUri != null) {
- if (LinphoneUtils.isExtensionImage(fileSharedUri)) {
- addImageToPendingList(fileSharedUri);
- } else {
- if (fileSharedUri.startsWith("content://") || fileSharedUri.startsWith("file://")) {
- fileSharedUri = LinphoneUtils.getFilePath(getActivity().getApplicationContext(), Uri.parse(fileSharedUri));
- } else if (fileSharedUri.contains("com.android.contacts/contacts/")) {
- fileSharedUri = LinphoneUtils.getCVSPathFromLookupUri(fileSharedUri).toString();
- }
- addFileToPendingList(fileSharedUri);
- }
- }
+ if (getArguments() != null) {
+ String fileSharedUri = getArguments().getString("fileSharedUri");
+ if (fileSharedUri != null) {
+ if (LinphoneUtils.isExtensionImage(fileSharedUri)) {
+ addImageToPendingList(fileSharedUri);
+ } else {
+ if (fileSharedUri.startsWith("content://") || fileSharedUri.startsWith("file://")) {
+ fileSharedUri = LinphoneUtils.getFilePath(getActivity().getApplicationContext(), Uri.parse(fileSharedUri));
+ } else if (fileSharedUri.contains("com.android.contacts/contacts/")) {
+ fileSharedUri = LinphoneUtils.getCVSPathFromLookupUri(fileSharedUri).toString();
+ }
+ addFileToPendingList(fileSharedUri);
+ }
+ }
- if (getArguments().getString("messageDraft") != null)
- mMessageTextToSend.setText(getArguments().getString("messageDraft"));
- }
- return view;
- }
-
- @Override
- public void onResume() {
- super.onResume();
-
- if (LinphoneActivity.isInstanciated()) {
- LinphoneActivity.instance().selectMenu(CHAT);
- }
- ContactsManager.addContactsListener(this);
-
- addVirtualKeyboardVisiblityListener();
- // Force hide keyboard
- getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
- InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(INPUT_METHOD_SERVICE);
- if (getActivity().getCurrentFocus() != null) {
- inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
- }
-
- initChatRoom();
- displayChatRoomHeader();
- displayChatRoomHistory();
- LinphoneManager.getInstance().setCurrentChatRoomAddress(mRemoteSipAddress);
- }
-
- public void changeDisplayedChat(String sipUri) {
- mRemoteSipUri = sipUri;
- mRemoteSipAddress = LinphoneManager.getLc().createAddress(mRemoteSipUri);
-
- initChatRoom();
- displayChatRoomHeader();
- displayChatRoomHistory();
-
- LinphoneManager.getInstance().setCurrentChatRoomAddress(mRemoteSipAddress);
- }
-
- @Override
- public void onPause() {
- ContactsManager.removeContactsListener(this);
- removeVirtualKeyboardVisiblityListener();
- LinphoneManager.getInstance().setCurrentChatRoomAddress(null);
- if (mChatRoom != null) mChatRoom.removeListener(this);
- if (mEventsAdapter != null) mEventsAdapter.clear();
- super.onPause();
- }
-
- @Override
- public void onActivityResult(int requestCode, int resultCode, Intent data) {
- if (data != null) {
- if (requestCode == ADD_PHOTO && resultCode == Activity.RESULT_OK) {
- String fileToUploadPath = null;
- if (data != null && data.getData() != null) {
- if (data.getData().toString().contains("com.android.contacts/contacts/")) {
- if (LinphoneUtils.getCVSPathFromLookupUri(data.getData().toString()) != null) {
- fileToUploadPath = LinphoneUtils.getCVSPathFromLookupUri(data.getData().toString()).toString();
- } else {
- //TODO Error
- return;
- }
- } else {
- fileToUploadPath = LinphoneUtils.getRealPathFromURI(getActivity(), data.getData());
- }
- if (fileToUploadPath == null) {
- fileToUploadPath = data.getData().toString();
- }
- } else if (mImageToUploadUri != null) {
- fileToUploadPath = mImageToUploadUri.getPath();
- }
-
- if (LinphoneUtils.isExtensionImage(fileToUploadPath)) {
- addImageToPendingList(fileToUploadPath);
- } else {
- if (fileToUploadPath.startsWith("content://") || fileToUploadPath.startsWith("file://")) {
- fileToUploadPath = LinphoneUtils.getFilePath(getActivity().getApplicationContext(), Uri.parse(fileToUploadPath));
- } else if (fileToUploadPath.contains("com.android.contacts/contacts/")) {
- fileToUploadPath = LinphoneUtils.getCVSPathFromLookupUri(fileToUploadPath).toString();
- }
- addFileToPendingList(fileToUploadPath);
- }
- } else {
- super.onActivityResult(requestCode, resultCode, data);
- }
- } else {
- if (LinphoneUtils.isExtensionImage(mImageToUploadUri.getPath())) {
- addImageToPendingList(mImageToUploadUri.getPath());
- }
- }
- }
-
- @Override
- public void onDeleteSelection(Object[] objectsToDelete) {
- for (Object obj : objectsToDelete) {
- EventLog eventLog = (EventLog)obj;
- if (eventLog.getType() == EventLog.Type.ConferenceChatMessage) {
- ChatMessage message = eventLog.getChatMessage();
- if (message.getAppdata() != null && !message.isOutgoing()) {
- File file = new File(message.getAppdata());
- if (file.exists()) {
- file.delete(); // Delete downloaded file from incoming message that will be deleted
- }
- }
- }
- eventLog.deleteFromDatabase();
- }
- if (mChatRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt())) {
- mEventsAdapter.refresh(mChatRoom.getHistoryMessageEvents(0));
- } else {
- mEventsAdapter.refresh(mChatRoom.getHistoryEvents(0));
- }
- }
-
-
- @Override
- public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
- super.onCreateContextMenu(menu, v, menuInfo);
-
- ChatBubbleViewHolder holder = (ChatBubbleViewHolder) v.getTag();
- mContextMenuMessagePosition = holder.getAdapterPosition();
-
- EventLog event = (EventLog) mEventsAdapter.getItem(mContextMenuMessagePosition);
- if (event.getType() != EventLog.Type.ConferenceChatMessage) {
- return;
- }
-
- MenuInflater inflater = getActivity().getMenuInflater();
- ChatMessage message = event.getChatMessage();
- if (message.getState() == ChatMessage.State.NotDelivered) {
- inflater.inflate(R.menu.chat_bubble_menu_with_resend, menu);
- } else {
- inflater.inflate(R.menu.chat_bubble_menu, menu);
- }
-
- if (!message.isOutgoing() && mChatRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt())) {
- // Do not show incoming messages IDMN state in 1 to 1 chat room as we don't receive IMDN for them
- menu.removeItem(R.id.imdn_infos);
- }
- if (!message.hasTextContent()) {
- // Do not show copy text option if message doesn't have any text
- menu.removeItem(R.id.copy_text);
- }
- }
-
- @Override
- public boolean onContextItemSelected(MenuItem item) {
-
- EventLog event = (EventLog) mEventsAdapter.getItem(mContextMenuMessagePosition);
-
- if (event.getType() != EventLog.Type.ConferenceChatMessage) {
- return super.onContextItemSelected(item);
- }
-
- ChatMessage message = event.getChatMessage();
- String messageId = message.getMessageId();
-
- if (item.getItemId() == R.id.resend) {
- mEventsAdapter.removeItem(mContextMenuMessagePosition);
- message.resend();
- return true;
- }
- if (item.getItemId() == R.id.imdn_infos) {
- LinphoneActivity.instance().goToChatMessageImdnInfos(getRemoteSipUri(), messageId);
- return true;
- }
- if (item.getItemId() == R.id.copy_text) {
- if (message.hasTextContent()) {
- ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
- ClipData clip = ClipData.newPlainText("Message", message.getTextContent());
- clipboard.setPrimaryClip(clip);
- }
- return true;
- }
- if (item.getItemId() == R.id.delete_message) {
- mChatRoom.deleteMessage(message);
- mEventsAdapter.removeItem(mContextMenuMessagePosition);
- return true;
- }
- return super.onContextItemSelected(item);
- }
-
- /**
- * Keyboard management
- */
-
- private void addVirtualKeyboardVisiblityListener() {
- mKeyboardListener = new ViewTreeObserver.OnGlobalLayoutListener() {
- @Override
- public void onGlobalLayout() {
- Rect visibleArea = new Rect();
- getActivity().getWindow().getDecorView().getWindowVisibleDisplayFrame(visibleArea);
-
- int heightDiff = getActivity().getWindow().getDecorView().getRootView().getHeight() - (visibleArea.bottom - visibleArea.top);
- if (heightDiff > 200) {
- showKeyboardVisibleMode();
- } else {
- hideKeyboardVisibleMode();
- }
- }
- };
- getActivity().getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(mKeyboardListener);
- }
-
- private void removeVirtualKeyboardVisiblityListener() {
- Compatibility.removeGlobalLayoutListener(getActivity().getWindow().getDecorView().getViewTreeObserver(), mKeyboardListener);
- }
-
- public void showKeyboardVisibleMode() {
- LinphoneActivity.instance().hideTabBar(true);
- }
-
- public void hideKeyboardVisibleMode() {
- LinphoneActivity.instance().hideTabBar(false);
- }
-
- /**
- * View initialization
- */
-
- private void setReadOnly() {
- mMessageTextToSend.setEnabled(false);
- mAttachImageButton.setEnabled(false);
- mSendMessageButton.setEnabled(false);
- }
-
- private void getContactsForParticipants() {
- mParticipants = new ArrayList<>();
- if (mChatRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt())) {
- LinphoneContact c = ContactsManager.getInstance().findContactFromAddress(mRemoteParticipantAddress);
- if (c != null) {
- mParticipants.add(c);
- }
- } else {
- int index = 0;
- StringBuilder participantsLabel = new StringBuilder();
- for (Participant p : mChatRoom.getParticipants()) {
- LinphoneContact c = ContactsManager.getInstance().findContactFromAddress(p.getAddress());
- if (c != null) {
- mParticipants.add(c);
- participantsLabel.append(c.getFullName());
- } else {
- String displayName = LinphoneUtils.getAddressDisplayName(p.getAddress());
- participantsLabel.append(displayName);
- }
- index++;
- if (index != mChatRoom.getNbParticipants()) participantsLabel.append(", ");
- }
- mParticipantsLabel.setText(participantsLabel.toString());
- }
-
- if (mEventsAdapter != null) {
- mEventsAdapter.setContacts(mParticipants);
- }
- }
-
- private void initChatRoom() {
- Core core = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- if (mRemoteSipAddress == null || mRemoteSipUri == null || mRemoteSipUri.length() == 0 || core == null) {
- //TODO error
- return;
- }
- Address proxyConfigContact = (core.getDefaultProxyConfig() != null) ? core.getDefaultProxyConfig().getContact() : null;
- if (proxyConfigContact != null) {
- mChatRoom = core.findOneToOneChatRoom(proxyConfigContact, mRemoteSipAddress);
- }
- if (mChatRoom == null) {
- mChatRoom = core.getChatRoomFromUri(mRemoteSipAddress.asStringUriOnly());
- }
- mChatRoom.addListener(this);
- mChatRoom.markAsRead();
- LinphoneManager.getInstance().updateUnreadCountForChatRoom(mChatRoom, 0);
- LinphoneActivity.instance().refreshMissedChatCountDisplay();
-
- mRemoteParticipantAddress = mRemoteSipAddress;
- if (mChatRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt()) && mChatRoom.getParticipants().length > 0) {
- mRemoteParticipantAddress = mChatRoom.getParticipants()[0].getAddress();
- }
-
- getContactsForParticipants();
-
- mRemoteComposing.setVisibility(View.GONE);
- }
-
- private void displayChatRoomHeader() {
- Core core = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- if (core == null || mChatRoom == null) return;
-
- if (core.getCallsNb() > 0) {
- mBackToCallButton.setVisibility(View.VISIBLE);
- } else {
- mBackToCallButton.setVisibility(View.GONE);
- if (mChatRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt())) {
- mCallButton.setVisibility(View.VISIBLE);
- mGroupInfosButton.setVisibility(View.GONE);
- mParticipantsLabel.setVisibility(View.GONE);
-
- if (mParticipants.size() == 0) {
- // Contact not found
- String displayName = LinphoneUtils.getAddressDisplayName(mRemoteParticipantAddress);
- mRoomLabel.setText(displayName);
- } else {
- mRoomLabel.setText(mParticipants.get(0).getFullName());
- }
- } else {
- mCallButton.setVisibility(View.GONE);
- mGroupInfosButton.setVisibility(View.VISIBLE);
- mRoomLabel.setText(mChatRoom.getSubject());
- mParticipantsLabel.setVisibility(View.VISIBLE);
- }
- }
-
- if (mChatRoom.hasBeenLeft()) {
- setReadOnly();
- }
- }
-
- private void displayChatRoomHistory() {
-
- if (mChatRoom == null) return;
- if (mChatRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt())) {
- mEventsAdapter = new ChatEventsAdapter(this, mSelectionHelper, R.layout.chat_bubble, mChatRoom.getHistoryMessageEvents(0), mParticipants, this);
- } else {
- mEventsAdapter = new ChatEventsAdapter(this, mSelectionHelper, R.layout.chat_bubble, mChatRoom.getHistoryEvents(0), mParticipants, this);
- }
- mSelectionHelper.setAdapter(mEventsAdapter);
- mChatEventsList.setAdapter(mEventsAdapter);
- scrollToBottom();
+ if (getArguments().getString("messageDraft") != null)
+ mMessageTextToSend.setText(getArguments().getString("messageDraft"));
+ }
+ return view;
}
- public void scrollToBottom() {
- mChatEventsList.getLayoutManager().scrollToPosition(mEventsAdapter.getCount() - 1);
- }
+ @Override
+ public void onResume() {
+ super.onResume();
- public String getRemoteSipUri() {
- return mRemoteSipUri;
- }
+ if (LinphoneActivity.isInstanciated()) {
+ LinphoneActivity.instance().selectMenu(CHAT);
+ }
+ ContactsManager.addContactsListener(this);
- @Override
- public void onItemClicked(int position) {
- if (mEventsAdapter.isEditionEnabled()) {
- mEventsAdapter.toggleSelection(position);
- }
- }
+ addVirtualKeyboardVisiblityListener();
+ // Force hide keyboard
+ getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
+ InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(INPUT_METHOD_SERVICE);
+ if (getActivity().getCurrentFocus() != null) {
+ inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
+ }
- /**
- * File transfer related
- */
+ initChatRoom();
+ displayChatRoomHeader();
+ displayChatRoomHistory();
+ LinphoneManager.getInstance().setCurrentChatRoomAddress(mRemoteSipAddress);
+ }
- private void pickFile() {
- List cameraIntents = new ArrayList<>();
- Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
- File file = new File(Environment.getExternalStorageDirectory(), getString(R.string.temp_photo_name_with_date).replace("%s", String.valueOf(System.currentTimeMillis())+".jpeg"));
- mImageToUploadUri = Uri.fromFile(file);
- captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageToUploadUri);
- cameraIntents.add(captureIntent);
+ public void changeDisplayedChat(String sipUri) {
+ mRemoteSipUri = sipUri;
+ mRemoteSipAddress = LinphoneManager.getLc().createAddress(mRemoteSipUri);
- Intent galleryIntent = new Intent();
- galleryIntent.setType("image/*");
- galleryIntent.setAction(Intent.ACTION_PICK);
+ initChatRoom();
+ displayChatRoomHeader();
+ displayChatRoomHistory();
- Intent fileIntent = new Intent();
- fileIntent.setType("*/*");
- fileIntent.setAction(Intent.ACTION_GET_CONTENT);
- cameraIntents.add(fileIntent);
+ LinphoneManager.getInstance().setCurrentChatRoomAddress(mRemoteSipAddress);
+ }
- Intent chooserIntent = Intent.createChooser(galleryIntent, getString(R.string.image_picker_title));
- chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
+ @Override
+ public void onPause() {
+ ContactsManager.removeContactsListener(this);
+ removeVirtualKeyboardVisiblityListener();
+ LinphoneManager.getInstance().setCurrentChatRoomAddress(null);
+ if (mChatRoom != null) mChatRoom.removeListener(this);
+ if (mEventsAdapter != null) mEventsAdapter.clear();
+ super.onPause();
+ }
- LinphoneActivity.instance().disableGoToCall();
- startActivityForResult(chooserIntent, ADD_PHOTO);
- }
+ @Override
+ public void onActivityResult(int requestCode, int resultCode, Intent data) {
+ if (data != null) {
+ if (requestCode == ADD_PHOTO && resultCode == Activity.RESULT_OK) {
+ String fileToUploadPath = null;
+ if (data != null && data.getData() != null) {
+ if (data.getData().toString().contains("com.android.contacts/contacts/")) {
+ if (LinphoneUtils.getCVSPathFromLookupUri(data.getData().toString()) != null) {
+ fileToUploadPath = LinphoneUtils.getCVSPathFromLookupUri(data.getData().toString()).toString();
+ } else {
+ //TODO Error
+ return;
+ }
+ } else {
+ fileToUploadPath = LinphoneUtils.getRealPathFromURI(getActivity(), data.getData());
+ }
+ if (fileToUploadPath == null) {
+ fileToUploadPath = data.getData().toString();
+ }
+ } else if (mImageToUploadUri != null) {
+ fileToUploadPath = mImageToUploadUri.getPath();
+ }
- private void addFileToPendingList(String path) {
- if (path == null) {
- Log.e("Can't add file to pending list because it's path is null...");
- return;
- }
+ if (LinphoneUtils.isExtensionImage(fileToUploadPath)) {
+ addImageToPendingList(fileToUploadPath);
+ } else {
+ if (fileToUploadPath.startsWith("content://") || fileToUploadPath.startsWith("file://")) {
+ fileToUploadPath = LinphoneUtils.getFilePath(getActivity().getApplicationContext(), Uri.parse(fileToUploadPath));
+ } else if (fileToUploadPath.contains("com.android.contacts/contacts/")) {
+ fileToUploadPath = LinphoneUtils.getCVSPathFromLookupUri(fileToUploadPath).toString();
+ }
+ addFileToPendingList(fileToUploadPath);
+ }
+ } else {
+ super.onActivityResult(requestCode, resultCode, data);
+ }
+ } else {
+ if (LinphoneUtils.isExtensionImage(mImageToUploadUri.getPath())) {
+ addImageToPendingList(mImageToUploadUri.getPath());
+ }
+ }
+ }
- View pendingFile = mInflater.inflate(R.layout.file_upload_cell, mFilesUploadLayout, false);
- pendingFile.setTag(path);
+ @Override
+ public void onDeleteSelection(Object[] objectsToDelete) {
+ for (Object obj : objectsToDelete) {
+ EventLog eventLog = (EventLog) obj;
+ if (eventLog.getType() == EventLog.Type.ConferenceChatMessage) {
+ ChatMessage message = eventLog.getChatMessage();
+ if (message.getAppdata() != null && !message.isOutgoing()) {
+ File file = new File(message.getAppdata());
+ if (file.exists()) {
+ file.delete(); // Delete downloaded file from incoming message that will be deleted
+ }
+ }
+ }
+ eventLog.deleteFromDatabase();
+ }
+ if (mChatRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt())) {
+ mEventsAdapter.refresh(mChatRoom.getHistoryMessageEvents(0));
+ } else {
+ mEventsAdapter.refresh(mChatRoom.getHistoryEvents(0));
+ }
+ }
- TextView text = pendingFile.findViewById(R.id.pendingFileForUpload);
- String extension = path.substring(path.lastIndexOf('.'));
- text.setText(extension);
- ImageView remove = pendingFile.findViewById(R.id.remove);
- remove.setTag(pendingFile);
- remove.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- View pendingImage = (View)view.getTag();
- mFilesUploadLayout.removeView(pendingImage);
- mAttachImageButton.setEnabled(true);
- mMessageTextToSend.setEnabled(true);
- mSendMessageButton.setEnabled(mMessageTextToSend.getText().length() > 0 || mFilesUploadLayout.getChildCount() > 0);
- }
- });
+ @Override
+ public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
+ super.onCreateContextMenu(menu, v, menuInfo);
- mFilesUploadLayout.addView(pendingFile);
+ ChatBubbleViewHolder holder = (ChatBubbleViewHolder) v.getTag();
+ mContextMenuMessagePosition = holder.getAdapterPosition();
- mAttachImageButton.setEnabled(false); // For now limit file per message to 1
- mMessageTextToSend.setEnabled(false); // For now forbid to send both text and picture at the same time
- mSendMessageButton.setEnabled(true);
- }
+ EventLog event = (EventLog) mEventsAdapter.getItem(mContextMenuMessagePosition);
+ if (event.getType() != EventLog.Type.ConferenceChatMessage) {
+ return;
+ }
- private void addImageToPendingList(String path) {
- if (path == null) {
- Log.e("Can't add image to pending list because it's path is null...");
- return;
- }
+ MenuInflater inflater = getActivity().getMenuInflater();
+ ChatMessage message = event.getChatMessage();
+ if (message.getState() == ChatMessage.State.NotDelivered) {
+ inflater.inflate(R.menu.chat_bubble_menu_with_resend, menu);
+ } else {
+ inflater.inflate(R.menu.chat_bubble_menu, menu);
+ }
- View pendingImage = mInflater.inflate(R.layout.image_upload_cell, mFilesUploadLayout, false);
- pendingImage.setTag(path);
+ if (!message.isOutgoing() && mChatRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt())) {
+ // Do not show incoming messages IDMN state in 1 to 1 chat room as we don't receive IMDN for them
+ menu.removeItem(R.id.imdn_infos);
+ }
+ if (!message.hasTextContent()) {
+ // Do not show copy text option if message doesn't have any text
+ menu.removeItem(R.id.copy_text);
+ }
+ }
- ImageView image = pendingImage.findViewById(R.id.pendingImageForUpload);
- Bitmap bm = BitmapFactory.decodeFile(path);
- if (bm == null) return;
- image.setImageBitmap(bm);
+ @Override
+ public boolean onContextItemSelected(MenuItem item) {
- ImageView remove = pendingImage.findViewById(R.id.remove);
- remove.setTag(pendingImage);
- remove.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- View pendingImage = (View)view.getTag();
- mFilesUploadLayout.removeView(pendingImage);
- mAttachImageButton.setEnabled(true);
- mMessageTextToSend.setEnabled(true);
- mSendMessageButton.setEnabled(mMessageTextToSend.getText().length() > 0 || mFilesUploadLayout.getChildCount() > 0);
- }
- });
+ EventLog event = (EventLog) mEventsAdapter.getItem(mContextMenuMessagePosition);
- mFilesUploadLayout.addView(pendingImage);
+ if (event.getType() != EventLog.Type.ConferenceChatMessage) {
+ return super.onContextItemSelected(item);
+ }
- mAttachImageButton.setEnabled(false); // For now limit file per message to 1
- mMessageTextToSend.setEnabled(false); // For now forbid to send both text and picture at the same time
- mSendMessageButton.setEnabled(true);
- }
+ ChatMessage message = event.getChatMessage();
+ String messageId = message.getMessageId();
- /**
- * Message sending
- */
+ if (item.getItemId() == R.id.resend) {
+ mEventsAdapter.removeItem(mContextMenuMessagePosition);
+ message.resend();
+ return true;
+ }
+ if (item.getItemId() == R.id.imdn_infos) {
+ LinphoneActivity.instance().goToChatMessageImdnInfos(getRemoteSipUri(), messageId);
+ return true;
+ }
+ if (item.getItemId() == R.id.copy_text) {
+ if (message.hasTextContent()) {
+ ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
+ ClipData clip = ClipData.newPlainText("Message", message.getTextContent());
+ clipboard.setPrimaryClip(clip);
+ }
+ return true;
+ }
+ if (item.getItemId() == R.id.delete_message) {
+ mChatRoom.deleteMessage(message);
+ mEventsAdapter.removeItem(mContextMenuMessagePosition);
+ return true;
+ }
+ return super.onContextItemSelected(item);
+ }
- private void sendMessage() {
- String text = mMessageTextToSend.getText().toString();
+ /**
+ * Keyboard management
+ */
- ChatMessage msg;
- //TODO: rework when we'll send multiple files at once
- if (mFilesUploadLayout.getChildCount() > 0) {
- String filePath = (String) mFilesUploadLayout.getChildAt(0).getTag();
- String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
- String extension = LinphoneUtils.getExtensionFromFileName(fileName);
- Content content = Factory.instance().createContent();
- if (LinphoneUtils.isExtensionImage(fileName)) {
- content.setType("image");
- } else {
- content.setType("file");
- }
- content.setSubtype(extension);
- content.setName(fileName);
- msg = mChatRoom.createFileTransferMessage(content);
- msg.setFileTransferFilepath(filePath); // Let the file body handler take care of the upload
- msg.setAppdata(filePath);
+ private void addVirtualKeyboardVisiblityListener() {
+ mKeyboardListener = new ViewTreeObserver.OnGlobalLayoutListener() {
+ @Override
+ public void onGlobalLayout() {
+ Rect visibleArea = new Rect();
+ getActivity().getWindow().getDecorView().getWindowVisibleDisplayFrame(visibleArea);
- if (text != null && text.length() > 0) {
- msg.addTextContent(text);
- }
- } else {
- msg = mChatRoom.createMessage(text);
- }
- // Set listener not required here anymore, message will be added to messages list and adapter will set the listener
- msg.send();
+ int heightDiff = getActivity().getWindow().getDecorView().getRootView().getHeight() - (visibleArea.bottom - visibleArea.top);
+ if (heightDiff > 200) {
+ showKeyboardVisibleMode();
+ } else {
+ hideKeyboardVisibleMode();
+ }
+ }
+ };
+ getActivity().getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(mKeyboardListener);
+ }
- mFilesUploadLayout.removeAllViews();
- mAttachImageButton.setEnabled(true);
- mMessageTextToSend.setEnabled(true);
- mMessageTextToSend.setText("");
- }
+ private void removeVirtualKeyboardVisiblityListener() {
+ Compatibility.removeGlobalLayoutListener(getActivity().getWindow().getDecorView().getViewTreeObserver(), mKeyboardListener);
+ }
- /*
- * Chat room callbacks
- */
+ public void showKeyboardVisibleMode() {
+ LinphoneActivity.instance().hideTabBar(true);
+ }
- @Override
- public void onChatMessageSent(ChatRoom cr, EventLog event) {
- mEventsAdapter.addToHistory(event);
- }
+ public void hideKeyboardVisibleMode() {
+ LinphoneActivity.instance().hideTabBar(false);
+ }
- @Override
- public void onConferenceAddressGeneration(ChatRoom cr) {
+ /**
+ * View initialization
+ */
- }
+ private void setReadOnly() {
+ mMessageTextToSend.setEnabled(false);
+ mAttachImageButton.setEnabled(false);
+ mSendMessageButton.setEnabled(false);
+ }
- @Override
- public void onParticipantDeviceFetchRequested(ChatRoom cr, Address addr) {
+ private void getContactsForParticipants() {
+ mParticipants = new ArrayList<>();
+ if (mChatRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt())) {
+ LinphoneContact c = ContactsManager.getInstance().findContactFromAddress(mRemoteParticipantAddress);
+ if (c != null) {
+ mParticipants.add(c);
+ }
+ } else {
+ int index = 0;
+ StringBuilder participantsLabel = new StringBuilder();
+ for (Participant p : mChatRoom.getParticipants()) {
+ LinphoneContact c = ContactsManager.getInstance().findContactFromAddress(p.getAddress());
+ if (c != null) {
+ mParticipants.add(c);
+ participantsLabel.append(c.getFullName());
+ } else {
+ String displayName = LinphoneUtils.getAddressDisplayName(p.getAddress());
+ participantsLabel.append(displayName);
+ }
+ index++;
+ if (index != mChatRoom.getNbParticipants()) participantsLabel.append(", ");
+ }
+ mParticipantsLabel.setText(participantsLabel.toString());
+ }
- }
- @Override
- public void onParticipantRegistrationSubscriptionRequested(ChatRoom cr, Address participantAddr){
- }
+ if (mEventsAdapter != null) {
+ mEventsAdapter.setContacts(mParticipants);
+ }
+ }
- @Override
- public void onParticipantRegistrationUnsubscriptionRequested(ChatRoom cr, Address participantAddr){
- }
+ private void initChatRoom() {
+ Core core = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ if (mRemoteSipAddress == null || mRemoteSipUri == null || mRemoteSipUri.length() == 0 || core == null) {
+ //TODO error
+ return;
+ }
+ Address proxyConfigContact = (core.getDefaultProxyConfig() != null) ? core.getDefaultProxyConfig().getContact() : null;
+ if (proxyConfigContact != null) {
+ mChatRoom = core.findOneToOneChatRoom(proxyConfigContact, mRemoteSipAddress);
+ }
+ if (mChatRoom == null) {
+ mChatRoom = core.getChatRoomFromUri(mRemoteSipAddress.asStringUriOnly());
+ }
+ mChatRoom.addListener(this);
+ mChatRoom.markAsRead();
+ LinphoneManager.getInstance().updateUnreadCountForChatRoom(mChatRoom, 0);
+ LinphoneActivity.instance().refreshMissedChatCountDisplay();
- @Override
- public void onUndecryptableMessageReceived(ChatRoom cr, ChatMessage msg) {
- final Address from = msg.getFromAddress();
- final LinphoneContact contact = ContactsManager.getInstance().findContactFromAddress(from);
+ mRemoteParticipantAddress = mRemoteSipAddress;
+ if (mChatRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt()) && mChatRoom.getParticipants().length > 0) {
+ mRemoteParticipantAddress = mChatRoom.getParticipants()[0].getAddress();
+ }
- if (LinphoneActivity.instance().isOnBackground()) {
- if (!getResources().getBoolean(R.bool.disable_chat_message_notification)) {
- if (contact != null) {
- LinphoneService.instance().displayMessageNotification(from.asStringUriOnly(),
- contact.getFullName(), contact.getThumbnailUri(), getString(R.string.message_cant_be_decrypted_notif));
- } else {
- LinphoneService.instance().displayMessageNotification(from.asStringUriOnly(),
- from.getUsername(), null, getString(R.string.message_cant_be_decrypted_notif));
- }
- }
- } else if (LinphoneManager.getLc().limeEnabled() == LimeState.Mandatory) {
- final Dialog dialog = LinphoneActivity.instance().displayDialog(
- getString(R.string.message_cant_be_decrypted)
- .replace("%s", (contact != null) ? contact.getFullName() : from.getUsername()));
- Button delete = dialog.findViewById(R.id.delete_button);
- delete.setText(getString(R.string.call));
- Button cancel = dialog.findViewById(R.id.cancel);
- cancel.setText(getString(R.string.ok));
- delete.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- LinphoneManager.getInstance().newOutgoingCall(from.asStringUriOnly()
- , (contact != null) ? contact.getFullName() : from.getUsername());
- dialog.dismiss();
- }
- });
+ getContactsForParticipants();
- cancel.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- dialog.dismiss();
- }
- });
- dialog.show();
- }
- }
+ mRemoteComposing.setVisibility(View.GONE);
+ }
- @Override
- public void onChatMessageReceived(ChatRoom cr, EventLog event) {
- cr.markAsRead();
- LinphoneManager.getInstance().updateUnreadCountForChatRoom(mChatRoom, 0);
- LinphoneActivity.instance().refreshMissedChatCountDisplay();
+ private void displayChatRoomHeader() {
+ Core core = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ if (core == null || mChatRoom == null) return;
- ChatMessage msg = event.getChatMessage();
- if (msg.getErrorInfo() != null && msg.getErrorInfo().getReason() == Reason.UnsupportedContent) {
- Log.w("Message received but content is unsupported, do not display it");
- return;
- }
+ if (core.getCallsNb() > 0) {
+ mBackToCallButton.setVisibility(View.VISIBLE);
+ } else {
+ mBackToCallButton.setVisibility(View.GONE);
+ if (mChatRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt())) {
+ mCallButton.setVisibility(View.VISIBLE);
+ mGroupInfosButton.setVisibility(View.GONE);
+ mParticipantsLabel.setVisibility(View.GONE);
- if (!msg.hasTextContent() && msg.getFileTransferInformation() == null) {
- Log.w("Message has no text or file transfer information to display, ignoring it...");
- return;
- }
+ if (mParticipants.size() == 0) {
+ // Contact not found
+ String displayName = LinphoneUtils.getAddressDisplayName(mRemoteParticipantAddress);
+ mRoomLabel.setText(displayName);
+ } else {
+ mRoomLabel.setText(mParticipants.get(0).getFullName());
+ }
+ } else {
+ mCallButton.setVisibility(View.GONE);
+ mGroupInfosButton.setVisibility(View.VISIBLE);
+ mRoomLabel.setText(mChatRoom.getSubject());
+ mParticipantsLabel.setVisibility(View.VISIBLE);
+ }
+ }
- String externalBodyUrl = msg.getExternalBodyUrl();
- Content fileTransferContent = msg.getFileTransferInformation();
- if (externalBodyUrl != null || fileTransferContent != null) {
- LinphoneActivity.instance().checkAndRequestExternalStoragePermission();
- }
+ if (mChatRoom.hasBeenLeft()) {
+ setReadOnly();
+ }
+ }
- mEventsAdapter.addToHistory(event);
- }
+ private void displayChatRoomHistory() {
- @Override
- public void onIsComposingReceived(ChatRoom cr, Address remoteAddr, boolean isComposing) {
- ArrayList composing = new ArrayList<>();
- for (Address a : cr.getComposingAddresses()) {
- boolean found = false;
- for (LinphoneContact c : mParticipants) {
- if (c.hasAddress(a.asStringUriOnly())) {
- composing.add(c.getFullName());
- found = true;
- break;
- }
- }
- if (!found) {
- LinphoneContact contact = ContactsManager.getInstance().findContactFromAddress(remoteAddr);
- String displayName;
- if (contact != null) {
- if (contact.getFullName() != null) {
- displayName = contact.getFullName();
- } else {
- displayName = LinphoneUtils.getAddressDisplayName(remoteAddr);
- }
- } else {
- displayName = LinphoneUtils.getAddressDisplayName(a);
- }
- composing.add(displayName);
- }
- }
+ if (mChatRoom == null) return;
+ if (mChatRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt())) {
+ mEventsAdapter = new ChatEventsAdapter(this, mSelectionHelper, R.layout.chat_bubble, mChatRoom.getHistoryMessageEvents(0), mParticipants, this);
+ } else {
+ mEventsAdapter = new ChatEventsAdapter(this, mSelectionHelper, R.layout.chat_bubble, mChatRoom.getHistoryEvents(0), mParticipants, this);
+ }
+ mSelectionHelper.setAdapter(mEventsAdapter);
+ mChatEventsList.setAdapter(mEventsAdapter);
+ scrollToBottom();
+ }
- mRemoteComposing.setVisibility(View.VISIBLE);
- if (composing.size() == 0) {
- mRemoteComposing.setVisibility(View.GONE);
- } else if (composing.size() == 1) {
- mRemoteComposing.setText(getString(R.string.remote_composing_single).replace("%s", composing.get(0)));
- } else {
- StringBuilder remotes = new StringBuilder();
- int i = 0;
- for (String remote : composing) {
- remotes.append(remote);
- i++;
- if (i != composing.size()) {
- remotes.append(", ");
- }
- }
- mRemoteComposing.setText(getString(R.string.remote_composing_multiple).replace("%s", remotes.toString()));
- }
- }
+ public void scrollToBottom() {
+ mChatEventsList.getLayoutManager().scrollToPosition(mEventsAdapter.getCount() - 1);
+ }
- @Override
- public void onMessageReceived(ChatRoom cr, ChatMessage msg) {
+ public String getRemoteSipUri() {
+ return mRemoteSipUri;
+ }
- }
+ @Override
+ public void onItemClicked(int position) {
+ if (mEventsAdapter.isEditionEnabled()) {
+ mEventsAdapter.toggleSelection(position);
+ }
+ }
- @Override
- public void onConferenceJoined(ChatRoom cr, EventLog event) {
- // Currently flexisip doesn't send the participants list in the INVITE
- // So we have to refresh the display when information is available
- // In the meantime header will be chatroom-xxxxxxx
- if (mChatRoom == null) mChatRoom = cr;
- if (mChatRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt()) && mChatRoom.getParticipants().length > 0) {
- mRemoteParticipantAddress = mChatRoom.getParticipants()[0].getAddress();
- }
- getContactsForParticipants();
- displayChatRoomHeader();
+ /**
+ * File transfer related
+ */
- mEventsAdapter.addToHistory(event);
- }
+ private void pickFile() {
+ List cameraIntents = new ArrayList<>();
+ Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
+ File file = new File(Environment.getExternalStorageDirectory(), getString(R.string.temp_photo_name_with_date).replace("%s", String.valueOf(System.currentTimeMillis()) + ".jpeg"));
+ mImageToUploadUri = Uri.fromFile(file);
+ captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageToUploadUri);
+ cameraIntents.add(captureIntent);
- @Override
- public void onConferenceLeft(ChatRoom cr, EventLog event) {
- mEventsAdapter.addToHistory(event);
- }
+ Intent galleryIntent = new Intent();
+ galleryIntent.setType("image/*");
+ galleryIntent.setAction(Intent.ACTION_PICK);
- @Override
- public void onParticipantAdminStatusChanged(ChatRoom cr, EventLog event) {
- mEventsAdapter.addToHistory(event);
- }
+ Intent fileIntent = new Intent();
+ fileIntent.setType("*/*");
+ fileIntent.setAction(Intent.ACTION_GET_CONTENT);
+ cameraIntents.add(fileIntent);
- @Override
- public void onParticipantDeviceRemoved(ChatRoom cr, EventLog event) {
+ Intent chooserIntent = Intent.createChooser(galleryIntent, getString(R.string.image_picker_title));
+ chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
- }
+ LinphoneActivity.instance().disableGoToCall();
+ startActivityForResult(chooserIntent, ADD_PHOTO);
+ }
- @Override
- public void onParticipantRemoved(ChatRoom cr, EventLog event) {
- getContactsForParticipants();
- mEventsAdapter.addToHistory(event);
- }
+ private void addFileToPendingList(String path) {
+ if (path == null) {
+ Log.e("Can't add file to pending list because it's path is null...");
+ return;
+ }
- @Override
- public void onChatMessageShouldBeStored(ChatRoom cr, ChatMessage msg) {
+ View pendingFile = mInflater.inflate(R.layout.file_upload_cell, mFilesUploadLayout, false);
+ pendingFile.setTag(path);
- }
+ TextView text = pendingFile.findViewById(R.id.pendingFileForUpload);
+ String extension = path.substring(path.lastIndexOf('.'));
+ text.setText(extension);
- @Override
- public void onParticipantsCapabilitiesChecked(ChatRoom cr, Address deviceAddr, Address[] participantsAddr) {
+ ImageView remove = pendingFile.findViewById(R.id.remove);
+ remove.setTag(pendingFile);
+ remove.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ View pendingImage = (View) view.getTag();
+ mFilesUploadLayout.removeView(pendingImage);
+ mAttachImageButton.setEnabled(true);
+ mMessageTextToSend.setEnabled(true);
+ mSendMessageButton.setEnabled(mMessageTextToSend.getText().length() > 0 || mFilesUploadLayout.getChildCount() > 0);
+ }
+ });
- }
+ mFilesUploadLayout.addView(pendingFile);
- @Override
- public void onParticipantDeviceAdded(ChatRoom cr, EventLog event) {
+ mAttachImageButton.setEnabled(false); // For now limit file per message to 1
+ mMessageTextToSend.setEnabled(false); // For now forbid to send both text and picture at the same time
+ mSendMessageButton.setEnabled(true);
+ }
- }
+ private void addImageToPendingList(String path) {
+ if (path == null) {
+ Log.e("Can't add image to pending list because it's path is null...");
+ return;
+ }
- @Override
- public void onStateChanged(ChatRoom cr, ChatRoom.State newState) {
- if (mChatRoom.hasBeenLeft()) {
- setReadOnly();
- }
- }
+ View pendingImage = mInflater.inflate(R.layout.image_upload_cell, mFilesUploadLayout, false);
+ pendingImage.setTag(path);
- @Override
- public void onParticipantAdded(ChatRoom cr, EventLog event) {
- getContactsForParticipants();
- mEventsAdapter.addToHistory(event);
- }
+ ImageView image = pendingImage.findViewById(R.id.pendingImageForUpload);
+ Bitmap bm = BitmapFactory.decodeFile(path);
+ if (bm == null) return;
+ image.setImageBitmap(bm);
- @Override
- public void onSubjectChanged(ChatRoom cr, EventLog event) {
- mRoomLabel.setText(event.getSubject());
- mEventsAdapter.addToHistory(event);
- }
+ ImageView remove = pendingImage.findViewById(R.id.remove);
+ remove.setTag(pendingImage);
+ remove.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ View pendingImage = (View) view.getTag();
+ mFilesUploadLayout.removeView(pendingImage);
+ mAttachImageButton.setEnabled(true);
+ mMessageTextToSend.setEnabled(true);
+ mSendMessageButton.setEnabled(mMessageTextToSend.getText().length() > 0 || mFilesUploadLayout.getChildCount() > 0);
+ }
+ });
- @Override
- public void onContactsUpdated() {
- getContactsForParticipants();
- }
+ mFilesUploadLayout.addView(pendingImage);
+
+ mAttachImageButton.setEnabled(false); // For now limit file per message to 1
+ mMessageTextToSend.setEnabled(false); // For now forbid to send both text and picture at the same time
+ mSendMessageButton.setEnabled(true);
+ }
+
+ /**
+ * Message sending
+ */
+
+ private void sendMessage() {
+ String text = mMessageTextToSend.getText().toString();
+
+ ChatMessage msg;
+ //TODO: rework when we'll send multiple files at once
+ if (mFilesUploadLayout.getChildCount() > 0) {
+ String filePath = (String) mFilesUploadLayout.getChildAt(0).getTag();
+ String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
+ String extension = LinphoneUtils.getExtensionFromFileName(fileName);
+ Content content = Factory.instance().createContent();
+ if (LinphoneUtils.isExtensionImage(fileName)) {
+ content.setType("image");
+ } else {
+ content.setType("file");
+ }
+ content.setSubtype(extension);
+ content.setName(fileName);
+ msg = mChatRoom.createFileTransferMessage(content);
+ msg.setFileTransferFilepath(filePath); // Let the file body handler take care of the upload
+ msg.setAppdata(filePath);
+
+ if (text != null && text.length() > 0) {
+ msg.addTextContent(text);
+ }
+ } else {
+ msg = mChatRoom.createMessage(text);
+ }
+ // Set listener not required here anymore, message will be added to messages list and adapter will set the listener
+ msg.send();
+
+ mFilesUploadLayout.removeAllViews();
+ mAttachImageButton.setEnabled(true);
+ mMessageTextToSend.setEnabled(true);
+ mMessageTextToSend.setText("");
+ }
+
+ /*
+ * Chat room callbacks
+ */
+
+ @Override
+ public void onChatMessageSent(ChatRoom cr, EventLog event) {
+ mEventsAdapter.addToHistory(event);
+ }
+
+ @Override
+ public void onConferenceAddressGeneration(ChatRoom cr) {
+
+ }
+
+ @Override
+ public void onParticipantDeviceFetchRequested(ChatRoom cr, Address addr) {
+
+ }
+
+ @Override
+ public void onParticipantRegistrationSubscriptionRequested(ChatRoom cr, Address participantAddr) {
+ }
+
+ @Override
+ public void onParticipantRegistrationUnsubscriptionRequested(ChatRoom cr, Address participantAddr) {
+ }
+
+ @Override
+ public void onUndecryptableMessageReceived(ChatRoom cr, ChatMessage msg) {
+ final Address from = msg.getFromAddress();
+ final LinphoneContact contact = ContactsManager.getInstance().findContactFromAddress(from);
+
+ if (LinphoneActivity.instance().isOnBackground()) {
+ if (!getResources().getBoolean(R.bool.disable_chat_message_notification)) {
+ if (contact != null) {
+ LinphoneService.instance().displayMessageNotification(from.asStringUriOnly(),
+ contact.getFullName(), contact.getThumbnailUri(), getString(R.string.message_cant_be_decrypted_notif));
+ } else {
+ LinphoneService.instance().displayMessageNotification(from.asStringUriOnly(),
+ from.getUsername(), null, getString(R.string.message_cant_be_decrypted_notif));
+ }
+ }
+ } else if (LinphoneManager.getLc().limeEnabled() == LimeState.Mandatory) {
+ final Dialog dialog = LinphoneActivity.instance().displayDialog(
+ getString(R.string.message_cant_be_decrypted)
+ .replace("%s", (contact != null) ? contact.getFullName() : from.getUsername()));
+ Button delete = dialog.findViewById(R.id.delete_button);
+ delete.setText(getString(R.string.call));
+ Button cancel = dialog.findViewById(R.id.cancel);
+ cancel.setText(getString(R.string.ok));
+ delete.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ LinphoneManager.getInstance().newOutgoingCall(from.asStringUriOnly()
+ , (contact != null) ? contact.getFullName() : from.getUsername());
+ dialog.dismiss();
+ }
+ });
+
+ cancel.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ dialog.dismiss();
+ }
+ });
+ dialog.show();
+ }
+ }
+
+ @Override
+ public void onChatMessageReceived(ChatRoom cr, EventLog event) {
+ cr.markAsRead();
+ LinphoneManager.getInstance().updateUnreadCountForChatRoom(mChatRoom, 0);
+ LinphoneActivity.instance().refreshMissedChatCountDisplay();
+
+ ChatMessage msg = event.getChatMessage();
+ if (msg.getErrorInfo() != null && msg.getErrorInfo().getReason() == Reason.UnsupportedContent) {
+ Log.w("Message received but content is unsupported, do not display it");
+ return;
+ }
+
+ if (!msg.hasTextContent() && msg.getFileTransferInformation() == null) {
+ Log.w("Message has no text or file transfer information to display, ignoring it...");
+ return;
+ }
+
+ String externalBodyUrl = msg.getExternalBodyUrl();
+ Content fileTransferContent = msg.getFileTransferInformation();
+ if (externalBodyUrl != null || fileTransferContent != null) {
+ LinphoneActivity.instance().checkAndRequestExternalStoragePermission();
+ }
+
+ mEventsAdapter.addToHistory(event);
+ }
+
+ @Override
+ public void onIsComposingReceived(ChatRoom cr, Address remoteAddr, boolean isComposing) {
+ ArrayList composing = new ArrayList<>();
+ for (Address a : cr.getComposingAddresses()) {
+ boolean found = false;
+ for (LinphoneContact c : mParticipants) {
+ if (c.hasAddress(a.asStringUriOnly())) {
+ composing.add(c.getFullName());
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
+ LinphoneContact contact = ContactsManager.getInstance().findContactFromAddress(remoteAddr);
+ String displayName;
+ if (contact != null) {
+ if (contact.getFullName() != null) {
+ displayName = contact.getFullName();
+ } else {
+ displayName = LinphoneUtils.getAddressDisplayName(remoteAddr);
+ }
+ } else {
+ displayName = LinphoneUtils.getAddressDisplayName(a);
+ }
+ composing.add(displayName);
+ }
+ }
+
+ mRemoteComposing.setVisibility(View.VISIBLE);
+ if (composing.size() == 0) {
+ mRemoteComposing.setVisibility(View.GONE);
+ } else if (composing.size() == 1) {
+ mRemoteComposing.setText(getString(R.string.remote_composing_single).replace("%s", composing.get(0)));
+ } else {
+ StringBuilder remotes = new StringBuilder();
+ int i = 0;
+ for (String remote : composing) {
+ remotes.append(remote);
+ i++;
+ if (i != composing.size()) {
+ remotes.append(", ");
+ }
+ }
+ mRemoteComposing.setText(getString(R.string.remote_composing_multiple).replace("%s", remotes.toString()));
+ }
+ }
+
+ @Override
+ public void onMessageReceived(ChatRoom cr, ChatMessage msg) {
+
+ }
+
+ @Override
+ public void onConferenceJoined(ChatRoom cr, EventLog event) {
+ // Currently flexisip doesn't send the participants list in the INVITE
+ // So we have to refresh the display when information is available
+ // In the meantime header will be chatroom-xxxxxxx
+ if (mChatRoom == null) mChatRoom = cr;
+ if (mChatRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt()) && mChatRoom.getParticipants().length > 0) {
+ mRemoteParticipantAddress = mChatRoom.getParticipants()[0].getAddress();
+ }
+ getContactsForParticipants();
+ displayChatRoomHeader();
+
+ mEventsAdapter.addToHistory(event);
+ }
+
+ @Override
+ public void onConferenceLeft(ChatRoom cr, EventLog event) {
+ mEventsAdapter.addToHistory(event);
+ }
+
+ @Override
+ public void onParticipantAdminStatusChanged(ChatRoom cr, EventLog event) {
+ mEventsAdapter.addToHistory(event);
+ }
+
+ @Override
+ public void onParticipantDeviceRemoved(ChatRoom cr, EventLog event) {
+
+ }
+
+ @Override
+ public void onParticipantRemoved(ChatRoom cr, EventLog event) {
+ getContactsForParticipants();
+ mEventsAdapter.addToHistory(event);
+ }
+
+ @Override
+ public void onChatMessageShouldBeStored(ChatRoom cr, ChatMessage msg) {
+
+ }
+
+ @Override
+ public void onParticipantsCapabilitiesChecked(ChatRoom cr, Address deviceAddr, Address[] participantsAddr) {
+
+ }
+
+ @Override
+ public void onParticipantDeviceAdded(ChatRoom cr, EventLog event) {
+
+ }
+
+ @Override
+ public void onStateChanged(ChatRoom cr, ChatRoom.State newState) {
+ if (mChatRoom.hasBeenLeft()) {
+ setReadOnly();
+ }
+ }
+
+ @Override
+ public void onParticipantAdded(ChatRoom cr, EventLog event) {
+ getContactsForParticipants();
+ mEventsAdapter.addToHistory(event);
+ }
+
+ @Override
+ public void onSubjectChanged(ChatRoom cr, EventLog event) {
+ mRoomLabel.setText(event.getSubject());
+ mEventsAdapter.addToHistory(event);
+ }
+
+ @Override
+ public void onContactsUpdated() {
+ getContactsForParticipants();
+ }
}
diff --git a/src/android/org/linphone/chat/GroupInfoAdapter.java b/src/android/org/linphone/chat/GroupInfoAdapter.java
index d3c6025c5..396fb2f93 100644
--- a/src/android/org/linphone/chat/GroupInfoAdapter.java
+++ b/src/android/org/linphone/chat/GroupInfoAdapter.java
@@ -56,7 +56,7 @@ public class GroupInfoAdapter extends RecyclerView.Adapter mItems;
private View.OnClickListener mDeleteListener;
@@ -77,7 +77,7 @@ public class GroupInfoAdapter extends RecyclerView.Adapter mParticipants;
- private String mSubject;
- private ChatRoom mChatRoom, mTempChatRoom;
- private Dialog mAdminStateChangedDialog;
- private ChatRoomListenerStub mChatRoomCreationListener;
- private Bundle mShareInfos;
- private Context mContext;
- private LinearLayoutManager layoutManager;
+ private LinearLayout mLeaveGroupButton;
+ private RelativeLayout mWaitLayout;
+ private GroupInfoAdapter mAdapter;
+ private boolean mIsAlreadyCreatedGroup;
+ private boolean mIsEditionEnabled;
+ private ArrayList mParticipants;
+ private String mSubject;
+ private ChatRoom mChatRoom, mTempChatRoom;
+ private Dialog mAdminStateChangedDialog;
+ private ChatRoomListenerStub mChatRoomCreationListener;
+ private Bundle mShareInfos;
+ private Context mContext;
+ private LinearLayoutManager layoutManager;
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
- mInflater = inflater;
- View view = inflater.inflate(R.layout.chat_infos, container, false);
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ mInflater = inflater;
+ View view = inflater.inflate(R.layout.chat_infos, container, false);
- if (getArguments() == null || getArguments().isEmpty()) {
- return null;
- }
- mContext = getActivity().getApplicationContext();
+ if (getArguments() == null || getArguments().isEmpty()) {
+ return null;
+ }
+ mContext = getActivity().getApplicationContext();
- mParticipants = (ArrayList) getArguments().getSerializable("ContactAddress");
+ mParticipants = (ArrayList) getArguments().getSerializable("ContactAddress");
- mGroupChatRoomAddress = null;
- mChatRoom = null;
+ mGroupChatRoomAddress = null;
+ mChatRoom = null;
- String address = getArguments().getString("groupChatRoomAddress");
- if (address != null && address.length() > 0) {
- mGroupChatRoomAddress = LinphoneManager.getLc().createAddress(address);
- }
- mIsAlreadyCreatedGroup = mGroupChatRoomAddress != null;
- if (mIsAlreadyCreatedGroup) {
- mChatRoom = LinphoneManager.getLc().getChatRoom(mGroupChatRoomAddress);
- }
- if (mChatRoom == null) mIsAlreadyCreatedGroup = false;
+ String address = getArguments().getString("groupChatRoomAddress");
+ if (address != null && address.length() > 0) {
+ mGroupChatRoomAddress = LinphoneManager.getLc().createAddress(address);
+ }
+ mIsAlreadyCreatedGroup = mGroupChatRoomAddress != null;
+ if (mIsAlreadyCreatedGroup) {
+ mChatRoom = LinphoneManager.getLc().getChatRoom(mGroupChatRoomAddress);
+ }
+ if (mChatRoom == null) mIsAlreadyCreatedGroup = false;
- mIsEditionEnabled = getArguments().getBoolean("isEditionEnabled");
- mSubject = getArguments().getString("subject");
+ mIsEditionEnabled = getArguments().getBoolean("isEditionEnabled");
+ mSubject = getArguments().getString("subject");
- if (mChatRoom != null && mChatRoom.hasBeenLeft()) {
- mIsEditionEnabled = false;
- }
+ if (mChatRoom != null && mChatRoom.hasBeenLeft()) {
+ mIsEditionEnabled = false;
+ }
- mParticipantsList = view.findViewById(R.id.chat_room_participants);
- mAdapter = new GroupInfoAdapter(mParticipants, !mIsEditionEnabled, !mIsAlreadyCreatedGroup);
- mAdapter.setOnDeleteClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- ContactAddress ca = (ContactAddress) view.getTag();
- mParticipants.remove(ca);
- mAdapter.updateDataSet(mParticipants);
- mParticipantsList.setAdapter(mAdapter);
- mConfirmButton.setEnabled(mSubjectField.getText().length() > 0 && mParticipants.size() > 0);
- }
- });
- mParticipantsList.setAdapter(mAdapter);
- mAdapter.setChatRoom(mChatRoom);
- layoutManager = new LinearLayoutManager(mContext);
- mParticipantsList.setLayoutManager(layoutManager);
+ mParticipantsList = view.findViewById(R.id.chat_room_participants);
+ mAdapter = new GroupInfoAdapter(mParticipants, !mIsEditionEnabled, !mIsAlreadyCreatedGroup);
+ mAdapter.setOnDeleteClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ ContactAddress ca = (ContactAddress) view.getTag();
+ mParticipants.remove(ca);
+ mAdapter.updateDataSet(mParticipants);
+ mParticipantsList.setAdapter(mAdapter);
+ mConfirmButton.setEnabled(mSubjectField.getText().length() > 0 && mParticipants.size() > 0);
+ }
+ });
+ mParticipantsList.setAdapter(mAdapter);
+ mAdapter.setChatRoom(mChatRoom);
+ layoutManager = new LinearLayoutManager(mContext);
+ mParticipantsList.setLayoutManager(layoutManager);
- //Divider between items
- DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(mParticipantsList.getContext(),
- layoutManager.getOrientation());
- dividerItemDecoration.setDrawable(mContext.getResources().getDrawable(R.drawable.divider));
- mParticipantsList.addItemDecoration(dividerItemDecoration);
+ //Divider between items
+ DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(mParticipantsList.getContext(),
+ layoutManager.getOrientation());
+ dividerItemDecoration.setDrawable(mContext.getResources().getDrawable(R.drawable.divider));
+ mParticipantsList.addItemDecoration(dividerItemDecoration);
- String fileSharedUri = getArguments().getString("fileSharedUri");
- String messageDraft = getArguments().getString("messageDraft");
+ String fileSharedUri = getArguments().getString("fileSharedUri");
+ String messageDraft = getArguments().getString("messageDraft");
- if (fileSharedUri != null || messageDraft != null)
- mShareInfos = new Bundle();
+ if (fileSharedUri != null || messageDraft != null)
+ mShareInfos = new Bundle();
- if (fileSharedUri != null)
- mShareInfos.putString("fileSharedUri", fileSharedUri);
+ if (fileSharedUri != null)
+ mShareInfos.putString("fileSharedUri", fileSharedUri);
- if (messageDraft != null)
- mShareInfos.putString("messageDraft", messageDraft);
+ if (messageDraft != null)
+ mShareInfos.putString("messageDraft", messageDraft);
- mBackButton = view.findViewById(R.id.back);
- mBackButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- if (mIsAlreadyCreatedGroup) {
- if (LinphoneActivity.instance().isTablet()) {
- LinphoneActivity.instance().goToChat(mGroupChatRoomAddress.asStringUriOnly(), mShareInfos);
- } else {
- getFragmentManager().popBackStack();
- }
- } else {
- LinphoneActivity.instance().goToChatCreator(null, mParticipants, null, true, mShareInfos);
- }
- }
- });
+ mBackButton = view.findViewById(R.id.back);
+ mBackButton.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ if (mIsAlreadyCreatedGroup) {
+ if (LinphoneActivity.instance().isTablet()) {
+ LinphoneActivity.instance().goToChat(mGroupChatRoomAddress.asStringUriOnly(), mShareInfos);
+ } else {
+ getFragmentManager().popBackStack();
+ }
+ } else {
+ LinphoneActivity.instance().goToChatCreator(null, mParticipants, null, true, mShareInfos);
+ }
+ }
+ });
- mConfirmButton = view.findViewById(R.id.confirm);
+ mConfirmButton = view.findViewById(R.id.confirm);
- mLeaveGroupButton = view.findViewById(R.id.leaveGroupLayout);
- mLeaveGroupButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- final Dialog dialog = LinphoneActivity.instance().displayDialog(getString(R.string.chat_room_leave_dialog));
- Button delete = dialog.findViewById(R.id.delete_button);
- delete.setText(getString(R.string.chat_room_leave_button));
- Button cancel = dialog.findViewById(R.id.cancel);
+ mLeaveGroupButton = view.findViewById(R.id.leaveGroupLayout);
+ mLeaveGroupButton.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ final Dialog dialog = LinphoneActivity.instance().displayDialog(getString(R.string.chat_room_leave_dialog));
+ Button delete = dialog.findViewById(R.id.delete_button);
+ delete.setText(getString(R.string.chat_room_leave_button));
+ Button cancel = dialog.findViewById(R.id.cancel);
- delete.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- if (mChatRoom != null) {
- mChatRoom.leave();
- LinphoneActivity.instance().goToChat(mGroupChatRoomAddress.asString(), null);
- } else {
- Log.e("Can't leave, chatRoom for address " + mGroupChatRoomAddress.asString() + " is null...");
- }
- dialog.dismiss();
- }
- });
+ delete.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ if (mChatRoom != null) {
+ mChatRoom.leave();
+ LinphoneActivity.instance().goToChat(mGroupChatRoomAddress.asString(), null);
+ } else {
+ Log.e("Can't leave, chatRoom for address " + mGroupChatRoomAddress.asString() + " is null...");
+ }
+ dialog.dismiss();
+ }
+ });
- cancel.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- dialog.dismiss();
- }
- });
- dialog.show();
- }
- });
- mLeaveGroupButton.setVisibility(mIsAlreadyCreatedGroup && mChatRoom.hasBeenLeft() ? View.GONE : mIsAlreadyCreatedGroup ? View.VISIBLE : View.GONE);
+ cancel.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ dialog.dismiss();
+ }
+ });
+ dialog.show();
+ }
+ });
+ mLeaveGroupButton.setVisibility(mIsAlreadyCreatedGroup && mChatRoom.hasBeenLeft() ? View.GONE : mIsAlreadyCreatedGroup ? View.VISIBLE : View.GONE);
- mAddParticipantsLayout = view.findViewById(R.id.addParticipantsLayout);
- mAddParticipantsLayout.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- if (mIsEditionEnabled) {
- LinphoneActivity.instance().goToChatCreator(mGroupChatRoomAddress != null ? mGroupChatRoomAddress.asString() : null, mParticipants, mSubject, !mIsAlreadyCreatedGroup, null);
- }
- }
- });
- mAddParticipantsButton = view.findViewById(R.id.addParticipants);
- mAddParticipantsButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- LinphoneActivity.instance().goToChatCreator(mGroupChatRoomAddress != null ? mGroupChatRoomAddress.asString() : null, mParticipants, mSubject, !mIsAlreadyCreatedGroup, null);
- }
- });
+ mAddParticipantsLayout = view.findViewById(R.id.addParticipantsLayout);
+ mAddParticipantsLayout.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ if (mIsEditionEnabled) {
+ LinphoneActivity.instance().goToChatCreator(mGroupChatRoomAddress != null ? mGroupChatRoomAddress.asString() : null, mParticipants, mSubject, !mIsAlreadyCreatedGroup, null);
+ }
+ }
+ });
+ mAddParticipantsButton = view.findViewById(R.id.addParticipants);
+ mAddParticipantsButton.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ LinphoneActivity.instance().goToChatCreator(mGroupChatRoomAddress != null ? mGroupChatRoomAddress.asString() : null, mParticipants, mSubject, !mIsAlreadyCreatedGroup, null);
+ }
+ });
- mSubjectField = view.findViewById(R.id.subjectField);
- mSubjectField.addTextChangedListener(new TextWatcher() {
- @Override
- public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
+ mSubjectField = view.findViewById(R.id.subjectField);
+ mSubjectField.addTextChangedListener(new TextWatcher() {
+ @Override
+ public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
- }
+ }
- @Override
- public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
+ @Override
+ public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
- }
+ }
- @Override
- public void afterTextChanged(Editable editable) {
- mConfirmButton.setEnabled(mSubjectField.getText().length() > 0 && mParticipants.size() > 0);
- }
- });
- mSubjectField.setText(mSubject);
+ @Override
+ public void afterTextChanged(Editable editable) {
+ mConfirmButton.setEnabled(mSubjectField.getText().length() > 0 && mParticipants.size() > 0);
+ }
+ });
+ mSubjectField.setText(mSubject);
- mChatRoomCreationListener = new ChatRoomListenerStub() {
- @Override
- public void onStateChanged(ChatRoom cr, ChatRoom.State newState) {
- if (newState == ChatRoom.State.Created) {
- mWaitLayout.setVisibility(View.GONE);
- // This will remove both the creation fragment and the group info fragment from the back stack
- getFragmentManager().popBackStack();
- getFragmentManager().popBackStack();
- LinphoneActivity.instance().goToChat(cr.getPeerAddress().asStringUriOnly(), mShareInfos);
- } else if (newState == ChatRoom.State.CreationFailed) {
- mWaitLayout.setVisibility(View.GONE);
- LinphoneActivity.instance().displayChatRoomError();
- Log.e("Group chat room for address " + cr.getPeerAddress() + " has failed !");
- }
- }
- };
+ mChatRoomCreationListener = new ChatRoomListenerStub() {
+ @Override
+ public void onStateChanged(ChatRoom cr, ChatRoom.State newState) {
+ if (newState == ChatRoom.State.Created) {
+ mWaitLayout.setVisibility(View.GONE);
+ // This will remove both the creation fragment and the group info fragment from the back stack
+ getFragmentManager().popBackStack();
+ getFragmentManager().popBackStack();
+ LinphoneActivity.instance().goToChat(cr.getPeerAddress().asStringUriOnly(), mShareInfos);
+ } else if (newState == ChatRoom.State.CreationFailed) {
+ mWaitLayout.setVisibility(View.GONE);
+ LinphoneActivity.instance().displayChatRoomError();
+ Log.e("Group chat room for address " + cr.getPeerAddress() + " has failed !");
+ }
+ }
+ };
- mConfirmButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- if (!mIsAlreadyCreatedGroup) {
- mWaitLayout.setVisibility(View.VISIBLE);
- mTempChatRoom = LinphoneManager.getLc().createClientGroupChatRoom(mSubjectField.getText().toString(), mParticipants.size() == 1);
- mTempChatRoom.addListener(mChatRoomCreationListener);
+ mConfirmButton.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ if (!mIsAlreadyCreatedGroup) {
+ mWaitLayout.setVisibility(View.VISIBLE);
+ mTempChatRoom = LinphoneManager.getLc().createClientGroupChatRoom(mSubjectField.getText().toString(), mParticipants.size() == 1);
+ mTempChatRoom.addListener(mChatRoomCreationListener);
- Address addresses[] = new Address[mParticipants.size()];
- int index = 0;
- for (ContactAddress ca : mParticipants) {
- addresses[index] = ca.getAddress();
- index++;
- }
- mTempChatRoom.addParticipants(addresses);
- } else {
- // Subject
- String newSubject = mSubjectField.getText().toString();
- if (!newSubject.equals(mSubject)) {
- mChatRoom.setSubject(newSubject);
- }
+ Address addresses[] = new Address[mParticipants.size()];
+ int index = 0;
+ for (ContactAddress ca : mParticipants) {
+ addresses[index] = ca.getAddress();
+ index++;
+ }
+ mTempChatRoom.addParticipants(addresses);
+ } else {
+ // Subject
+ String newSubject = mSubjectField.getText().toString();
+ if (!newSubject.equals(mSubject)) {
+ mChatRoom.setSubject(newSubject);
+ }
- // Participants removed
- ArrayList toRemove = new ArrayList<>();
- for (Participant p : mChatRoom.getParticipants()) {
- boolean found = false;
- for (ContactAddress c : mParticipants) {
- if (c.getAddress().weakEqual(p.getAddress())) {
- found = true;
- break;
- }
- }
- if (!found) {
- toRemove.add(p);
- }
- }
- Participant[] participantsToRemove = new Participant[toRemove.size()];
- toRemove.toArray(participantsToRemove);
- mChatRoom.removeParticipants(participantsToRemove);
+ // Participants removed
+ ArrayList toRemove = new ArrayList<>();
+ for (Participant p : mChatRoom.getParticipants()) {
+ boolean found = false;
+ for (ContactAddress c : mParticipants) {
+ if (c.getAddress().weakEqual(p.getAddress())) {
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
+ toRemove.add(p);
+ }
+ }
+ Participant[] participantsToRemove = new Participant[toRemove.size()];
+ toRemove.toArray(participantsToRemove);
+ mChatRoom.removeParticipants(participantsToRemove);
- // Participants added
- ArrayList toAdd = new ArrayList<>();
- for (ContactAddress c : mParticipants) {
- boolean found = false;
- for (Participant p : mChatRoom.getParticipants()) {
- if (p.getAddress().weakEqual(c.getAddress())) {
- // Admin rights
- if (c.isAdmin() != p.isAdmin()) {
- mChatRoom.setParticipantAdminStatus(p, c.isAdmin());
- }
- found = true;
- break;
- }
- }
- if (!found) {
- Address addr = c.getAddress();
- if (addr != null) {
- toAdd.add(addr);
- } else {
- //TODO error
- }
- }
- }
- Address[] participantsToAdd = new Address[toAdd.size()];
- toAdd.toArray(participantsToAdd);
- mChatRoom.addParticipants(participantsToAdd);
+ // Participants added
+ ArrayList toAdd = new ArrayList<>();
+ for (ContactAddress c : mParticipants) {
+ boolean found = false;
+ for (Participant p : mChatRoom.getParticipants()) {
+ if (p.getAddress().weakEqual(c.getAddress())) {
+ // Admin rights
+ if (c.isAdmin() != p.isAdmin()) {
+ mChatRoom.setParticipantAdminStatus(p, c.isAdmin());
+ }
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
+ Address addr = c.getAddress();
+ if (addr != null) {
+ toAdd.add(addr);
+ } else {
+ //TODO error
+ }
+ }
+ }
+ Address[] participantsToAdd = new Address[toAdd.size()];
+ toAdd.toArray(participantsToAdd);
+ mChatRoom.addParticipants(participantsToAdd);
- LinphoneActivity.instance().goToChat(mGroupChatRoomAddress.asString(), null);
- }
- }
- });
- mConfirmButton.setEnabled(mSubjectField.getText().length() > 0 && mParticipants.size() > 0);
+ LinphoneActivity.instance().goToChat(mGroupChatRoomAddress.asString(), null);
+ }
+ }
+ });
+ mConfirmButton.setEnabled(mSubjectField.getText().length() > 0 && mParticipants.size() > 0);
- if (!mIsEditionEnabled) {
- mSubjectField.setEnabled(false);
- mConfirmButton.setVisibility(View.INVISIBLE);
- mAddParticipantsButton.setVisibility(View.GONE);
- }
+ if (!mIsEditionEnabled) {
+ mSubjectField.setEnabled(false);
+ mConfirmButton.setVisibility(View.INVISIBLE);
+ mAddParticipantsButton.setVisibility(View.GONE);
+ }
- mWaitLayout = view.findViewById(R.id.waitScreen);
- mWaitLayout.setVisibility(View.GONE);
+ mWaitLayout = view.findViewById(R.id.waitScreen);
+ mWaitLayout.setVisibility(View.GONE);
- if (mChatRoom != null) {
- mChatRoom.addListener(this);
- }
+ if (mChatRoom != null) {
+ mChatRoom.addListener(this);
+ }
- return view;
- }
+ return view;
+ }
- @Override
- public void onResume() {
- super.onResume();
+ @Override
+ public void onResume() {
+ super.onResume();
- InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(INPUT_METHOD_SERVICE);
- if (getActivity().getCurrentFocus() != null) {
- inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
- }
- }
+ InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(INPUT_METHOD_SERVICE);
+ if (getActivity().getCurrentFocus() != null) {
+ inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
+ }
+ }
- @Override
- public void onPause() {
- if (mTempChatRoom != null) {
- mTempChatRoom.removeListener(mChatRoomCreationListener);
- }
- super.onPause();
- }
+ @Override
+ public void onPause() {
+ if (mTempChatRoom != null) {
+ mTempChatRoom.removeListener(mChatRoomCreationListener);
+ }
+ super.onPause();
+ }
- @Override
- public void onDestroy() {
- if (mChatRoom != null) {
- mChatRoom.removeListener(this);
- }
- super.onDestroy();
- }
+ @Override
+ public void onDestroy() {
+ if (mChatRoom != null) {
+ mChatRoom.removeListener(this);
+ }
+ super.onDestroy();
+ }
- private void refreshParticipantsList() {
- if (mChatRoom == null) return;
- mParticipants = new ArrayList<>();
- for (Participant p : mChatRoom.getParticipants()) {
- Address a = p.getAddress();
- LinphoneContact c = ContactsManager.getInstance().findContactFromAddress(a);
- if (c == null) {
- c = new LinphoneContact();
- String displayName = LinphoneUtils.getAddressDisplayName(a);
- c.setFullName(displayName);
- }
- ContactAddress ca = new ContactAddress(c, a.asString(), "", c.isFriend(), p.isAdmin());
- mParticipants.add(ca);
- }
+ private void refreshParticipantsList() {
+ if (mChatRoom == null) return;
+ mParticipants = new ArrayList<>();
+ for (Participant p : mChatRoom.getParticipants()) {
+ Address a = p.getAddress();
+ LinphoneContact c = ContactsManager.getInstance().findContactFromAddress(a);
+ if (c == null) {
+ c = new LinphoneContact();
+ String displayName = LinphoneUtils.getAddressDisplayName(a);
+ c.setFullName(displayName);
+ }
+ ContactAddress ca = new ContactAddress(c, a.asString(), "", c.isFriend(), p.isAdmin());
+ mParticipants.add(ca);
+ }
- mAdapter.updateDataSet(mParticipants);
- mAdapter.setChatRoom(mChatRoom);
+ mAdapter.updateDataSet(mParticipants);
+ mAdapter.setChatRoom(mChatRoom);
}
private void refreshAdminRights() {
- mAdapter.setAdminFeaturesVisible(mIsEditionEnabled);
- mAdapter.setChatRoom(mChatRoom);
- mSubjectField.setEnabled(mIsEditionEnabled);
- mConfirmButton.setVisibility(mIsEditionEnabled ? View.VISIBLE : View.INVISIBLE);
- mAddParticipantsButton.setVisibility(mIsEditionEnabled ? View.VISIBLE : View.GONE);
+ mAdapter.setAdminFeaturesVisible(mIsEditionEnabled);
+ mAdapter.setChatRoom(mChatRoom);
+ mSubjectField.setEnabled(mIsEditionEnabled);
+ mConfirmButton.setVisibility(mIsEditionEnabled ? View.VISIBLE : View.INVISIBLE);
+ mAddParticipantsButton.setVisibility(mIsEditionEnabled ? View.VISIBLE : View.GONE);
}
private void displayMeAdminStatusUpdated() {
- if (mAdminStateChangedDialog != null) mAdminStateChangedDialog.dismiss();
+ if (mAdminStateChangedDialog != null) mAdminStateChangedDialog.dismiss();
- mAdminStateChangedDialog = LinphoneActivity.instance().displayDialog(getString(mIsEditionEnabled ? R.string.chat_room_you_are_now_admin : R.string.chat_room_you_are_no_longer_admin));
- Button delete = mAdminStateChangedDialog.findViewById(R.id.delete_button);
- Button cancel = mAdminStateChangedDialog.findViewById(R.id.cancel);
- delete.setVisibility(View.GONE);
- cancel.setText(getString(R.string.ok));
- cancel.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- mAdminStateChangedDialog.dismiss();
- }
- });
+ mAdminStateChangedDialog = LinphoneActivity.instance().displayDialog(getString(mIsEditionEnabled ? R.string.chat_room_you_are_now_admin : R.string.chat_room_you_are_no_longer_admin));
+ Button delete = mAdminStateChangedDialog.findViewById(R.id.delete_button);
+ Button cancel = mAdminStateChangedDialog.findViewById(R.id.cancel);
+ delete.setVisibility(View.GONE);
+ cancel.setText(getString(R.string.ok));
+ cancel.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ mAdminStateChangedDialog.dismiss();
+ }
+ });
- mAdminStateChangedDialog.show();
+ mAdminStateChangedDialog.show();
}
- @Override
- public void onParticipantAdminStatusChanged(ChatRoom cr, EventLog event_log) {
- if (mChatRoom.getMe().isAdmin() != mIsEditionEnabled) {
- // Either we weren't admin and we are now or the other way around
- mIsEditionEnabled = mChatRoom.getMe().isAdmin();
- displayMeAdminStatusUpdated();
- refreshAdminRights();
- }
- refreshParticipantsList();
- }
+ @Override
+ public void onParticipantAdminStatusChanged(ChatRoom cr, EventLog event_log) {
+ if (mChatRoom.getMe().isAdmin() != mIsEditionEnabled) {
+ // Either we weren't admin and we are now or the other way around
+ mIsEditionEnabled = mChatRoom.getMe().isAdmin();
+ displayMeAdminStatusUpdated();
+ refreshAdminRights();
+ }
+ refreshParticipantsList();
+ }
- @Override
- public void onSubjectChanged(ChatRoom cr, EventLog event_log) {
- mSubjectField.setText(event_log.getSubject());
- }
+ @Override
+ public void onSubjectChanged(ChatRoom cr, EventLog event_log) {
+ mSubjectField.setText(event_log.getSubject());
+ }
- @Override
- public void onConferenceJoined(ChatRoom cr, EventLog event_log) {
- }
+ @Override
+ public void onConferenceJoined(ChatRoom cr, EventLog event_log) {
+ }
- @Override
- public void onConferenceLeft(ChatRoom cr, EventLog event_log) {
- }
+ @Override
+ public void onConferenceLeft(ChatRoom cr, EventLog event_log) {
+ }
- @Override
- public void onParticipantAdded(ChatRoom cr, EventLog event_log) {
- refreshParticipantsList();
- }
+ @Override
+ public void onParticipantAdded(ChatRoom cr, EventLog event_log) {
+ refreshParticipantsList();
+ }
- @Override
- public void onParticipantRemoved(ChatRoom cr, EventLog event_log) {
- refreshParticipantsList();
- }
+ @Override
+ public void onParticipantRemoved(ChatRoom cr, EventLog event_log) {
+ refreshParticipantsList();
+ }
- @Override
- public void onChatMessageShouldBeStored(ChatRoom cr, ChatMessage msg) {
+ @Override
+ public void onChatMessageShouldBeStored(ChatRoom cr, ChatMessage msg) {
- }
+ }
- @Override
- public void onParticipantsCapabilitiesChecked(ChatRoom cr, Address deviceAddr, Address[] participantsAddr) {
+ @Override
+ public void onParticipantsCapabilitiesChecked(ChatRoom cr, Address deviceAddr, Address[] participantsAddr) {
- }
+ }
- @Override
- public void onIsComposingReceived(ChatRoom cr, Address remoteAddr, boolean isComposing) {
+ @Override
+ public void onIsComposingReceived(ChatRoom cr, Address remoteAddr, boolean isComposing) {
- }
+ }
- @Override
- public void onChatMessageSent(ChatRoom cr, EventLog event_log) {
+ @Override
+ public void onChatMessageSent(ChatRoom cr, EventLog event_log) {
- }
+ }
- @Override
- public void onConferenceAddressGeneration(ChatRoom cr) {
+ @Override
+ public void onConferenceAddressGeneration(ChatRoom cr) {
- }
+ }
- @Override
- public void onChatMessageReceived(ChatRoom cr, EventLog event_log) {
+ @Override
+ public void onChatMessageReceived(ChatRoom cr, EventLog event_log) {
- }
+ }
- @Override
- public void onMessageReceived(ChatRoom cr, ChatMessage msg) {
+ @Override
+ public void onMessageReceived(ChatRoom cr, ChatMessage msg) {
- }
+ }
- @Override
- public void onParticipantDeviceRemoved(ChatRoom cr, EventLog event_log) {
+ @Override
+ public void onParticipantDeviceRemoved(ChatRoom cr, EventLog event_log) {
- }
+ }
- @Override
- public void onParticipantDeviceAdded(ChatRoom cr, EventLog event_log) {
+ @Override
+ public void onParticipantDeviceAdded(ChatRoom cr, EventLog event_log) {
- }
+ }
- @Override
- public void onUndecryptableMessageReceived(ChatRoom cr, ChatMessage msg) {
+ @Override
+ public void onUndecryptableMessageReceived(ChatRoom cr, ChatMessage msg) {
- }
+ }
- @Override
- public void onStateChanged(ChatRoom cr, ChatRoom.State newState) {
+ @Override
+ public void onStateChanged(ChatRoom cr, ChatRoom.State newState) {
- }
+ }
- @Override
- public void onParticipantDeviceFetchRequested(ChatRoom cr, Address addr) {
+ @Override
+ public void onParticipantDeviceFetchRequested(ChatRoom cr, Address addr) {
- }
- @Override
- public void onParticipantRegistrationSubscriptionRequested(ChatRoom cr, Address participantAddr){
- }
+ }
- @Override
- public void onParticipantRegistrationUnsubscriptionRequested(ChatRoom cr, Address participantAddr){
- }
+ @Override
+ public void onParticipantRegistrationSubscriptionRequested(ChatRoom cr, Address participantAddr) {
+ }
+
+ @Override
+ public void onParticipantRegistrationUnsubscriptionRequested(ChatRoom cr, Address participantAddr) {
+ }
}
diff --git a/src/android/org/linphone/chat/ImdnFragment.java b/src/android/org/linphone/chat/ImdnFragment.java
index c5da89b6e..0246a2c65 100644
--- a/src/android/org/linphone/chat/ImdnFragment.java
+++ b/src/android/org/linphone/chat/ImdnFragment.java
@@ -46,244 +46,244 @@ import org.linphone.core.ChatRoom;
import org.linphone.core.Core;
import org.linphone.core.ParticipantImdnState;
-public class ImdnFragment extends Fragment{
- private LayoutInflater mInflater;
- private LinearLayout mRead, mReadHeader, mDelivered, mDeliveredHeader, mSent, mSentHeader, mUndelivered, mUndeliveredHeader;
- private ImageView mBackButton;
- private ChatBubbleViewHolder mBubble;
- private ViewGroup mContainer;
+public class ImdnFragment extends Fragment {
+ private LayoutInflater mInflater;
+ private LinearLayout mRead, mReadHeader, mDelivered, mDeliveredHeader, mSent, mSentHeader, mUndelivered, mUndeliveredHeader;
+ private ImageView mBackButton;
+ private ChatBubbleViewHolder mBubble;
+ private ViewGroup mContainer;
- private String mRoomUri, mMessageId;
- private Address mRoomAddr;
- private ChatRoom mRoom;
- private ChatMessage mMessage;
- private ChatMessageListenerStub mListener;
+ private String mRoomUri, mMessageId;
+ private Address mRoomAddr;
+ private ChatRoom mRoom;
+ private ChatMessage mMessage;
+ private ChatMessageListenerStub mListener;
- @Nullable
- @Override
- public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
+ @Nullable
+ @Override
+ public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
- if (getArguments() != null) {
- mRoomUri = getArguments().getString("SipUri");
- mRoomAddr = LinphoneManager.getLc().createAddress(mRoomUri);
- mMessageId = getArguments().getString("MessageId");
- }
- Core core = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- Address proxyConfigContact = core.getDefaultProxyConfig().getContact();
- if (proxyConfigContact != null) {
- mRoom = core.findOneToOneChatRoom(proxyConfigContact, mRoomAddr);
- }
- if (mRoom == null) {
- mRoom = core.getChatRoomFromUri(mRoomAddr.asStringUriOnly());
- }
+ if (getArguments() != null) {
+ mRoomUri = getArguments().getString("SipUri");
+ mRoomAddr = LinphoneManager.getLc().createAddress(mRoomUri);
+ mMessageId = getArguments().getString("MessageId");
+ }
+ Core core = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ Address proxyConfigContact = core.getDefaultProxyConfig().getContact();
+ if (proxyConfigContact != null) {
+ mRoom = core.findOneToOneChatRoom(proxyConfigContact, mRoomAddr);
+ }
+ if (mRoom == null) {
+ mRoom = core.getChatRoomFromUri(mRoomAddr.asStringUriOnly());
+ }
- mInflater = inflater;
- mContainer = container;
- View view = mInflater.inflate(R.layout.chat_imdn, container, false);
+ mInflater = inflater;
+ mContainer = container;
+ View view = mInflater.inflate(R.layout.chat_imdn, container, false);
- mBackButton = view.findViewById(R.id.back);
- mBackButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- if (LinphoneActivity.instance().isTablet()) {
- LinphoneActivity.instance().goToChat(mRoomUri, null);
- } else {
- LinphoneActivity.instance().onBackPressed();
- }
- }
- });
+ mBackButton = view.findViewById(R.id.back);
+ mBackButton.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ if (LinphoneActivity.instance().isTablet()) {
+ LinphoneActivity.instance().goToChat(mRoomUri, null);
+ } else {
+ LinphoneActivity.instance().onBackPressed();
+ }
+ }
+ });
- mRead = view.findViewById(R.id.read_layout);
- mDelivered = view.findViewById(R.id.delivered_layout);
- mSent = view.findViewById(R.id.sent_layout);
- mUndelivered = view.findViewById(R.id.undelivered_layout);
- mReadHeader = view.findViewById(R.id.read_layout_header);
- mDeliveredHeader = view.findViewById(R.id.delivered_layout_header);
- mSentHeader = view.findViewById(R.id.sent_layout_header);
- mUndeliveredHeader = view.findViewById(R.id.undelivered_layout_header);
+ mRead = view.findViewById(R.id.read_layout);
+ mDelivered = view.findViewById(R.id.delivered_layout);
+ mSent = view.findViewById(R.id.sent_layout);
+ mUndelivered = view.findViewById(R.id.undelivered_layout);
+ mReadHeader = view.findViewById(R.id.read_layout_header);
+ mDeliveredHeader = view.findViewById(R.id.delivered_layout_header);
+ mSentHeader = view.findViewById(R.id.sent_layout_header);
+ mUndeliveredHeader = view.findViewById(R.id.undelivered_layout_header);
- mBubble = new ChatBubbleViewHolder(view.findViewById(R.id.bubble));
- mBubble.eventLayout.setVisibility(View.GONE);
- mBubble.bubbleLayout.setVisibility(View.VISIBLE);
- mBubble.delete.setVisibility(View.GONE);
- mBubble.messageText.setVisibility(View.GONE);
- mBubble.messageImage.setVisibility(View.GONE);
- mBubble.fileTransferLayout.setVisibility(View.GONE);
- mBubble.fileName.setVisibility(View.GONE);
- mBubble.openFileButton.setVisibility(View.GONE);
- mBubble.messageStatus.setVisibility(View.INVISIBLE);
- mBubble.messageSendingInProgress.setVisibility(View.GONE);
- mBubble.imdmLayout.setVisibility(View.INVISIBLE);
- mBubble.contactPicture.setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap());
+ mBubble = new ChatBubbleViewHolder(view.findViewById(R.id.bubble));
+ mBubble.eventLayout.setVisibility(View.GONE);
+ mBubble.bubbleLayout.setVisibility(View.VISIBLE);
+ mBubble.delete.setVisibility(View.GONE);
+ mBubble.messageText.setVisibility(View.GONE);
+ mBubble.messageImage.setVisibility(View.GONE);
+ mBubble.fileTransferLayout.setVisibility(View.GONE);
+ mBubble.fileName.setVisibility(View.GONE);
+ mBubble.openFileButton.setVisibility(View.GONE);
+ mBubble.messageStatus.setVisibility(View.INVISIBLE);
+ mBubble.messageSendingInProgress.setVisibility(View.GONE);
+ mBubble.imdmLayout.setVisibility(View.INVISIBLE);
+ mBubble.contactPicture.setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap());
- mMessage = mRoom.findMessage(mMessageId);
- mListener = new ChatMessageListenerStub() {
- @Override
- public void onParticipantImdnStateChanged(ChatMessage msg, ParticipantImdnState state) {
- refreshInfo();
- }
- };
- mMessage.setListener(mListener);
+ mMessage = mRoom.findMessage(mMessageId);
+ mListener = new ChatMessageListenerStub() {
+ @Override
+ public void onParticipantImdnStateChanged(ChatMessage msg, ParticipantImdnState state) {
+ refreshInfo();
+ }
+ };
+ mMessage.setListener(mListener);
- RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
- layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
- layoutParams.setMargins(100, 10, 10, 10);
- if (mMessage.isOutgoing()) {
- mBubble.background.setBackgroundResource(R.drawable.resizable_chat_bubble_outgoing);
- Compatibility.setTextAppearance(mBubble.contactName, getActivity(), R.style.font3);
- Compatibility.setTextAppearance(mBubble.fileTransferAction, getActivity(), R.style.font15);
- mBubble.fileTransferAction.setBackgroundResource(R.drawable.resizable_confirm_delete_button);
- mBubble.contactPictureMask.setImageResource(R.drawable.avatar_chat_mask_outgoing);
- } else {
- mBubble.background.setBackgroundResource(R.drawable.resizable_chat_bubble_incoming);
- Compatibility.setTextAppearance(mBubble.contactName, getActivity(), R.style.font9);
- Compatibility.setTextAppearance(mBubble.fileTransferAction, getActivity(), R.style.font8);
- mBubble.fileTransferAction.setBackgroundResource(R.drawable.resizable_assistant_button);
- mBubble.contactPictureMask.setImageResource(R.drawable.avatar_chat_mask);
- }
+ RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
+ layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
+ layoutParams.setMargins(100, 10, 10, 10);
+ if (mMessage.isOutgoing()) {
+ mBubble.background.setBackgroundResource(R.drawable.resizable_chat_bubble_outgoing);
+ Compatibility.setTextAppearance(mBubble.contactName, getActivity(), R.style.font3);
+ Compatibility.setTextAppearance(mBubble.fileTransferAction, getActivity(), R.style.font15);
+ mBubble.fileTransferAction.setBackgroundResource(R.drawable.resizable_confirm_delete_button);
+ mBubble.contactPictureMask.setImageResource(R.drawable.avatar_chat_mask_outgoing);
+ } else {
+ mBubble.background.setBackgroundResource(R.drawable.resizable_chat_bubble_incoming);
+ Compatibility.setTextAppearance(mBubble.contactName, getActivity(), R.style.font9);
+ Compatibility.setTextAppearance(mBubble.fileTransferAction, getActivity(), R.style.font8);
+ mBubble.fileTransferAction.setBackgroundResource(R.drawable.resizable_assistant_button);
+ mBubble.contactPictureMask.setImageResource(R.drawable.avatar_chat_mask);
+ }
- return view;
- }
+ return view;
+ }
- @Override
- public void onResume() {
- super.onResume();
+ @Override
+ public void onResume() {
+ super.onResume();
- refreshInfo();
- }
+ refreshInfo();
+ }
- private void refreshInfo() {
- Address remoteSender = mMessage.getFromAddress();
- LinphoneContact contact = ContactsManager.getInstance().findContactFromAddress(remoteSender);
- String displayName;
+ private void refreshInfo() {
+ Address remoteSender = mMessage.getFromAddress();
+ LinphoneContact contact = ContactsManager.getInstance().findContactFromAddress(remoteSender);
+ String displayName;
- if (contact != null) {
- if (contact.getFullName() != null) {
- displayName = contact.getFullName();
- } else {
- displayName = LinphoneUtils.getAddressDisplayName(remoteSender);
- }
+ if (contact != null) {
+ if (contact.getFullName() != null) {
+ displayName = contact.getFullName();
+ } else {
+ displayName = LinphoneUtils.getAddressDisplayName(remoteSender);
+ }
- mBubble.contactPicture.setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap());
- if (contact.hasPhoto()) {
- LinphoneUtils.setThumbnailPictureFromUri(getActivity(), mBubble.contactPicture, contact.getThumbnailUri());
- }
- } else {
- displayName = LinphoneUtils.getAddressDisplayName(remoteSender);
- mBubble.contactPicture.setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap());
- }
- mBubble.contactName.setText(LinphoneUtils.timestampToHumanDate(getActivity(), mMessage.getTime(), R.string.messages_date_format) + " - " + displayName);
+ mBubble.contactPicture.setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap());
+ if (contact.hasPhoto()) {
+ LinphoneUtils.setThumbnailPictureFromUri(getActivity(), mBubble.contactPicture, contact.getThumbnailUri());
+ }
+ } else {
+ displayName = LinphoneUtils.getAddressDisplayName(remoteSender);
+ mBubble.contactPicture.setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap());
+ }
+ mBubble.contactName.setText(LinphoneUtils.timestampToHumanDate(getActivity(), mMessage.getTime(), R.string.messages_date_format) + " - " + displayName);
- if (mMessage.hasTextContent()) {
- String msg = mMessage.getTextContent();
- Spanned text = LinphoneUtils.getTextWithHttpLinks(msg);
- mBubble.messageText.setText(text);
- mBubble.messageText.setMovementMethod(LinkMovementMethod.getInstance());
- mBubble.messageText.setVisibility(View.VISIBLE);
- }
+ if (mMessage.hasTextContent()) {
+ String msg = mMessage.getTextContent();
+ Spanned text = LinphoneUtils.getTextWithHttpLinks(msg);
+ mBubble.messageText.setText(text);
+ mBubble.messageText.setMovementMethod(LinkMovementMethod.getInstance());
+ mBubble.messageText.setVisibility(View.VISIBLE);
+ }
- String appData = mMessage.getAppdata();
- if (appData != null) { // Something to display
- mBubble.fileName.setVisibility(View.VISIBLE);
- mBubble.fileName.setText(LinphoneUtils.getNameFromFilePath(appData));
- // We purposely chose not to display the image
- }
+ String appData = mMessage.getAppdata();
+ if (appData != null) { // Something to display
+ mBubble.fileName.setVisibility(View.VISIBLE);
+ mBubble.fileName.setText(LinphoneUtils.getNameFromFilePath(appData));
+ // We purposely chose not to display the image
+ }
- mRead.removeAllViews();
- mDelivered.removeAllViews();
- mSent.removeAllViews();
- mUndelivered.removeAllViews();
+ mRead.removeAllViews();
+ mDelivered.removeAllViews();
+ mSent.removeAllViews();
+ mUndelivered.removeAllViews();
- ParticipantImdnState[] participants = mMessage.getParticipantsByImdnState(ChatMessage.State.Displayed);
- mReadHeader.setVisibility(participants.length == 0 ? View.GONE : View.VISIBLE);
- boolean first = true;
- for (ParticipantImdnState participant : participants) {
- Address address = participant.getParticipant().getAddress();
+ ParticipantImdnState[] participants = mMessage.getParticipantsByImdnState(ChatMessage.State.Displayed);
+ mReadHeader.setVisibility(participants.length == 0 ? View.GONE : View.VISIBLE);
+ boolean first = true;
+ for (ParticipantImdnState participant : participants) {
+ Address address = participant.getParticipant().getAddress();
- LinphoneContact participantContact = ContactsManager.getInstance().findContactFromAddress(address);
- String participantDisplayName = participantContact != null ? participantContact.getFullName() : LinphoneUtils.getAddressDisplayName(address);
+ LinphoneContact participantContact = ContactsManager.getInstance().findContactFromAddress(address);
+ String participantDisplayName = participantContact != null ? participantContact.getFullName() : LinphoneUtils.getAddressDisplayName(address);
- View v = mInflater.inflate(R.layout.chat_imdn_cell, mContainer, false);
- v.findViewById(R.id.separator).setVisibility(first ? View.GONE : View.VISIBLE);
- ((TextView)v.findViewById(R.id.time)).setText(LinphoneUtils.timestampToHumanDate(getActivity(), participant.getStateChangeTime(), R.string.messages_date_format));
- ((TextView)v.findViewById(R.id.name)).setText(participantDisplayName);
- if (participantContact != null && participantContact.hasPhoto()) {
- LinphoneUtils.setThumbnailPictureFromUri(getActivity(), ((ImageView)v.findViewById(R.id.contact_picture)), participantContact.getThumbnailUri());
- } else {
- ((ImageView)v.findViewById(R.id.contact_picture)).setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap());
- }
+ View v = mInflater.inflate(R.layout.chat_imdn_cell, mContainer, false);
+ v.findViewById(R.id.separator).setVisibility(first ? View.GONE : View.VISIBLE);
+ ((TextView) v.findViewById(R.id.time)).setText(LinphoneUtils.timestampToHumanDate(getActivity(), participant.getStateChangeTime(), R.string.messages_date_format));
+ ((TextView) v.findViewById(R.id.name)).setText(participantDisplayName);
+ if (participantContact != null && participantContact.hasPhoto()) {
+ LinphoneUtils.setThumbnailPictureFromUri(getActivity(), ((ImageView) v.findViewById(R.id.contact_picture)), participantContact.getThumbnailUri());
+ } else {
+ ((ImageView) v.findViewById(R.id.contact_picture)).setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap());
+ }
- mRead.addView(v);
- first = false;
- }
+ mRead.addView(v);
+ first = false;
+ }
- participants = mMessage.getParticipantsByImdnState(ChatMessage.State.DeliveredToUser);
- mDeliveredHeader.setVisibility(participants.length == 0 ? View.GONE : View.VISIBLE);
- first = true;
- for (ParticipantImdnState participant : participants) {
- Address address = participant.getParticipant().getAddress();
+ participants = mMessage.getParticipantsByImdnState(ChatMessage.State.DeliveredToUser);
+ mDeliveredHeader.setVisibility(participants.length == 0 ? View.GONE : View.VISIBLE);
+ first = true;
+ for (ParticipantImdnState participant : participants) {
+ Address address = participant.getParticipant().getAddress();
- LinphoneContact participantContact = ContactsManager.getInstance().findContactFromAddress(address);
- String participantDisplayName = participantContact != null ? participantContact.getFullName() : LinphoneUtils.getAddressDisplayName(address);
+ LinphoneContact participantContact = ContactsManager.getInstance().findContactFromAddress(address);
+ String participantDisplayName = participantContact != null ? participantContact.getFullName() : LinphoneUtils.getAddressDisplayName(address);
- View v = mInflater.inflate(R.layout.chat_imdn_cell, mContainer, false);
- v.findViewById(R.id.separator).setVisibility(first ? View.GONE : View.VISIBLE);
- ((TextView)v.findViewById(R.id.time)).setText(LinphoneUtils.timestampToHumanDate(getActivity(), participant.getStateChangeTime(), R.string.messages_date_format));
- ((TextView)v.findViewById(R.id.name)).setText(participantDisplayName);
- if (participantContact != null && participantContact.hasPhoto()) {
- LinphoneUtils.setThumbnailPictureFromUri(getActivity(), ((ImageView)v.findViewById(R.id.contact_picture)), participantContact.getThumbnailUri());
- } else {
- ((ImageView)v.findViewById(R.id.contact_picture)).setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap());
- }
+ View v = mInflater.inflate(R.layout.chat_imdn_cell, mContainer, false);
+ v.findViewById(R.id.separator).setVisibility(first ? View.GONE : View.VISIBLE);
+ ((TextView) v.findViewById(R.id.time)).setText(LinphoneUtils.timestampToHumanDate(getActivity(), participant.getStateChangeTime(), R.string.messages_date_format));
+ ((TextView) v.findViewById(R.id.name)).setText(participantDisplayName);
+ if (participantContact != null && participantContact.hasPhoto()) {
+ LinphoneUtils.setThumbnailPictureFromUri(getActivity(), ((ImageView) v.findViewById(R.id.contact_picture)), participantContact.getThumbnailUri());
+ } else {
+ ((ImageView) v.findViewById(R.id.contact_picture)).setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap());
+ }
- mDelivered.addView(v);
- first = false;
- }
+ mDelivered.addView(v);
+ first = false;
+ }
- participants = mMessage.getParticipantsByImdnState(ChatMessage.State.Delivered);
- mSentHeader.setVisibility(participants.length == 0 ? View.GONE : View.VISIBLE);
- first = true;
- for (ParticipantImdnState participant : participants) {
- Address address = participant.getParticipant().getAddress();
+ participants = mMessage.getParticipantsByImdnState(ChatMessage.State.Delivered);
+ mSentHeader.setVisibility(participants.length == 0 ? View.GONE : View.VISIBLE);
+ first = true;
+ for (ParticipantImdnState participant : participants) {
+ Address address = participant.getParticipant().getAddress();
- LinphoneContact participantContact = ContactsManager.getInstance().findContactFromAddress(address);
- String participantDisplayName = participantContact != null ? participantContact.getFullName() : LinphoneUtils.getAddressDisplayName(address);
+ LinphoneContact participantContact = ContactsManager.getInstance().findContactFromAddress(address);
+ String participantDisplayName = participantContact != null ? participantContact.getFullName() : LinphoneUtils.getAddressDisplayName(address);
- View v = mInflater.inflate(R.layout.chat_imdn_cell, mContainer, false);
- v.findViewById(R.id.separator).setVisibility(first ? View.GONE : View.VISIBLE);
- ((TextView)v.findViewById(R.id.time)).setText(LinphoneUtils.timestampToHumanDate(getActivity(), participant.getStateChangeTime(), R.string.messages_date_format));
- ((TextView)v.findViewById(R.id.name)).setText(participantDisplayName);
- if (participantContact != null && participantContact.hasPhoto()) {
- LinphoneUtils.setThumbnailPictureFromUri(getActivity(), ((ImageView)v.findViewById(R.id.contact_picture)), participantContact.getThumbnailUri());
- } else {
- ((ImageView)v.findViewById(R.id.contact_picture)).setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap());
- }
+ View v = mInflater.inflate(R.layout.chat_imdn_cell, mContainer, false);
+ v.findViewById(R.id.separator).setVisibility(first ? View.GONE : View.VISIBLE);
+ ((TextView) v.findViewById(R.id.time)).setText(LinphoneUtils.timestampToHumanDate(getActivity(), participant.getStateChangeTime(), R.string.messages_date_format));
+ ((TextView) v.findViewById(R.id.name)).setText(participantDisplayName);
+ if (participantContact != null && participantContact.hasPhoto()) {
+ LinphoneUtils.setThumbnailPictureFromUri(getActivity(), ((ImageView) v.findViewById(R.id.contact_picture)), participantContact.getThumbnailUri());
+ } else {
+ ((ImageView) v.findViewById(R.id.contact_picture)).setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap());
+ }
- mSent.addView(v);
- first = false;
- }
+ mSent.addView(v);
+ first = false;
+ }
- participants = mMessage.getParticipantsByImdnState(ChatMessage.State.NotDelivered);
- mUndeliveredHeader.setVisibility(participants.length == 0 ? View.GONE : View.VISIBLE);
- first = true;
- for (ParticipantImdnState participant : participants) {
- Address address = participant.getParticipant().getAddress();
+ participants = mMessage.getParticipantsByImdnState(ChatMessage.State.NotDelivered);
+ mUndeliveredHeader.setVisibility(participants.length == 0 ? View.GONE : View.VISIBLE);
+ first = true;
+ for (ParticipantImdnState participant : participants) {
+ Address address = participant.getParticipant().getAddress();
- LinphoneContact participantContact = ContactsManager.getInstance().findContactFromAddress(address);
- String participantDisplayName = participantContact != null ? participantContact.getFullName() : LinphoneUtils.getAddressDisplayName(address);
+ LinphoneContact participantContact = ContactsManager.getInstance().findContactFromAddress(address);
+ String participantDisplayName = participantContact != null ? participantContact.getFullName() : LinphoneUtils.getAddressDisplayName(address);
- View v = mInflater.inflate(R.layout.chat_imdn_cell, mContainer, false);
- v.findViewById(R.id.separator).setVisibility(first ? View.GONE : View.VISIBLE);
- ((TextView)v.findViewById(R.id.name)).setText(participantDisplayName);
- if (participantContact != null && participantContact.hasPhoto()) {
- LinphoneUtils.setThumbnailPictureFromUri(getActivity(), ((ImageView)v.findViewById(R.id.contact_picture)), participantContact.getThumbnailUri());
- } else {
- ((ImageView)v.findViewById(R.id.contact_picture)).setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap());
- }
+ View v = mInflater.inflate(R.layout.chat_imdn_cell, mContainer, false);
+ v.findViewById(R.id.separator).setVisibility(first ? View.GONE : View.VISIBLE);
+ ((TextView) v.findViewById(R.id.name)).setText(participantDisplayName);
+ if (participantContact != null && participantContact.hasPhoto()) {
+ LinphoneUtils.setThumbnailPictureFromUri(getActivity(), ((ImageView) v.findViewById(R.id.contact_picture)), participantContact.getThumbnailUri());
+ } else {
+ ((ImageView) v.findViewById(R.id.contact_picture)).setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap());
+ }
- mUndelivered.addView(v);
- first = false;
- }
- }
+ mUndelivered.addView(v);
+ first = false;
+ }
+ }
}
diff --git a/src/android/org/linphone/compatibility/ApiElevenPlus.java b/src/android/org/linphone/compatibility/ApiElevenPlus.java
index cdfcaa8d2..299e30146 100644
--- a/src/android/org/linphone/compatibility/ApiElevenPlus.java
+++ b/src/android/org/linphone/compatibility/ApiElevenPlus.java
@@ -1,9 +1,5 @@
package org.linphone.compatibility;
-import java.util.ArrayList;
-
-import org.linphone.R;
-
import android.annotation.TargetApi;
import android.app.AlarmManager;
import android.app.Notification;
@@ -20,6 +16,10 @@ import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Intents.Insert;
import android.widget.TextView;
+import org.linphone.R;
+
+import java.util.ArrayList;
+
/*
ApiElevenPlus.java
Copyright (C) 2017 Belledonne Communications, Grenoble, France
@@ -42,147 +42,147 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
@TargetApi(11)
public class ApiElevenPlus {
- @SuppressWarnings("deprecation")
- public static Notification createMessageNotification(Context context,
- int msgCount, String msgSender, String msg, Bitmap contactIcon,
- PendingIntent intent) {
- String title;
- if (msgCount == 1) {
- title = msgSender;
- } else {
- title = context.getString(R.string.unread_messages)
- .replace("%i", String.valueOf(msgCount));
- }
+ @SuppressWarnings("deprecation")
+ public static Notification createMessageNotification(Context context,
+ int msgCount, String msgSender, String msg, Bitmap contactIcon,
+ PendingIntent intent) {
+ String title;
+ if (msgCount == 1) {
+ title = msgSender;
+ } else {
+ title = context.getString(R.string.unread_messages)
+ .replace("%i", String.valueOf(msgCount));
+ }
- Notification notif = new Notification.Builder(context)
- .setContentTitle(title)
- .setContentText(msg)
- .setContentIntent(intent)
- .setSmallIcon(R.drawable.chat)
- .setAutoCancel(true)
- .setDefaults(
- Notification.DEFAULT_LIGHTS
- | Notification.DEFAULT_SOUND
- | Notification.DEFAULT_VIBRATE)
- .setWhen(System.currentTimeMillis())
- .setNumber(msgCount)
- .setLargeIcon(contactIcon).getNotification();
+ Notification notif = new Notification.Builder(context)
+ .setContentTitle(title)
+ .setContentText(msg)
+ .setContentIntent(intent)
+ .setSmallIcon(R.drawable.chat)
+ .setAutoCancel(true)
+ .setDefaults(
+ Notification.DEFAULT_LIGHTS
+ | Notification.DEFAULT_SOUND
+ | Notification.DEFAULT_VIBRATE)
+ .setWhen(System.currentTimeMillis())
+ .setNumber(msgCount)
+ .setLargeIcon(contactIcon).getNotification();
- return notif;
- }
+ return notif;
+ }
- @SuppressWarnings("deprecation")
- public static Notification createInCallNotification(Context context,
- String title, String msg, int iconID, Bitmap contactIcon,
- String contactName, PendingIntent intent) {
+ @SuppressWarnings("deprecation")
+ public static Notification createInCallNotification(Context context,
+ String title, String msg, int iconID, Bitmap contactIcon,
+ String contactName, PendingIntent intent) {
- Notification notif = new Notification.Builder(context).setContentTitle(contactName)
- .setContentText(msg).setSmallIcon(iconID)
- .setAutoCancel(false)
- .setContentIntent(intent)
- .setWhen(System.currentTimeMillis())
- .setLargeIcon(contactIcon).getNotification();
- notif.flags |= Notification.FLAG_ONGOING_EVENT;
+ Notification notif = new Notification.Builder(context).setContentTitle(contactName)
+ .setContentText(msg).setSmallIcon(iconID)
+ .setAutoCancel(false)
+ .setContentIntent(intent)
+ .setWhen(System.currentTimeMillis())
+ .setLargeIcon(contactIcon).getNotification();
+ notif.flags |= Notification.FLAG_ONGOING_EVENT;
- return notif;
- }
+ return notif;
+ }
- @SuppressWarnings("deprecation")
- public static Notification createNotification(Context context, String title, String message, int icon, int level, Bitmap largeIcon, PendingIntent intent, boolean isOngoingEvent) {
- Notification notif;
+ @SuppressWarnings("deprecation")
+ public static Notification createNotification(Context context, String title, String message, int icon, int level, Bitmap largeIcon, PendingIntent intent, boolean isOngoingEvent) {
+ Notification notif;
- if (largeIcon != null) {
- notif = new Notification.Builder(context)
- .setContentTitle(title)
- .setContentText(message)
- .setSmallIcon(icon, level)
- .setLargeIcon(largeIcon)
- .setContentIntent(intent)
- .setWhen(System.currentTimeMillis())
- .getNotification();
- } else {
- notif = new Notification.Builder(context)
- .setContentTitle(title)
- .setContentText(message)
- .setSmallIcon(icon, level)
- .setContentIntent(intent)
- .setWhen(System.currentTimeMillis())
- .getNotification();
- }
- if (isOngoingEvent) {
- notif.flags |= Notification.FLAG_ONGOING_EVENT;
- }
+ if (largeIcon != null) {
+ notif = new Notification.Builder(context)
+ .setContentTitle(title)
+ .setContentText(message)
+ .setSmallIcon(icon, level)
+ .setLargeIcon(largeIcon)
+ .setContentIntent(intent)
+ .setWhen(System.currentTimeMillis())
+ .getNotification();
+ } else {
+ notif = new Notification.Builder(context)
+ .setContentTitle(title)
+ .setContentText(message)
+ .setSmallIcon(icon, level)
+ .setContentIntent(intent)
+ .setWhen(System.currentTimeMillis())
+ .getNotification();
+ }
+ if (isOngoingEvent) {
+ notif.flags |= Notification.FLAG_ONGOING_EVENT;
+ }
- return notif;
- }
+ return notif;
+ }
- public static Intent prepareAddContactIntent(String displayName, String sipUri) {
- Intent intent = new Intent(Intent.ACTION_INSERT, Contacts.CONTENT_URI);
- intent.putExtra(ContactsContract.Intents.Insert.NAME, displayName);
+ public static Intent prepareAddContactIntent(String displayName, String sipUri) {
+ Intent intent = new Intent(Intent.ACTION_INSERT, Contacts.CONTENT_URI);
+ intent.putExtra(ContactsContract.Intents.Insert.NAME, displayName);
- if (sipUri != null && sipUri.startsWith("sip:")) {
- sipUri = sipUri.substring(4);
- }
+ if (sipUri != null && sipUri.startsWith("sip:")) {
+ sipUri = sipUri.substring(4);
+ }
- ArrayList data = new ArrayList();
- ContentValues sipAddressRow = new ContentValues();
- sipAddressRow.put(Contacts.Data.MIMETYPE, SipAddress.CONTENT_ITEM_TYPE);
- sipAddressRow.put(SipAddress.SIP_ADDRESS, sipUri);
- data.add(sipAddressRow);
- intent.putParcelableArrayListExtra(Insert.DATA, data);
+ ArrayList data = new ArrayList();
+ ContentValues sipAddressRow = new ContentValues();
+ sipAddressRow.put(Contacts.Data.MIMETYPE, SipAddress.CONTENT_ITEM_TYPE);
+ sipAddressRow.put(SipAddress.SIP_ADDRESS, sipUri);
+ data.add(sipAddressRow);
+ intent.putParcelableArrayListExtra(Insert.DATA, data);
- return intent;
- }
+ return intent;
+ }
- public static Intent prepareEditContactIntentWithSipAddress(int id, String sipUri) {
- Intent intent = new Intent(Intent.ACTION_EDIT, Contacts.CONTENT_URI);
- Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, id);
- intent.setData(contactUri);
+ public static Intent prepareEditContactIntentWithSipAddress(int id, String sipUri) {
+ Intent intent = new Intent(Intent.ACTION_EDIT, Contacts.CONTENT_URI);
+ Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, id);
+ intent.setData(contactUri);
- ArrayList data = new ArrayList();
- ContentValues sipAddressRow = new ContentValues();
- sipAddressRow.put(Contacts.Data.MIMETYPE, SipAddress.CONTENT_ITEM_TYPE);
- sipAddressRow.put(SipAddress.SIP_ADDRESS, sipUri);
- data.add(sipAddressRow);
- intent.putParcelableArrayListExtra(Insert.DATA, data);
+ ArrayList data = new ArrayList();
+ ContentValues sipAddressRow = new ContentValues();
+ sipAddressRow.put(Contacts.Data.MIMETYPE, SipAddress.CONTENT_ITEM_TYPE);
+ sipAddressRow.put(SipAddress.SIP_ADDRESS, sipUri);
+ data.add(sipAddressRow);
+ intent.putParcelableArrayListExtra(Insert.DATA, data);
- return intent;
- }
+ return intent;
+ }
- @SuppressWarnings("deprecation")
- public static Notification createMissedCallNotification(Context context, String title, String text, PendingIntent intent) {
- Notification notif = new Notification.Builder(context)
- .setContentTitle(title)
- .setContentText(text)
- .setContentIntent(intent)
- .setSmallIcon(R.drawable.call_status_missed)
- .setAutoCancel(true)
- .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
- .setWhen(System.currentTimeMillis()).getNotification();
+ @SuppressWarnings("deprecation")
+ public static Notification createMissedCallNotification(Context context, String title, String text, PendingIntent intent) {
+ Notification notif = new Notification.Builder(context)
+ .setContentTitle(title)
+ .setContentText(text)
+ .setContentIntent(intent)
+ .setSmallIcon(R.drawable.call_status_missed)
+ .setAutoCancel(true)
+ .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
+ .setWhen(System.currentTimeMillis()).getNotification();
- return notif;
- }
+ return notif;
+ }
- @SuppressWarnings("deprecation")
- public static Notification createSimpleNotification(Context context, String title, String text, PendingIntent intent) {
- Notification notif = new Notification.Builder(context)
- .setContentTitle(title)
- .setContentText(text)
- .setContentIntent(intent)
- .setSmallIcon(R.drawable.linphone_logo)
- .setAutoCancel(true)
- .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
- .setWhen(System.currentTimeMillis()).getNotification();
+ @SuppressWarnings("deprecation")
+ public static Notification createSimpleNotification(Context context, String title, String text, PendingIntent intent) {
+ Notification notif = new Notification.Builder(context)
+ .setContentTitle(title)
+ .setContentText(text)
+ .setContentIntent(intent)
+ .setSmallIcon(R.drawable.linphone_logo)
+ .setAutoCancel(true)
+ .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
+ .setWhen(System.currentTimeMillis()).getNotification();
- return notif;
- }
+ return notif;
+ }
- @SuppressWarnings("deprecation")
- public static void setTextAppearance(TextView textview, Context context, int style) {
- textview.setTextAppearance(context, style);
- }
+ @SuppressWarnings("deprecation")
+ public static void setTextAppearance(TextView textview, Context context, int style) {
+ textview.setTextAppearance(context, style);
+ }
- public static void scheduleAlarm(AlarmManager alarmManager, int type, long triggerAtMillis, PendingIntent operation) {
- alarmManager.set(type, triggerAtMillis, operation);
- }
+ public static void scheduleAlarm(AlarmManager alarmManager, int type, long triggerAtMillis, PendingIntent operation) {
+ alarmManager.set(type, triggerAtMillis, operation);
+ }
}
diff --git a/src/android/org/linphone/compatibility/ApiNineteenPlus.java b/src/android/org/linphone/compatibility/ApiNineteenPlus.java
index 278224221..9c26fcc0b 100644
--- a/src/android/org/linphone/compatibility/ApiNineteenPlus.java
+++ b/src/android/org/linphone/compatibility/ApiNineteenPlus.java
@@ -24,11 +24,11 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
@TargetApi(19)
public class ApiNineteenPlus {
- public static void scheduleAlarm(AlarmManager alarmManager, int type, long triggerAtMillis, PendingIntent operation) {
- if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
- alarmManager.setExact(type, triggerAtMillis, operation);
- } else {
- alarmManager.set(type, triggerAtMillis, operation);
- }
- }
+ public static void scheduleAlarm(AlarmManager alarmManager, int type, long triggerAtMillis, PendingIntent operation) {
+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
+ alarmManager.setExact(type, triggerAtMillis, operation);
+ } else {
+ alarmManager.set(type, triggerAtMillis, operation);
+ }
+ }
}
diff --git a/src/android/org/linphone/compatibility/ApiSixteenPlus.java b/src/android/org/linphone/compatibility/ApiSixteenPlus.java
index 7a9c518fb..6eb8111a3 100644
--- a/src/android/org/linphone/compatibility/ApiSixteenPlus.java
+++ b/src/android/org/linphone/compatibility/ApiSixteenPlus.java
@@ -1,7 +1,5 @@
package org.linphone.compatibility;
-import org.linphone.R;
-
import android.annotation.TargetApi;
import android.app.FragmentTransaction;
import android.app.Notification;
@@ -11,6 +9,8 @@ import android.content.Intent;
import android.graphics.Bitmap;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
+
+import org.linphone.R;
/*
ApiSixteenPlus.java
Copyright (C) 2017 Belledonne Communications, Grenoble, France
@@ -33,118 +33,118 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
@TargetApi(16)
public class ApiSixteenPlus {
- @SuppressWarnings("deprecation")
- public static Notification createMessageNotification(Context context,
- int msgCount, String msgSender, String msg, Bitmap contactIcon,
- PendingIntent intent) {
- String title;
- if (msgCount == 1) {
- title = msgSender;
- } else {
- title = context.getString(R.string.unread_messages)
- .replace("%i", String.valueOf(msgCount));
- }
+ @SuppressWarnings("deprecation")
+ public static Notification createMessageNotification(Context context,
+ int msgCount, String msgSender, String msg, Bitmap contactIcon,
+ PendingIntent intent) {
+ String title;
+ if (msgCount == 1) {
+ title = msgSender;
+ } else {
+ title = context.getString(R.string.unread_messages)
+ .replace("%i", String.valueOf(msgCount));
+ }
- Notification notif = new Notification.Builder(context)
- .setContentTitle(title)
- .setContentText(msg)
- .setSmallIcon(R.drawable.topbar_chat_notification)
- .setAutoCancel(true)
- .setContentIntent(intent)
- .setDefaults(
- Notification.DEFAULT_LIGHTS
- | Notification.DEFAULT_SOUND
- | Notification.DEFAULT_VIBRATE)
- .setWhen(System.currentTimeMillis())
- .setLargeIcon(contactIcon)
- .setNumber(msgCount)
- .build();
+ Notification notif = new Notification.Builder(context)
+ .setContentTitle(title)
+ .setContentText(msg)
+ .setSmallIcon(R.drawable.topbar_chat_notification)
+ .setAutoCancel(true)
+ .setContentIntent(intent)
+ .setDefaults(
+ Notification.DEFAULT_LIGHTS
+ | Notification.DEFAULT_SOUND
+ | Notification.DEFAULT_VIBRATE)
+ .setWhen(System.currentTimeMillis())
+ .setLargeIcon(contactIcon)
+ .setNumber(msgCount)
+ .build();
- return notif;
- }
+ return notif;
+ }
- public static Notification createInCallNotification(Context context,
- String title, String msg, int iconID, Bitmap contactIcon,
- String contactName, PendingIntent intent) {
+ public static Notification createInCallNotification(Context context,
+ String title, String msg, int iconID, Bitmap contactIcon,
+ String contactName, PendingIntent intent) {
- Notification notif = new Notification.Builder(context).setContentTitle(contactName)
- .setContentText(msg).setSmallIcon(iconID)
- .setAutoCancel(false)
- .setContentIntent(intent)
- .setWhen(System.currentTimeMillis())
- .setLargeIcon(contactIcon).build();
- notif.flags |= Notification.FLAG_ONGOING_EVENT;
+ Notification notif = new Notification.Builder(context).setContentTitle(contactName)
+ .setContentText(msg).setSmallIcon(iconID)
+ .setAutoCancel(false)
+ .setContentIntent(intent)
+ .setWhen(System.currentTimeMillis())
+ .setLargeIcon(contactIcon).build();
+ notif.flags |= Notification.FLAG_ONGOING_EVENT;
- return notif;
- }
+ return notif;
+ }
- public static Notification createNotification(Context context, String title, String message, int icon, int level, Bitmap largeIcon, PendingIntent intent, boolean isOngoingEvent,int priority) {
- Notification notif;
+ public static Notification createNotification(Context context, String title, String message, int icon, int level, Bitmap largeIcon, PendingIntent intent, boolean isOngoingEvent, int priority) {
+ Notification notif;
- if (largeIcon != null) {
- notif = new Notification.Builder(context)
- .setContentTitle(title)
- .setContentText(message)
- .setSmallIcon(icon, level)
- .setLargeIcon(largeIcon)
- .setContentIntent(intent)
- .setWhen(System.currentTimeMillis())
- .setPriority(priority)
- .build();
- } else {
- notif = new Notification.Builder(context)
- .setContentTitle(title)
- .setContentText(message)
- .setSmallIcon(icon, level)
- .setContentIntent(intent)
- .setWhen(System.currentTimeMillis())
- .setPriority(priority)
- .build();
- }
- if (isOngoingEvent) {
- notif.flags |= Notification.FLAG_ONGOING_EVENT;
- }
+ if (largeIcon != null) {
+ notif = new Notification.Builder(context)
+ .setContentTitle(title)
+ .setContentText(message)
+ .setSmallIcon(icon, level)
+ .setLargeIcon(largeIcon)
+ .setContentIntent(intent)
+ .setWhen(System.currentTimeMillis())
+ .setPriority(priority)
+ .build();
+ } else {
+ notif = new Notification.Builder(context)
+ .setContentTitle(title)
+ .setContentText(message)
+ .setSmallIcon(icon, level)
+ .setContentIntent(intent)
+ .setWhen(System.currentTimeMillis())
+ .setPriority(priority)
+ .build();
+ }
+ if (isOngoingEvent) {
+ notif.flags |= Notification.FLAG_ONGOING_EVENT;
+ }
- return notif;
- }
+ return notif;
+ }
- public static void removeGlobalLayoutListener(ViewTreeObserver viewTreeObserver, OnGlobalLayoutListener keyboardListener) {
- viewTreeObserver.removeOnGlobalLayoutListener(keyboardListener);
- }
+ public static void removeGlobalLayoutListener(ViewTreeObserver viewTreeObserver, OnGlobalLayoutListener keyboardListener) {
+ viewTreeObserver.removeOnGlobalLayoutListener(keyboardListener);
+ }
- public static Notification createMissedCallNotification(Context context, String title, String text, PendingIntent intent) {
- Notification notif = new Notification.Builder(context)
- .setContentTitle(title)
- .setContentText(text)
- .setSmallIcon(R.drawable.call_status_missed)
- .setAutoCancel(true)
- .setContentIntent(intent)
- .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
- .setWhen(System.currentTimeMillis())
- .build();
+ public static Notification createMissedCallNotification(Context context, String title, String text, PendingIntent intent) {
+ Notification notif = new Notification.Builder(context)
+ .setContentTitle(title)
+ .setContentText(text)
+ .setSmallIcon(R.drawable.call_status_missed)
+ .setAutoCancel(true)
+ .setContentIntent(intent)
+ .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
+ .setWhen(System.currentTimeMillis())
+ .build();
- return notif;
- }
+ return notif;
+ }
- public static Notification createSimpleNotification(Context context, String title, String text, PendingIntent intent) {
- Notification notif = new Notification.Builder(context)
- .setContentTitle(title)
- .setContentText(text)
- .setSmallIcon(R.drawable.linphone_logo)
- .setAutoCancel(true)
- .setContentIntent(intent)
- .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
- .setWhen(System.currentTimeMillis())
- .build();
+ public static Notification createSimpleNotification(Context context, String title, String text, PendingIntent intent) {
+ Notification notif = new Notification.Builder(context)
+ .setContentTitle(title)
+ .setContentText(text)
+ .setSmallIcon(R.drawable.linphone_logo)
+ .setAutoCancel(true)
+ .setContentIntent(intent)
+ .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
+ .setWhen(System.currentTimeMillis())
+ .build();
- return notif;
- }
+ return notif;
+ }
- public static void startService(Context context, Intent intent) {
- context.startService(intent);
- }
+ public static void startService(Context context, Intent intent) {
+ context.startService(intent);
+ }
- public static void setFragmentTransactionReorderingAllowed(FragmentTransaction transaction, boolean allowed) {
+ public static void setFragmentTransactionReorderingAllowed(FragmentTransaction transaction, boolean allowed) {
- }
+ }
}
diff --git a/src/android/org/linphone/compatibility/ApiTwentyOnePlus.java b/src/android/org/linphone/compatibility/ApiTwentyOnePlus.java
index d633daa18..951b8c0a7 100644
--- a/src/android/org/linphone/compatibility/ApiTwentyOnePlus.java
+++ b/src/android/org/linphone/compatibility/ApiTwentyOnePlus.java
@@ -1,7 +1,5 @@
package org.linphone.compatibility;
-import org.linphone.R;
-
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.PendingIntent;
@@ -10,6 +8,8 @@ import android.graphics.Bitmap;
import android.support.v4.content.ContextCompat;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
+
+import org.linphone.R;
/*
ApiTwentyOnePlus.java
Copyright (C) 2017 Belledonne Communications, Grenoble, France
@@ -32,146 +32,146 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
@TargetApi(21)
public class ApiTwentyOnePlus {
- @SuppressWarnings("deprecation")
- public static Notification createMessageNotification(Context context,
- int msgCount, String msgSender, String msg, Bitmap contactIcon,
- PendingIntent intent) {
- String title;
- if (msgCount == 1) {
- title = msgSender;
- } else {
- title = context.getString(R.string.unread_messages).replace("%i", String.valueOf(msgCount));
- }
+ @SuppressWarnings("deprecation")
+ public static Notification createMessageNotification(Context context,
+ int msgCount, String msgSender, String msg, Bitmap contactIcon,
+ PendingIntent intent) {
+ String title;
+ if (msgCount == 1) {
+ title = msgSender;
+ } else {
+ title = context.getString(R.string.unread_messages).replace("%i", String.valueOf(msgCount));
+ }
- Notification notif = new Notification.Builder(context)
- .setContentTitle(title)
- .setContentText(msg)
- .setSmallIcon(R.drawable.topbar_chat_notification)
- .setAutoCancel(true)
- .setContentIntent(intent)
- .setDefaults(Notification.DEFAULT_SOUND
- | Notification.DEFAULT_VIBRATE)
- .setLargeIcon(contactIcon)
- .setLights(ContextCompat.getColor(context, R.color.notification_color_led),
- context.getResources().getInteger(R.integer.notification_ms_on),
- context.getResources().getInteger(R.integer.notification_ms_off))
- .setCategory(Notification.CATEGORY_MESSAGE)
- .setVisibility(Notification.VISIBILITY_PRIVATE)
- .setPriority(Notification.PRIORITY_HIGH)
- .setNumber(msgCount)
- .setWhen(System.currentTimeMillis())
- .setShowWhen(true)
- .build();
+ Notification notif = new Notification.Builder(context)
+ .setContentTitle(title)
+ .setContentText(msg)
+ .setSmallIcon(R.drawable.topbar_chat_notification)
+ .setAutoCancel(true)
+ .setContentIntent(intent)
+ .setDefaults(Notification.DEFAULT_SOUND
+ | Notification.DEFAULT_VIBRATE)
+ .setLargeIcon(contactIcon)
+ .setLights(ContextCompat.getColor(context, R.color.notification_color_led),
+ context.getResources().getInteger(R.integer.notification_ms_on),
+ context.getResources().getInteger(R.integer.notification_ms_off))
+ .setCategory(Notification.CATEGORY_MESSAGE)
+ .setVisibility(Notification.VISIBILITY_PRIVATE)
+ .setPriority(Notification.PRIORITY_HIGH)
+ .setNumber(msgCount)
+ .setWhen(System.currentTimeMillis())
+ .setShowWhen(true)
+ .build();
- return notif;
- }
+ return notif;
+ }
- public static Notification createInCallNotification(Context context,
- String title, String msg, int iconID, Bitmap contactIcon,
- String contactName, PendingIntent intent) {
+ public static Notification createInCallNotification(Context context,
+ String title, String msg, int iconID, Bitmap contactIcon,
+ String contactName, PendingIntent intent) {
- Notification notif = new Notification.Builder(context).setContentTitle(contactName)
- .setContentText(msg)
- .setSmallIcon(iconID)
- .setAutoCancel(false)
- .setContentIntent(intent)
- .setLargeIcon(contactIcon)
- .setCategory(Notification.CATEGORY_CALL)
- .setVisibility(Notification.VISIBILITY_PUBLIC)
- .setPriority(Notification.PRIORITY_HIGH)
- .setLights(ContextCompat.getColor(context, R.color.notification_color_led),
- context.getResources().getInteger(R.integer.notification_ms_on),
- context.getResources().getInteger(R.integer.notification_ms_off))
- .setShowWhen(true)
- .build();
+ Notification notif = new Notification.Builder(context).setContentTitle(contactName)
+ .setContentText(msg)
+ .setSmallIcon(iconID)
+ .setAutoCancel(false)
+ .setContentIntent(intent)
+ .setLargeIcon(contactIcon)
+ .setCategory(Notification.CATEGORY_CALL)
+ .setVisibility(Notification.VISIBILITY_PUBLIC)
+ .setPriority(Notification.PRIORITY_HIGH)
+ .setLights(ContextCompat.getColor(context, R.color.notification_color_led),
+ context.getResources().getInteger(R.integer.notification_ms_on),
+ context.getResources().getInteger(R.integer.notification_ms_off))
+ .setShowWhen(true)
+ .build();
- return notif;
- }
+ return notif;
+ }
- public static Notification createNotification(Context context, String title, String message, int icon, int level, Bitmap largeIcon, PendingIntent intent, boolean isOngoingEvent,int priority) {
- Notification notif;
+ public static Notification createNotification(Context context, String title, String message, int icon, int level, Bitmap largeIcon, PendingIntent intent, boolean isOngoingEvent, int priority) {
+ Notification notif;
- if (largeIcon != null) {
- notif = new Notification.Builder(context)
- .setContentTitle(title)
- .setContentText(message)
- .setSmallIcon(icon, level)
- .setLargeIcon(largeIcon)
- .setContentIntent(intent)
- .setCategory(Notification.CATEGORY_SERVICE)
- .setVisibility(Notification.VISIBILITY_SECRET)
- .setLights(ContextCompat.getColor(context, R.color.notification_color_led),
- context.getResources().getInteger(R.integer.notification_ms_on),
- context.getResources().getInteger(R.integer.notification_ms_off))
- .setWhen(System.currentTimeMillis())
- .setPriority(priority)
- .setShowWhen(true)
- .build();
- } else {
- notif = new Notification.Builder(context)
- .setContentTitle(title)
- .setContentText(message)
- .setSmallIcon(icon, level)
- .setContentIntent(intent)
- .setCategory(Notification.CATEGORY_SERVICE)
- .setVisibility(Notification.VISIBILITY_SECRET)
- .setLights(ContextCompat.getColor(context, R.color.notification_color_led),
- context.getResources().getInteger(R.integer.notification_ms_on),
- context.getResources().getInteger(R.integer.notification_ms_off))
- .setPriority(priority)
- .setWhen(System.currentTimeMillis())
- .setShowWhen(true)
- .build();
- }
+ if (largeIcon != null) {
+ notif = new Notification.Builder(context)
+ .setContentTitle(title)
+ .setContentText(message)
+ .setSmallIcon(icon, level)
+ .setLargeIcon(largeIcon)
+ .setContentIntent(intent)
+ .setCategory(Notification.CATEGORY_SERVICE)
+ .setVisibility(Notification.VISIBILITY_SECRET)
+ .setLights(ContextCompat.getColor(context, R.color.notification_color_led),
+ context.getResources().getInteger(R.integer.notification_ms_on),
+ context.getResources().getInteger(R.integer.notification_ms_off))
+ .setWhen(System.currentTimeMillis())
+ .setPriority(priority)
+ .setShowWhen(true)
+ .build();
+ } else {
+ notif = new Notification.Builder(context)
+ .setContentTitle(title)
+ .setContentText(message)
+ .setSmallIcon(icon, level)
+ .setContentIntent(intent)
+ .setCategory(Notification.CATEGORY_SERVICE)
+ .setVisibility(Notification.VISIBILITY_SECRET)
+ .setLights(ContextCompat.getColor(context, R.color.notification_color_led),
+ context.getResources().getInteger(R.integer.notification_ms_on),
+ context.getResources().getInteger(R.integer.notification_ms_off))
+ .setPriority(priority)
+ .setWhen(System.currentTimeMillis())
+ .setShowWhen(true)
+ .build();
+ }
- return notif;
- }
+ return notif;
+ }
- public static void removeGlobalLayoutListener(ViewTreeObserver viewTreeObserver, OnGlobalLayoutListener keyboardListener) {
- viewTreeObserver.removeOnGlobalLayoutListener(keyboardListener);
- }
+ public static void removeGlobalLayoutListener(ViewTreeObserver viewTreeObserver, OnGlobalLayoutListener keyboardListener) {
+ viewTreeObserver.removeOnGlobalLayoutListener(keyboardListener);
+ }
- public static Notification createMissedCallNotification(Context context, String title, String text, PendingIntent intent) {
- Notification notif = new Notification.Builder(context)
- .setContentTitle(title)
- .setContentText(text)
- .setSmallIcon(R.drawable.call_status_missed)
- .setAutoCancel(true)
- .setContentIntent(intent)
- .setDefaults(Notification.DEFAULT_SOUND
- | Notification.DEFAULT_VIBRATE)
- .setCategory(Notification.CATEGORY_MESSAGE)
- .setVisibility(Notification.VISIBILITY_PRIVATE)
- .setLights(ContextCompat.getColor(context, R.color.notification_color_led),
- context.getResources().getInteger(R.integer.notification_ms_on),
- context.getResources().getInteger(R.integer.notification_ms_off))
- .setPriority(Notification.PRIORITY_HIGH)
- .setWhen(System.currentTimeMillis())
- .setShowWhen(true)
- .build();
+ public static Notification createMissedCallNotification(Context context, String title, String text, PendingIntent intent) {
+ Notification notif = new Notification.Builder(context)
+ .setContentTitle(title)
+ .setContentText(text)
+ .setSmallIcon(R.drawable.call_status_missed)
+ .setAutoCancel(true)
+ .setContentIntent(intent)
+ .setDefaults(Notification.DEFAULT_SOUND
+ | Notification.DEFAULT_VIBRATE)
+ .setCategory(Notification.CATEGORY_MESSAGE)
+ .setVisibility(Notification.VISIBILITY_PRIVATE)
+ .setLights(ContextCompat.getColor(context, R.color.notification_color_led),
+ context.getResources().getInteger(R.integer.notification_ms_on),
+ context.getResources().getInteger(R.integer.notification_ms_off))
+ .setPriority(Notification.PRIORITY_HIGH)
+ .setWhen(System.currentTimeMillis())
+ .setShowWhen(true)
+ .build();
- return notif;
- }
+ return notif;
+ }
- public static Notification createSimpleNotification(Context context, String title, String text, PendingIntent intent) {
- Notification notif = new Notification.Builder(context)
- .setContentTitle(title)
- .setContentText(text)
- .setSmallIcon(R.drawable.linphone_logo)
- .setAutoCancel(true)
- .setContentIntent(intent)
- .setDefaults(Notification.DEFAULT_SOUND
- | Notification.DEFAULT_VIBRATE)
- .setCategory(Notification.CATEGORY_MESSAGE)
- .setVisibility(Notification.VISIBILITY_PRIVATE)
- .setLights(ContextCompat.getColor(context, R.color.notification_color_led),
- context.getResources().getInteger(R.integer.notification_ms_on),
- context.getResources().getInteger(R.integer.notification_ms_off))
- .setWhen(System.currentTimeMillis())
- .setPriority(Notification.PRIORITY_HIGH)
- .setShowWhen(true)
- .build();
+ public static Notification createSimpleNotification(Context context, String title, String text, PendingIntent intent) {
+ Notification notif = new Notification.Builder(context)
+ .setContentTitle(title)
+ .setContentText(text)
+ .setSmallIcon(R.drawable.linphone_logo)
+ .setAutoCancel(true)
+ .setContentIntent(intent)
+ .setDefaults(Notification.DEFAULT_SOUND
+ | Notification.DEFAULT_VIBRATE)
+ .setCategory(Notification.CATEGORY_MESSAGE)
+ .setVisibility(Notification.VISIBILITY_PRIVATE)
+ .setLights(ContextCompat.getColor(context, R.color.notification_color_led),
+ context.getResources().getInteger(R.integer.notification_ms_on),
+ context.getResources().getInteger(R.integer.notification_ms_off))
+ .setWhen(System.currentTimeMillis())
+ .setPriority(Notification.PRIORITY_HIGH)
+ .setShowWhen(true)
+ .build();
- return notif;
- }
+ return notif;
+ }
}
diff --git a/src/android/org/linphone/compatibility/ApiTwentySixPlus.java b/src/android/org/linphone/compatibility/ApiTwentySixPlus.java
index f40c1b892..3f39e2797 100644
--- a/src/android/org/linphone/compatibility/ApiTwentySixPlus.java
+++ b/src/android/org/linphone/compatibility/ApiTwentySixPlus.java
@@ -10,7 +10,6 @@ import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
-import android.media.AudioAttributes;
import android.view.ViewTreeObserver;
import org.linphone.R;
@@ -37,176 +36,176 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
@TargetApi(26)
public class ApiTwentySixPlus {
- public static void CreateChannel(Context context) {
- NotificationManager notificationManager =
- (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
- // Create service/call notification channel
- String id = context.getString(R.string.notification_service_channel_id);
- CharSequence name = context.getString(R.string.content_title_notification_service);
- String description = context.getString(R.string.content_title_notification_service);
- int importance = NotificationManager.IMPORTANCE_NONE;
- NotificationChannel mChannel = new NotificationChannel(id, name, importance);
- mChannel.setDescription(description);
- mChannel.enableVibration(false);
- mChannel.enableLights(false);
- notificationManager.createNotificationChannel(mChannel);
- // Create message notification channel
- id = context.getString(R.string.notification_channel_id);
- name = context.getString(R.string.content_title_notification);
- description = context.getString(R.string.content_title_notification);
- importance = NotificationManager.IMPORTANCE_HIGH;
- mChannel = new NotificationChannel(id, name, importance);
- mChannel.setDescription(description);
- mChannel.enableLights(true);
- mChannel.setLightColor(context.getColor(R.color.notification_color_led));
- mChannel.enableLights(true);
- notificationManager.createNotificationChannel(mChannel);
- }
+ public static void CreateChannel(Context context) {
+ NotificationManager notificationManager =
+ (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
+ // Create service/call notification channel
+ String id = context.getString(R.string.notification_service_channel_id);
+ CharSequence name = context.getString(R.string.content_title_notification_service);
+ String description = context.getString(R.string.content_title_notification_service);
+ int importance = NotificationManager.IMPORTANCE_NONE;
+ NotificationChannel mChannel = new NotificationChannel(id, name, importance);
+ mChannel.setDescription(description);
+ mChannel.enableVibration(false);
+ mChannel.enableLights(false);
+ notificationManager.createNotificationChannel(mChannel);
+ // Create message notification channel
+ id = context.getString(R.string.notification_channel_id);
+ name = context.getString(R.string.content_title_notification);
+ description = context.getString(R.string.content_title_notification);
+ importance = NotificationManager.IMPORTANCE_HIGH;
+ mChannel = new NotificationChannel(id, name, importance);
+ mChannel.setDescription(description);
+ mChannel.enableLights(true);
+ mChannel.setLightColor(context.getColor(R.color.notification_color_led));
+ mChannel.enableLights(true);
+ notificationManager.createNotificationChannel(mChannel);
+ }
- public static Notification createMessageNotification(Context context,
- int msgCount, String msgSender, String msg, Bitmap contactIcon,
- PendingIntent intent) {
- String title;
- if (msgCount == 1) {
- title = msgSender;
- } else {
- title = context.getString(R.string.unread_messages).replace("%i", String.valueOf(msgCount));
- }
+ public static Notification createMessageNotification(Context context,
+ int msgCount, String msgSender, String msg, Bitmap contactIcon,
+ PendingIntent intent) {
+ String title;
+ if (msgCount == 1) {
+ title = msgSender;
+ } else {
+ title = context.getString(R.string.unread_messages).replace("%i", String.valueOf(msgCount));
+ }
- Notification notif = null;
- notif = new Notification.Builder(context, context.getString(R.string.notification_channel_id))
- .setContentTitle(title)
- .setContentText(msg)
- .setSmallIcon(R.drawable.topbar_chat_notification)
- .setAutoCancel(true)
- .setContentIntent(intent)
- .setDefaults(Notification.DEFAULT_SOUND
- | Notification.DEFAULT_VIBRATE)
- .setLargeIcon(contactIcon)
- .setCategory(Notification.CATEGORY_MESSAGE)
- .setVisibility(Notification.VISIBILITY_PRIVATE)
- .setPriority(Notification.PRIORITY_HIGH)
- .setNumber(msgCount)
- .setWhen(System.currentTimeMillis())
- .setShowWhen(true)
- .setColorized(true)
- .setColor(context.getColor(R.color.notification_color_led))
- .build();
+ Notification notif = null;
+ notif = new Notification.Builder(context, context.getString(R.string.notification_channel_id))
+ .setContentTitle(title)
+ .setContentText(msg)
+ .setSmallIcon(R.drawable.topbar_chat_notification)
+ .setAutoCancel(true)
+ .setContentIntent(intent)
+ .setDefaults(Notification.DEFAULT_SOUND
+ | Notification.DEFAULT_VIBRATE)
+ .setLargeIcon(contactIcon)
+ .setCategory(Notification.CATEGORY_MESSAGE)
+ .setVisibility(Notification.VISIBILITY_PRIVATE)
+ .setPriority(Notification.PRIORITY_HIGH)
+ .setNumber(msgCount)
+ .setWhen(System.currentTimeMillis())
+ .setShowWhen(true)
+ .setColorized(true)
+ .setColor(context.getColor(R.color.notification_color_led))
+ .build();
- return notif;
- }
+ return notif;
+ }
- public static Notification createInCallNotification(Context context,
- String title, String msg, int iconID, Bitmap contactIcon,
- String contactName, PendingIntent intent) {
+ public static Notification createInCallNotification(Context context,
+ String title, String msg, int iconID, Bitmap contactIcon,
+ String contactName, PendingIntent intent) {
- Notification notif = new Notification.Builder(context, context.getString(R.string.notification_service_channel_id))
- .setContentTitle(contactName)
- .setContentText(msg)
- .setSmallIcon(iconID)
- .setAutoCancel(false)
- .setContentIntent(intent)
- .setLargeIcon(contactIcon)
- .setCategory(Notification.CATEGORY_CALL)
- .setVisibility(Notification.VISIBILITY_PUBLIC)
- .setPriority(Notification.PRIORITY_HIGH)
- .setWhen(System.currentTimeMillis())
- .setShowWhen(true)
- .setColorized(true)
- .setColor(context.getColor(R.color.notification_color_led))
- .build();
+ Notification notif = new Notification.Builder(context, context.getString(R.string.notification_service_channel_id))
+ .setContentTitle(contactName)
+ .setContentText(msg)
+ .setSmallIcon(iconID)
+ .setAutoCancel(false)
+ .setContentIntent(intent)
+ .setLargeIcon(contactIcon)
+ .setCategory(Notification.CATEGORY_CALL)
+ .setVisibility(Notification.VISIBILITY_PUBLIC)
+ .setPriority(Notification.PRIORITY_HIGH)
+ .setWhen(System.currentTimeMillis())
+ .setShowWhen(true)
+ .setColorized(true)
+ .setColor(context.getColor(R.color.notification_color_led))
+ .build();
- return notif;
- }
+ return notif;
+ }
- public static Notification createNotification(Context context, String title, String message, int icon, int level, Bitmap largeIcon, PendingIntent intent, boolean isOngoingEvent,int priority) {
- Notification notif;
+ public static Notification createNotification(Context context, String title, String message, int icon, int level, Bitmap largeIcon, PendingIntent intent, boolean isOngoingEvent, int priority) {
+ Notification notif;
- if (largeIcon != null) {
- notif = new Notification.Builder(context, context.getString(R.string.notification_service_channel_id))
- .setContentTitle(title)
- .setContentText(message)
- .setSmallIcon(icon, level)
- .setLargeIcon(largeIcon)
- .setContentIntent(intent)
- .setCategory(Notification.CATEGORY_SERVICE)
- .setVisibility(Notification.VISIBILITY_SECRET)
- .setPriority(priority)
- .setWhen(System.currentTimeMillis())
- .setShowWhen(true)
- .setColorized(true)
- .setColor(context.getColor(R.color.notification_color_led))
- .build();
- } else {
- notif = new Notification.Builder(context, context.getString(R.string.notification_service_channel_id))
- .setContentTitle(title)
- .setContentText(message)
- .setSmallIcon(icon, level)
- .setContentIntent(intent)
- .setCategory(Notification.CATEGORY_SERVICE)
- .setVisibility(Notification.VISIBILITY_SECRET)
- .setPriority(priority)
- .setWhen(System.currentTimeMillis())
- .setShowWhen(true)
- .setColorized(true)
- .setColor(context.getColor(R.color.notification_color_led))
- .build();
- }
+ if (largeIcon != null) {
+ notif = new Notification.Builder(context, context.getString(R.string.notification_service_channel_id))
+ .setContentTitle(title)
+ .setContentText(message)
+ .setSmallIcon(icon, level)
+ .setLargeIcon(largeIcon)
+ .setContentIntent(intent)
+ .setCategory(Notification.CATEGORY_SERVICE)
+ .setVisibility(Notification.VISIBILITY_SECRET)
+ .setPriority(priority)
+ .setWhen(System.currentTimeMillis())
+ .setShowWhen(true)
+ .setColorized(true)
+ .setColor(context.getColor(R.color.notification_color_led))
+ .build();
+ } else {
+ notif = new Notification.Builder(context, context.getString(R.string.notification_service_channel_id))
+ .setContentTitle(title)
+ .setContentText(message)
+ .setSmallIcon(icon, level)
+ .setContentIntent(intent)
+ .setCategory(Notification.CATEGORY_SERVICE)
+ .setVisibility(Notification.VISIBILITY_SECRET)
+ .setPriority(priority)
+ .setWhen(System.currentTimeMillis())
+ .setShowWhen(true)
+ .setColorized(true)
+ .setColor(context.getColor(R.color.notification_color_led))
+ .build();
+ }
- return notif;
- }
+ return notif;
+ }
- public static void removeGlobalLayoutListener(ViewTreeObserver viewTreeObserver, ViewTreeObserver.OnGlobalLayoutListener keyboardListener) {
- viewTreeObserver.removeOnGlobalLayoutListener(keyboardListener);
- }
+ public static void removeGlobalLayoutListener(ViewTreeObserver viewTreeObserver, ViewTreeObserver.OnGlobalLayoutListener keyboardListener) {
+ viewTreeObserver.removeOnGlobalLayoutListener(keyboardListener);
+ }
- public static Notification createMissedCallNotification(Context context, String title, String text, PendingIntent intent) {
- Notification notif = new Notification.Builder(context, context.getString(R.string.notification_channel_id))
- .setContentTitle(title)
- .setContentText(text)
- .setSmallIcon(R.drawable.call_status_missed)
- .setAutoCancel(true)
- .setContentIntent(intent)
- .setDefaults(Notification.DEFAULT_SOUND
- | Notification.DEFAULT_VIBRATE)
- .setCategory(Notification.CATEGORY_MESSAGE)
- .setVisibility(Notification.VISIBILITY_PRIVATE)
- .setPriority(Notification.PRIORITY_HIGH)
- .setWhen(System.currentTimeMillis())
- .setShowWhen(true)
- .setColorized(true)
- .setColor(context.getColor(R.color.notification_color_led))
- .build();
+ public static Notification createMissedCallNotification(Context context, String title, String text, PendingIntent intent) {
+ Notification notif = new Notification.Builder(context, context.getString(R.string.notification_channel_id))
+ .setContentTitle(title)
+ .setContentText(text)
+ .setSmallIcon(R.drawable.call_status_missed)
+ .setAutoCancel(true)
+ .setContentIntent(intent)
+ .setDefaults(Notification.DEFAULT_SOUND
+ | Notification.DEFAULT_VIBRATE)
+ .setCategory(Notification.CATEGORY_MESSAGE)
+ .setVisibility(Notification.VISIBILITY_PRIVATE)
+ .setPriority(Notification.PRIORITY_HIGH)
+ .setWhen(System.currentTimeMillis())
+ .setShowWhen(true)
+ .setColorized(true)
+ .setColor(context.getColor(R.color.notification_color_led))
+ .build();
- return notif;
- }
+ return notif;
+ }
- public static Notification createSimpleNotification(Context context, String title, String text, PendingIntent intent) {
- Notification notif = new Notification.Builder(context, context.getString(R.string.notification_channel_id))
- .setContentTitle(title)
- .setContentText(text)
- .setSmallIcon(R.drawable.linphone_logo)
- .setAutoCancel(true)
- .setContentIntent(intent)
- .setDefaults(Notification.DEFAULT_SOUND
- | Notification.DEFAULT_VIBRATE)
- .setCategory(Notification.CATEGORY_MESSAGE)
- .setVisibility(Notification.VISIBILITY_PRIVATE)
- .setPriority(Notification.PRIORITY_HIGH)
- .setWhen(System.currentTimeMillis())
- .setShowWhen(true)
- .setColorized(true)
- .setColor(context.getColor(R.color.notification_color_led))
- .build();
+ public static Notification createSimpleNotification(Context context, String title, String text, PendingIntent intent) {
+ Notification notif = new Notification.Builder(context, context.getString(R.string.notification_channel_id))
+ .setContentTitle(title)
+ .setContentText(text)
+ .setSmallIcon(R.drawable.linphone_logo)
+ .setAutoCancel(true)
+ .setContentIntent(intent)
+ .setDefaults(Notification.DEFAULT_SOUND
+ | Notification.DEFAULT_VIBRATE)
+ .setCategory(Notification.CATEGORY_MESSAGE)
+ .setVisibility(Notification.VISIBILITY_PRIVATE)
+ .setPriority(Notification.PRIORITY_HIGH)
+ .setWhen(System.currentTimeMillis())
+ .setShowWhen(true)
+ .setColorized(true)
+ .setColor(context.getColor(R.color.notification_color_led))
+ .build();
- return notif;
- }
+ return notif;
+ }
- public static void startService(Context context, Intent intent) {
- context.startForegroundService(intent);
- }
+ public static void startService(Context context, Intent intent) {
+ context.startForegroundService(intent);
+ }
- public static void setFragmentTransactionReorderingAllowed(FragmentTransaction transaction, boolean allowed) {
- transaction.setReorderingAllowed(allowed);
- }
+ public static void setFragmentTransactionReorderingAllowed(FragmentTransaction transaction, boolean allowed) {
+ transaction.setReorderingAllowed(allowed);
+ }
}
diff --git a/src/android/org/linphone/compatibility/ApiTwentyThreePlus.java b/src/android/org/linphone/compatibility/ApiTwentyThreePlus.java
index fb3db0484..5e7124df4 100644
--- a/src/android/org/linphone/compatibility/ApiTwentyThreePlus.java
+++ b/src/android/org/linphone/compatibility/ApiTwentyThreePlus.java
@@ -1,7 +1,7 @@
package org.linphone.compatibility;
-import android.widget.TextView;
import android.annotation.TargetApi;
+import android.widget.TextView;
/*
ApiTwentyThreePlus.java
@@ -24,7 +24,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
@TargetApi(23)
public class ApiTwentyThreePlus {
- public static void setTextAppearance(TextView textview, int style) {
- textview.setTextAppearance(style);
- }
+ public static void setTextAppearance(TextView textview, int style) {
+ textview.setTextAppearance(style);
+ }
}
diff --git a/src/android/org/linphone/compatibility/Compatibility.java b/src/android/org/linphone/compatibility/Compatibility.java
index 86927aa1c..ad6e0930d 100644
--- a/src/android/org/linphone/compatibility/Compatibility.java
+++ b/src/android/org/linphone/compatibility/Compatibility.java
@@ -17,7 +17,6 @@ You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
-import org.linphone.mediastream.Version;
import android.app.AlarmManager;
import android.app.FragmentTransaction;
@@ -35,139 +34,143 @@ import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.TextView;
+import org.linphone.mediastream.Version;
+
public class Compatibility {
- public static void CreateChannel(Context context) {
- if (Version.sdkAboveOrEqual(Version.API26_O_80)) {
- ApiTwentySixPlus.CreateChannel(context);
- }
- }
- public static Notification createSimpleNotification(Context context, String title, String text, PendingIntent intent) {
- if (Version.sdkAboveOrEqual(Version.API26_O_80)) {
- return ApiTwentySixPlus.createSimpleNotification(context, title, text, intent);
- } else if (Version.sdkAboveOrEqual(Version.API21_LOLLIPOP_50)) {
- return ApiTwentyOnePlus.createSimpleNotification(context, title, text, intent);
- } else if (Version.sdkAboveOrEqual(Version.API16_JELLY_BEAN_41)) {
- return ApiSixteenPlus.createSimpleNotification(context, title, text, intent);
- } else {
- return ApiElevenPlus.createSimpleNotification(context, title, text, intent);
- }
- }
- public static Notification createMissedCallNotification(Context context, String title, String text, PendingIntent intent) {
- if (Version.sdkAboveOrEqual(Version.API26_O_80)) {
- return ApiTwentySixPlus.createMissedCallNotification(context, title, text, intent);
- } else if (Version.sdkAboveOrEqual(Version.API21_LOLLIPOP_50)) {
- return ApiTwentyOnePlus.createMissedCallNotification(context, title, text, intent);
- } else if (Version.sdkAboveOrEqual(Version.API16_JELLY_BEAN_41)) {
- return ApiSixteenPlus.createMissedCallNotification(context, title, text, intent);
- } else {
- return ApiElevenPlus.createMissedCallNotification(context, title, text, intent);
- }
- }
+ public static void CreateChannel(Context context) {
+ if (Version.sdkAboveOrEqual(Version.API26_O_80)) {
+ ApiTwentySixPlus.CreateChannel(context);
+ }
+ }
- public static Notification createMessageNotification(Context context, int msgCount, String msgSender, String msg, Bitmap contactIcon, PendingIntent intent) {
- if (Version.sdkAboveOrEqual(Version.API26_O_80)) {
- return ApiTwentySixPlus.createMessageNotification(context, msgCount, msgSender, msg, contactIcon, intent);
- } else if (Version.sdkAboveOrEqual(Version.API21_LOLLIPOP_50)) {
- return ApiTwentyOnePlus.createMessageNotification(context, msgCount, msgSender, msg, contactIcon, intent);
- } else if (Version.sdkAboveOrEqual(Version.API16_JELLY_BEAN_41)) {
- return ApiSixteenPlus.createMessageNotification(context, msgCount, msgSender, msg, contactIcon, intent);
- } else {
- return ApiElevenPlus.createMessageNotification(context, msgCount, msgSender, msg, contactIcon, intent);
- }
- }
+ public static Notification createSimpleNotification(Context context, String title, String text, PendingIntent intent) {
+ if (Version.sdkAboveOrEqual(Version.API26_O_80)) {
+ return ApiTwentySixPlus.createSimpleNotification(context, title, text, intent);
+ } else if (Version.sdkAboveOrEqual(Version.API21_LOLLIPOP_50)) {
+ return ApiTwentyOnePlus.createSimpleNotification(context, title, text, intent);
+ } else if (Version.sdkAboveOrEqual(Version.API16_JELLY_BEAN_41)) {
+ return ApiSixteenPlus.createSimpleNotification(context, title, text, intent);
+ } else {
+ return ApiElevenPlus.createSimpleNotification(context, title, text, intent);
+ }
+ }
- public static Notification createInCallNotification(Context context, String title, String msg, int iconID, Bitmap contactIcon, String contactName, PendingIntent intent) {
- if (Version.sdkAboveOrEqual(Version.API26_O_80)) {
- return ApiTwentySixPlus.createInCallNotification(context, title, msg, iconID, contactIcon, contactName, intent);
- } else if (Version.sdkAboveOrEqual(Version.API21_LOLLIPOP_50)) {
- return ApiTwentyOnePlus.createInCallNotification(context, title, msg, iconID, contactIcon, contactName, intent);
- } else if (Version.sdkAboveOrEqual(Version.API16_JELLY_BEAN_41)) {
- return ApiSixteenPlus.createInCallNotification(context, title, msg, iconID, contactIcon, contactName, intent);
- } else {
- return ApiElevenPlus.createInCallNotification(context, title, msg, iconID, contactIcon, contactName, intent);
- }
- }
+ public static Notification createMissedCallNotification(Context context, String title, String text, PendingIntent intent) {
+ if (Version.sdkAboveOrEqual(Version.API26_O_80)) {
+ return ApiTwentySixPlus.createMissedCallNotification(context, title, text, intent);
+ } else if (Version.sdkAboveOrEqual(Version.API21_LOLLIPOP_50)) {
+ return ApiTwentyOnePlus.createMissedCallNotification(context, title, text, intent);
+ } else if (Version.sdkAboveOrEqual(Version.API16_JELLY_BEAN_41)) {
+ return ApiSixteenPlus.createMissedCallNotification(context, title, text, intent);
+ } else {
+ return ApiElevenPlus.createMissedCallNotification(context, title, text, intent);
+ }
+ }
- public static Notification createNotification(Context context, String title, String message, int icon, int iconLevel, Bitmap largeIcon, PendingIntent intent, boolean isOngoingEvent,int priority) {
- if (Version.sdkAboveOrEqual(Version.API26_O_80)) {
- return ApiTwentySixPlus.createNotification(context, title, message, icon, iconLevel, largeIcon, intent, isOngoingEvent,priority);
- } else if (Version.sdkAboveOrEqual(Version.API21_LOLLIPOP_50)) {
- return ApiTwentyOnePlus.createNotification(context, title, message, icon, iconLevel, largeIcon, intent, isOngoingEvent,priority);
- } else if (Version.sdkAboveOrEqual(Version.API16_JELLY_BEAN_41)) {
- return ApiSixteenPlus.createNotification(context, title, message, icon, iconLevel, largeIcon, intent, isOngoingEvent,priority);
- } else {
- return ApiElevenPlus.createNotification(context, title, message, icon, iconLevel, largeIcon, intent, isOngoingEvent);
- }
- }
+ public static Notification createMessageNotification(Context context, int msgCount, String msgSender, String msg, Bitmap contactIcon, PendingIntent intent) {
+ if (Version.sdkAboveOrEqual(Version.API26_O_80)) {
+ return ApiTwentySixPlus.createMessageNotification(context, msgCount, msgSender, msg, contactIcon, intent);
+ } else if (Version.sdkAboveOrEqual(Version.API21_LOLLIPOP_50)) {
+ return ApiTwentyOnePlus.createMessageNotification(context, msgCount, msgSender, msg, contactIcon, intent);
+ } else if (Version.sdkAboveOrEqual(Version.API16_JELLY_BEAN_41)) {
+ return ApiSixteenPlus.createMessageNotification(context, msgCount, msgSender, msg, contactIcon, intent);
+ } else {
+ return ApiElevenPlus.createMessageNotification(context, msgCount, msgSender, msg, contactIcon, intent);
+ }
+ }
- public static CompatibilityScaleGestureDetector getScaleGestureDetector(Context context, CompatibilityScaleGestureListener listener) {
- if (Version.sdkAboveOrEqual(Version.API08_FROYO_22)) {
- CompatibilityScaleGestureDetector csgd = new CompatibilityScaleGestureDetector(context);
- csgd.setOnScaleListener(listener);
- return csgd;
- }
- return null;
- }
+ public static Notification createInCallNotification(Context context, String title, String msg, int iconID, Bitmap contactIcon, String contactName, PendingIntent intent) {
+ if (Version.sdkAboveOrEqual(Version.API26_O_80)) {
+ return ApiTwentySixPlus.createInCallNotification(context, title, msg, iconID, contactIcon, contactName, intent);
+ } else if (Version.sdkAboveOrEqual(Version.API21_LOLLIPOP_50)) {
+ return ApiTwentyOnePlus.createInCallNotification(context, title, msg, iconID, contactIcon, contactName, intent);
+ } else if (Version.sdkAboveOrEqual(Version.API16_JELLY_BEAN_41)) {
+ return ApiSixteenPlus.createInCallNotification(context, title, msg, iconID, contactIcon, contactName, intent);
+ } else {
+ return ApiElevenPlus.createInCallNotification(context, title, msg, iconID, contactIcon, contactName, intent);
+ }
+ }
- @SuppressWarnings("deprecation")
- public static void removeGlobalLayoutListener(ViewTreeObserver viewTreeObserver, OnGlobalLayoutListener keyboardListener) {
- if (Version.sdkAboveOrEqual(Version.API16_JELLY_BEAN_41)) {
- ApiSixteenPlus.removeGlobalLayoutListener(viewTreeObserver, keyboardListener);
- } else {
- viewTreeObserver.removeGlobalOnLayoutListener(keyboardListener);
- }
- }
+ public static Notification createNotification(Context context, String title, String message, int icon, int iconLevel, Bitmap largeIcon, PendingIntent intent, boolean isOngoingEvent, int priority) {
+ if (Version.sdkAboveOrEqual(Version.API26_O_80)) {
+ return ApiTwentySixPlus.createNotification(context, title, message, icon, iconLevel, largeIcon, intent, isOngoingEvent, priority);
+ } else if (Version.sdkAboveOrEqual(Version.API21_LOLLIPOP_50)) {
+ return ApiTwentyOnePlus.createNotification(context, title, message, icon, iconLevel, largeIcon, intent, isOngoingEvent, priority);
+ } else if (Version.sdkAboveOrEqual(Version.API16_JELLY_BEAN_41)) {
+ return ApiSixteenPlus.createNotification(context, title, message, icon, iconLevel, largeIcon, intent, isOngoingEvent, priority);
+ } else {
+ return ApiElevenPlus.createNotification(context, title, message, icon, iconLevel, largeIcon, intent, isOngoingEvent);
+ }
+ }
- public static boolean canDrawOverlays(Context context) {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
- return Settings.canDrawOverlays(context);
- }
- return true;
- }
+ public static CompatibilityScaleGestureDetector getScaleGestureDetector(Context context, CompatibilityScaleGestureListener listener) {
+ if (Version.sdkAboveOrEqual(Version.API08_FROYO_22)) {
+ CompatibilityScaleGestureDetector csgd = new CompatibilityScaleGestureDetector(context);
+ csgd.setOnScaleListener(listener);
+ return csgd;
+ }
+ return null;
+ }
- @SuppressWarnings("deprecation")
- public static boolean isScreenOn(PowerManager pm) {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
- return pm.isInteractive();
- }
- return pm.isScreenOn();
- }
+ @SuppressWarnings("deprecation")
+ public static void removeGlobalLayoutListener(ViewTreeObserver viewTreeObserver, OnGlobalLayoutListener keyboardListener) {
+ if (Version.sdkAboveOrEqual(Version.API16_JELLY_BEAN_41)) {
+ ApiSixteenPlus.removeGlobalLayoutListener(viewTreeObserver, keyboardListener);
+ } else {
+ viewTreeObserver.removeGlobalOnLayoutListener(keyboardListener);
+ }
+ }
- @SuppressWarnings("deprecation")
- public static Spanned fromHtml(String text) {
+ public static boolean canDrawOverlays(Context context) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+ return Settings.canDrawOverlays(context);
+ }
+ return true;
+ }
+
+ @SuppressWarnings("deprecation")
+ public static boolean isScreenOn(PowerManager pm) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
+ return pm.isInteractive();
+ }
+ return pm.isScreenOn();
+ }
+
+ @SuppressWarnings("deprecation")
+ public static Spanned fromHtml(String text) {
/*if (Version.sdkAboveOrEqual(Version.API24_NOUGAT_70)) {
return Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY);
}*/
- return Html.fromHtml(text);
- }
+ return Html.fromHtml(text);
+ }
- public static void setTextAppearance(TextView textview, Context context, int style) {
- if (Version.sdkAboveOrEqual(Version.API23_MARSHMALLOW_60)) {
- ApiTwentyThreePlus.setTextAppearance(textview, style);
- } else {
- ApiElevenPlus.setTextAppearance(textview, context, style);
- }
- }
+ public static void setTextAppearance(TextView textview, Context context, int style) {
+ if (Version.sdkAboveOrEqual(Version.API23_MARSHMALLOW_60)) {
+ ApiTwentyThreePlus.setTextAppearance(textview, style);
+ } else {
+ ApiElevenPlus.setTextAppearance(textview, context, style);
+ }
+ }
- public static void scheduleAlarm(AlarmManager alarmManager, int type, long triggerAtMillis, PendingIntent operation) {
- if (Version.sdkAboveOrEqual(Version.API19_KITKAT_44)) {
- ApiNineteenPlus.scheduleAlarm(alarmManager, type, triggerAtMillis, operation);
- } else {
- ApiElevenPlus.scheduleAlarm(alarmManager, type, triggerAtMillis, operation);
- }
- }
+ public static void scheduleAlarm(AlarmManager alarmManager, int type, long triggerAtMillis, PendingIntent operation) {
+ if (Version.sdkAboveOrEqual(Version.API19_KITKAT_44)) {
+ ApiNineteenPlus.scheduleAlarm(alarmManager, type, triggerAtMillis, operation);
+ } else {
+ ApiElevenPlus.scheduleAlarm(alarmManager, type, triggerAtMillis, operation);
+ }
+ }
- public static void startService(Context context, Intent intent) {
- if (Version.sdkAboveOrEqual(Version.API26_O_80)) {
- ApiTwentySixPlus.startService(context, intent);
- } else {
- ApiSixteenPlus.startService(context, intent);
- }
- }
+ public static void startService(Context context, Intent intent) {
+ if (Version.sdkAboveOrEqual(Version.API26_O_80)) {
+ ApiTwentySixPlus.startService(context, intent);
+ } else {
+ ApiSixteenPlus.startService(context, intent);
+ }
+ }
- public static void setFragmentTransactionReorderingAllowed(FragmentTransaction transaction, boolean allowed) {
- if (Version.sdkAboveOrEqual(Version.API26_O_80)) {
- ApiTwentySixPlus.setFragmentTransactionReorderingAllowed(transaction, allowed);
- }
- }
+ public static void setFragmentTransactionReorderingAllowed(FragmentTransaction transaction, boolean allowed) {
+ if (Version.sdkAboveOrEqual(Version.API26_O_80)) {
+ ApiTwentySixPlus.setFragmentTransactionReorderingAllowed(transaction, allowed);
+ }
+ }
}
diff --git a/src/android/org/linphone/compatibility/CompatibilityScaleGestureDetector.java b/src/android/org/linphone/compatibility/CompatibilityScaleGestureDetector.java
index a8e315896..d24e4d110 100644
--- a/src/android/org/linphone/compatibility/CompatibilityScaleGestureDetector.java
+++ b/src/android/org/linphone/compatibility/CompatibilityScaleGestureDetector.java
@@ -26,36 +26,36 @@ import android.view.ScaleGestureDetector;
@TargetApi(8)
public class CompatibilityScaleGestureDetector extends ScaleGestureDetector.SimpleOnScaleGestureListener {
- private ScaleGestureDetector detector;
- private CompatibilityScaleGestureListener listener;
+ private ScaleGestureDetector detector;
+ private CompatibilityScaleGestureListener listener;
- public CompatibilityScaleGestureDetector(Context context) {
- detector = new ScaleGestureDetector(context, this);
- }
-
- public void setOnScaleListener(CompatibilityScaleGestureListener newListener) {
- listener = newListener;
- }
-
- public boolean onTouchEvent(MotionEvent event) {
- return detector.onTouchEvent(event);
- }
-
- @Override
- public boolean onScale(ScaleGestureDetector detector) {
- if (listener == null) {
- return false;
- }
-
- return listener.onScale(this);
+ public CompatibilityScaleGestureDetector(Context context) {
+ detector = new ScaleGestureDetector(context, this);
}
- public float getScaleFactor() {
- return detector.getScaleFactor();
- }
+ public void setOnScaleListener(CompatibilityScaleGestureListener newListener) {
+ listener = newListener;
+ }
- public void destroy() {
- listener = null;
- detector = null;
- }
+ public boolean onTouchEvent(MotionEvent event) {
+ return detector.onTouchEvent(event);
+ }
+
+ @Override
+ public boolean onScale(ScaleGestureDetector detector) {
+ if (listener == null) {
+ return false;
+ }
+
+ return listener.onScale(this);
+ }
+
+ public float getScaleFactor() {
+ return detector.getScaleFactor();
+ }
+
+ public void destroy() {
+ listener = null;
+ detector = null;
+ }
}
\ No newline at end of file
diff --git a/src/android/org/linphone/compatibility/CompatibilityScaleGestureListener.java b/src/android/org/linphone/compatibility/CompatibilityScaleGestureListener.java
index 48ec9b17b..bd4393385 100644
--- a/src/android/org/linphone/compatibility/CompatibilityScaleGestureListener.java
+++ b/src/android/org/linphone/compatibility/CompatibilityScaleGestureListener.java
@@ -20,5 +20,5 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
public interface CompatibilityScaleGestureListener {
- public boolean onScale(CompatibilityScaleGestureDetector detector);
+ public boolean onScale(CompatibilityScaleGestureDetector detector);
}
\ No newline at end of file
diff --git a/src/android/org/linphone/contacts/ContactAddress.java b/src/android/org/linphone/contacts/ContactAddress.java
index f6c54154b..78a6d2e5e 100644
--- a/src/android/org/linphone/contacts/ContactAddress.java
+++ b/src/android/org/linphone/contacts/ContactAddress.java
@@ -28,117 +28,118 @@ import org.linphone.core.SearchResult;
import java.io.Serializable;
public class ContactAddress implements Serializable {
- private LinphoneContact contact;
- private SearchResult result;
- private String address;
- private String phoneNumber;
- private boolean isLinphoneContact;
- private boolean isSelect = false;
- private boolean isAdmin = false;
- private transient View view;
+ private LinphoneContact contact;
+ private SearchResult result;
+ private String address;
+ private String phoneNumber;
+ private boolean isLinphoneContact;
+ private boolean isSelect = false;
+ private boolean isAdmin = false;
+ private transient View view;
- public boolean isAdmin() {
- return isAdmin;
- }
+ public boolean isAdmin() {
+ return isAdmin;
+ }
- public void setAdmin(boolean admin) {
- isAdmin = admin;
- }
+ public void setAdmin(boolean admin) {
+ isAdmin = admin;
+ }
- public boolean isSelect() {
- return isSelect;
- }
+ public boolean isSelect() {
+ return isSelect;
+ }
- public void setView(View v) {
- view = v;
- }
+ public void setView(View v) {
+ view = v;
+ }
- public View getView() {
- return view;
- }
+ public View getView() {
+ return view;
+ }
- public LinphoneContact getContact() {
- return contact;
- }
+ public LinphoneContact getContact() {
+ return contact;
+ }
- public SearchResult getResult() {
- return result;
- }
+ public SearchResult getResult() {
+ return result;
+ }
- public void setResult(SearchResult result) {
- this.result = result;
- }
+ public void setResult(SearchResult result) {
+ this.result = result;
+ }
- public String getAddressAsDisplayableString() {
- Address addr = getAddress();
- if (addr != null && addr.getUsername() != null) return addr.asStringUriOnly();
- return address;
- }
+ public String getAddressAsDisplayableString() {
+ Address addr = getAddress();
+ if (addr != null && addr.getUsername() != null) return addr.asStringUriOnly();
+ return address;
+ }
- public Address getAddress() {
- String presence = contact.getPresenceModelForUriOrTel((phoneNumber != null && !phoneNumber.isEmpty()) ? phoneNumber: address);
- Address addr = Factory.instance().createAddress(presence != null ? presence : address);
- // Remove the user=phone URI param if existing, it will break everything otherwise
- if (addr.hasUriParam("user")) {
- addr.removeUriParam("user");
- }
- return addr;
- }
+ public Address getAddress() {
+ String presence = contact.getPresenceModelForUriOrTel((phoneNumber != null && !phoneNumber.isEmpty()) ? phoneNumber : address);
+ Address addr = Factory.instance().createAddress(presence != null ? presence : address);
+ // Remove the user=phone URI param if existing, it will break everything otherwise
+ if (addr.hasUriParam("user")) {
+ addr.removeUriParam("user");
+ }
+ return addr;
+ }
- public String getDisplayName() {
- if (address != null) {
- Address addr = Factory.instance().createAddress(address);
- if (addr != null) {
- return addr.getDisplayName();
- }
- }
- return null;
- }
+ public String getDisplayName() {
+ if (address != null) {
+ Address addr = Factory.instance().createAddress(address);
+ if (addr != null) {
+ return addr.getDisplayName();
+ }
+ }
+ return null;
+ }
- public String getUsername() {
- if (address != null) {
- Address addr = Factory.instance().createAddress(address);
- if (addr != null) {
- return addr.getUsername();
- }
- }
- return null;
- }
+ public String getUsername() {
+ if (address != null) {
+ Address addr = Factory.instance().createAddress(address);
+ if (addr != null) {
+ return addr.getUsername();
+ }
+ }
+ return null;
+ }
- public String getPhoneNumber() {
- return phoneNumber;
- }
+ public String getPhoneNumber() {
+ return phoneNumber;
+ }
- public void setSelect(boolean select) {
- isSelect = select;
- }
+ public void setSelect(boolean select) {
+ isSelect = select;
+ }
- public boolean isLinphoneContact() {
- return isLinphoneContact;
- }
+ public boolean isLinphoneContact() {
+ return isLinphoneContact;
+ }
- private void init(LinphoneContact c, String a, String pn, boolean isLC) {
- contact = c;
- address = a;
- phoneNumber = pn;
- isLinphoneContact = isLC;
- }
+ private void init(LinphoneContact c, String a, String pn, boolean isLC) {
+ contact = c;
+ address = a;
+ phoneNumber = pn;
+ isLinphoneContact = isLC;
+ }
- public ContactAddress(LinphoneContact c, String a, String pn, boolean isLC) {
- init(c, a, pn, isLC);
- }
+ public ContactAddress(LinphoneContact c, String a, String pn, boolean isLC) {
+ init(c, a, pn, isLC);
+ }
- public ContactAddress(LinphoneContact c, String a, String pn, boolean isLC, boolean isAdmin) {
- init(c, a, pn, isLC);
- this.isAdmin = isAdmin;
- }
+ public ContactAddress(LinphoneContact c, String a, String pn, boolean isLC, boolean isAdmin) {
+ init(c, a, pn, isLC);
+ this.isAdmin = isAdmin;
+ }
- @Override
- public boolean equals(Object other){
- if (other == null) return false;
- if (other == this) return true;
- if (!(other instanceof ContactAddress))return false;
- if (((ContactAddress)other).getAddressAsDisplayableString() == this.getAddressAsDisplayableString()) return true;
- return false;
- }
+ @Override
+ public boolean equals(Object other) {
+ if (other == null) return false;
+ if (other == this) return true;
+ if (!(other instanceof ContactAddress)) return false;
+ if (((ContactAddress) other).getAddressAsDisplayableString() == this.getAddressAsDisplayableString())
+ return true;
+ return false;
+ }
}
diff --git a/src/android/org/linphone/contacts/ContactDetailsFragment.java b/src/android/org/linphone/contacts/ContactDetailsFragment.java
index 2325435cf..3567bca15 100644
--- a/src/android/org/linphone/contacts/ContactDetailsFragment.java
+++ b/src/android/org/linphone/contacts/ContactDetailsFragment.java
@@ -19,20 +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 org.linphone.LinphoneManager;
-import org.linphone.LinphonePreferences;
-import org.linphone.LinphoneUtils;
-import org.linphone.R;
-import org.linphone.activities.LinphoneActivity;
-import org.linphone.core.Address;
-import org.linphone.core.ChatRoom;
-import org.linphone.core.ChatRoomListenerStub;
-import org.linphone.core.Core;
-import org.linphone.core.Factory;
-import org.linphone.core.ProxyConfig;
-import org.linphone.fragments.FragmentsAvailable;
-import org.linphone.mediastream.Log;
-
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.Fragment;
@@ -47,241 +33,255 @@ import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TextView;
+import org.linphone.LinphoneManager;
+import org.linphone.LinphonePreferences;
+import org.linphone.LinphoneUtils;
+import org.linphone.R;
+import org.linphone.activities.LinphoneActivity;
+import org.linphone.core.Address;
+import org.linphone.core.ChatRoom;
+import org.linphone.core.ChatRoomListenerStub;
+import org.linphone.core.Core;
+import org.linphone.core.Factory;
+import org.linphone.core.ProxyConfig;
+import org.linphone.fragments.FragmentsAvailable;
+import org.linphone.mediastream.Log;
+
public class ContactDetailsFragment extends Fragment implements OnClickListener {
- private LinphoneContact contact;
- private ImageView editContact, deleteContact, back;
- private TextView organization;
- private RelativeLayout mWaitLayout;
- private LayoutInflater inflater;
- private View view;
- private boolean displayChatAddressOnly = false;
- private ChatRoom mChatRoom;
- private ChatRoomListenerStub mChatRoomCreationListener;
+ private LinphoneContact contact;
+ private ImageView editContact, deleteContact, back;
+ private TextView organization;
+ private RelativeLayout mWaitLayout;
+ private LayoutInflater inflater;
+ private View view;
+ private boolean displayChatAddressOnly = false;
+ private ChatRoom mChatRoom;
+ private ChatRoomListenerStub mChatRoomCreationListener;
- private OnClickListener dialListener = new OnClickListener() {
- @Override
- public void onClick(View v) {
- if (LinphoneActivity.isInstanciated()) {
- String tag = (String)v.getTag();
- LinphoneActivity.instance().setAddresGoToDialerAndCall(tag, contact.getFullName(), contact.getPhotoUri());
- }
- }
- };
+ private OnClickListener dialListener = new OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (LinphoneActivity.isInstanciated()) {
+ String tag = (String) v.getTag();
+ LinphoneActivity.instance().setAddresGoToDialerAndCall(tag, contact.getFullName(), contact.getPhotoUri());
+ }
+ }
+ };
- private OnClickListener chatListener = new OnClickListener() {
- @Override
- public void onClick(View v) {
- if (LinphoneActivity.isInstanciated()) {
- String tag = (String)v.getTag();
- Core lc = LinphoneManager.getLc();
- Address participant = Factory.instance().createAddress(tag);
- ProxyConfig defaultProxyConfig = lc.getDefaultProxyConfig();
- if (defaultProxyConfig != null) {
- ChatRoom room = lc.findOneToOneChatRoom(defaultProxyConfig.getContact(), participant);
- if (room != null) {
- LinphoneActivity.instance().goToChat(room.getPeerAddress().asStringUriOnly(), null);
- } else {
- if (defaultProxyConfig.getConferenceFactoryUri() != null && !LinphonePreferences.instance().useBasicChatRoomFor1To1()) {
- mWaitLayout.setVisibility(View.VISIBLE);
- mChatRoom = lc.createClientGroupChatRoom(getString(R.string.dummy_group_chat_subject), true);
- mChatRoom.addListener(mChatRoomCreationListener);
- mChatRoom.addParticipant(participant);
- } else {
- room = lc.getChatRoom(participant);
- LinphoneActivity.instance().goToChat(room.getPeerAddress().asStringUriOnly(), null);
- }
- }
- }
- }
- }
- };
+ private OnClickListener chatListener = new OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (LinphoneActivity.isInstanciated()) {
+ String tag = (String) v.getTag();
+ Core lc = LinphoneManager.getLc();
+ Address participant = Factory.instance().createAddress(tag);
+ ProxyConfig defaultProxyConfig = lc.getDefaultProxyConfig();
+ if (defaultProxyConfig != null) {
+ ChatRoom room = lc.findOneToOneChatRoom(defaultProxyConfig.getContact(), participant);
+ if (room != null) {
+ LinphoneActivity.instance().goToChat(room.getPeerAddress().asStringUriOnly(), null);
+ } else {
+ if (defaultProxyConfig.getConferenceFactoryUri() != null && !LinphonePreferences.instance().useBasicChatRoomFor1To1()) {
+ mWaitLayout.setVisibility(View.VISIBLE);
+ mChatRoom = lc.createClientGroupChatRoom(getString(R.string.dummy_group_chat_subject), true);
+ mChatRoom.addListener(mChatRoomCreationListener);
+ mChatRoom.addParticipant(participant);
+ } else {
+ room = lc.getChatRoom(participant);
+ LinphoneActivity.instance().goToChat(room.getPeerAddress().asStringUriOnly(), null);
+ }
+ }
+ }
+ }
+ }
+ };
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
- contact = (LinphoneContact) getArguments().getSerializable("Contact");
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ contact = (LinphoneContact) getArguments().getSerializable("Contact");
- this.inflater = inflater;
- view = inflater.inflate(R.layout.contact, container, false);
+ this.inflater = inflater;
+ view = inflater.inflate(R.layout.contact, container, false);
- if (getArguments() != null) {
- displayChatAddressOnly = getArguments().getBoolean("ChatAddressOnly");
- }
-
- mWaitLayout = view.findViewById(R.id.waitScreen);
- mWaitLayout.setVisibility(View.GONE);
-
- editContact = view.findViewById(R.id.editContact);
- editContact.setOnClickListener(this);
-
- deleteContact = view.findViewById(R.id.deleteContact);
- deleteContact.setOnClickListener(this);
-
- organization = view.findViewById(R.id.contactOrganization);
- boolean isOrgVisible = getResources().getBoolean(R.bool.display_contact_organization);
- String org = contact.getOrganization();
- if (org != null && !org.isEmpty() && isOrgVisible) {
- organization.setText(org);
- } else {
- organization.setVisibility(View.GONE);
- }
-
- back = view.findViewById(R.id.back);
- if (getResources().getBoolean(R.bool.isTablet)) {
- back.setVisibility(View.INVISIBLE);
- } else {
- back.setOnClickListener(this);
- }
-
- mChatRoomCreationListener = new ChatRoomListenerStub() {
- @Override
- public void onStateChanged(ChatRoom cr, ChatRoom.State newState) {
- if (newState == ChatRoom.State.Created) {
- mWaitLayout.setVisibility(View.GONE);
- LinphoneActivity.instance().goToChat(cr.getPeerAddress().asStringUriOnly(), null);
- } else if (newState == ChatRoom.State.CreationFailed) {
- mWaitLayout.setVisibility(View.GONE);
- LinphoneActivity.instance().displayChatRoomError();
- Log.e("Group chat room for address " + cr.getPeerAddress() + " has failed !");
- }
- }
- };
-
- return view;
- }
-
- @Override
- public void onPause() {
- if (mChatRoom != null) {
- mChatRoom.removeListener(mChatRoomCreationListener);
- }
- super.onPause();
- }
-
- public void changeDisplayedContact(LinphoneContact newContact) {
- contact = newContact;
- displayContact(inflater, view);
- }
-
- @SuppressLint("InflateParams")
- private void displayContact(LayoutInflater inflater, View view) {
- ImageView contactPicture = view.findViewById(R.id.contact_picture);
- if (contact.hasPhoto()) {
- LinphoneUtils.setImagePictureFromUri(getActivity(), contactPicture, contact.getPhotoUri(), contact.getThumbnailUri());
- } else {
- contactPicture.setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap());
+ if (getArguments() != null) {
+ displayChatAddressOnly = getArguments().getBoolean("ChatAddressOnly");
}
- TextView contactName = view.findViewById(R.id.contact_name);
- contactName.setText(contact.getFullName());
- organization.setText((contact.getOrganization() != null) ? contact.getOrganization() : "");
+ mWaitLayout = view.findViewById(R.id.waitScreen);
+ mWaitLayout.setVisibility(View.GONE);
- TableLayout controls = view.findViewById(R.id.controls);
- controls.removeAllViews();
- for (LinphoneNumberOrAddress noa : contact.getNumbersOrAddresses()) {
- boolean skip = false;
- View v = inflater.inflate(R.layout.contact_control_row, null);
+ editContact = view.findViewById(R.id.editContact);
+ editContact.setOnClickListener(this);
- String value = noa.getValue();
- String displayednumberOrAddress = LinphoneUtils.getDisplayableUsernameFromAddress(value);
+ deleteContact = view.findViewById(R.id.deleteContact);
+ deleteContact.setOnClickListener(this);
- TextView label = v.findViewById(R.id.address_label);
- if (noa.isSIPAddress()) {
- label.setText(R.string.sip_address);
- skip |= getResources().getBoolean(R.bool.hide_contact_sip_addresses);
- } else {
- label.setText(R.string.phone_number);
- skip |= getResources().getBoolean(R.bool.hide_contact_phone_numbers);
- }
+ organization = view.findViewById(R.id.contactOrganization);
+ boolean isOrgVisible = getResources().getBoolean(R.bool.display_contact_organization);
+ String org = contact.getOrganization();
+ if (org != null && !org.isEmpty() && isOrgVisible) {
+ organization.setText(org);
+ } else {
+ organization.setVisibility(View.GONE);
+ }
- TextView tv = v.findViewById(R.id.numeroOrAddress);
- tv.setText(displayednumberOrAddress);
- tv.setSelected(true);
+ back = view.findViewById(R.id.back);
+ if (getResources().getBoolean(R.bool.isTablet)) {
+ back.setVisibility(View.INVISIBLE);
+ } else {
+ back.setOnClickListener(this);
+ }
+
+ mChatRoomCreationListener = new ChatRoomListenerStub() {
+ @Override
+ public void onStateChanged(ChatRoom cr, ChatRoom.State newState) {
+ if (newState == ChatRoom.State.Created) {
+ mWaitLayout.setVisibility(View.GONE);
+ LinphoneActivity.instance().goToChat(cr.getPeerAddress().asStringUriOnly(), null);
+ } else if (newState == ChatRoom.State.CreationFailed) {
+ mWaitLayout.setVisibility(View.GONE);
+ LinphoneActivity.instance().displayChatRoomError();
+ Log.e("Group chat room for address " + cr.getPeerAddress() + " has failed !");
+ }
+ }
+ };
+
+ return view;
+ }
+
+ @Override
+ public void onPause() {
+ if (mChatRoom != null) {
+ mChatRoom.removeListener(mChatRoomCreationListener);
+ }
+ super.onPause();
+ }
+
+ public void changeDisplayedContact(LinphoneContact newContact) {
+ contact = newContact;
+ displayContact(inflater, view);
+ }
+
+ @SuppressLint("InflateParams")
+ private void displayContact(LayoutInflater inflater, View view) {
+ ImageView contactPicture = view.findViewById(R.id.contact_picture);
+ if (contact.hasPhoto()) {
+ LinphoneUtils.setImagePictureFromUri(getActivity(), contactPicture, contact.getPhotoUri(), contact.getThumbnailUri());
+ } else {
+ contactPicture.setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap());
+ }
+
+ TextView contactName = view.findViewById(R.id.contact_name);
+ contactName.setText(contact.getFullName());
+ organization.setText((contact.getOrganization() != null) ? contact.getOrganization() : "");
+
+ TableLayout controls = view.findViewById(R.id.controls);
+ controls.removeAllViews();
+ for (LinphoneNumberOrAddress noa : contact.getNumbersOrAddresses()) {
+ boolean skip = false;
+ View v = inflater.inflate(R.layout.contact_control_row, null);
+
+ String value = noa.getValue();
+ String displayednumberOrAddress = LinphoneUtils.getDisplayableUsernameFromAddress(value);
+
+ TextView label = v.findViewById(R.id.address_label);
+ if (noa.isSIPAddress()) {
+ label.setText(R.string.sip_address);
+ skip |= getResources().getBoolean(R.bool.hide_contact_sip_addresses);
+ } else {
+ label.setText(R.string.phone_number);
+ skip |= getResources().getBoolean(R.bool.hide_contact_phone_numbers);
+ }
+
+ TextView tv = v.findViewById(R.id.numeroOrAddress);
+ tv.setText(displayednumberOrAddress);
+ tv.setSelected(true);
- ProxyConfig lpc = LinphoneManager.getLc().getDefaultProxyConfig();
- if (lpc != null) {
- String username = lpc.normalizePhoneNumber(displayednumberOrAddress);
- if (username != null) {
- value = LinphoneUtils.getFullAddressFromUsername(username);
- }
- }
+ ProxyConfig lpc = LinphoneManager.getLc().getDefaultProxyConfig();
+ if (lpc != null) {
+ String username = lpc.normalizePhoneNumber(displayednumberOrAddress);
+ if (username != null) {
+ value = LinphoneUtils.getFullAddressFromUsername(username);
+ }
+ }
- String contactAddress = contact.getPresenceModelForUriOrTel(noa.getValue());
- if (contactAddress != null) {
- v.findViewById(R.id.friendLinphone).setVisibility(View.VISIBLE);
- }
+ String contactAddress = contact.getPresenceModelForUriOrTel(noa.getValue());
+ if (contactAddress != null) {
+ v.findViewById(R.id.friendLinphone).setVisibility(View.VISIBLE);
+ }
- if (!displayChatAddressOnly) {
- v.findViewById(R.id.contact_call).setOnClickListener(dialListener);
- if (contactAddress != null) {
- v.findViewById(R.id.contact_call).setTag(contactAddress);
- } else {
- v.findViewById(R.id.contact_call).setTag(value);
- }
- } else {
- v.findViewById(R.id.contact_call).setVisibility(View.GONE);
- }
+ if (!displayChatAddressOnly) {
+ v.findViewById(R.id.contact_call).setOnClickListener(dialListener);
+ if (contactAddress != null) {
+ v.findViewById(R.id.contact_call).setTag(contactAddress);
+ } else {
+ v.findViewById(R.id.contact_call).setTag(value);
+ }
+ } else {
+ v.findViewById(R.id.contact_call).setVisibility(View.GONE);
+ }
- v.findViewById(R.id.contact_chat).setOnClickListener(chatListener);
- if (contactAddress != null) {
- v.findViewById(R.id.contact_chat).setTag(contactAddress);
- } else {
- v.findViewById(R.id.contact_chat).setTag(value);
- }
+ v.findViewById(R.id.contact_chat).setOnClickListener(chatListener);
+ if (contactAddress != null) {
+ v.findViewById(R.id.contact_chat).setTag(contactAddress);
+ } else {
+ v.findViewById(R.id.contact_chat).setTag(value);
+ }
- if (getResources().getBoolean(R.bool.disable_chat)) {
- v.findViewById(R.id.contact_chat).setVisibility(View.GONE);
- }
+ if (getResources().getBoolean(R.bool.disable_chat)) {
+ v.findViewById(R.id.contact_chat).setVisibility(View.GONE);
+ }
- if (!skip) {
- controls.addView(v);
- }
- }
- }
+ if (!skip) {
+ controls.addView(v);
+ }
+ }
+ }
- @Override
- public void onResume() {
- super.onResume();
+ @Override
+ public void onResume() {
+ super.onResume();
- if (LinphoneActivity.isInstanciated()) {
- LinphoneActivity.instance().selectMenu(FragmentsAvailable.CONTACT_DETAIL);
- LinphoneActivity.instance().hideTabBar(false);
- }
- contact.refresh();
- displayContact(inflater, view);
- }
+ if (LinphoneActivity.isInstanciated()) {
+ LinphoneActivity.instance().selectMenu(FragmentsAvailable.CONTACT_DETAIL);
+ LinphoneActivity.instance().hideTabBar(false);
+ }
+ contact.refresh();
+ displayContact(inflater, view);
+ }
- @Override
- public void onClick(View v) {
- int id = v.getId();
+ @Override
+ public void onClick(View v) {
+ int id = v.getId();
- if (id == R.id.editContact) {
- LinphoneActivity.instance().editContact(contact);
- }
- if (id == R.id.deleteContact) {
- final Dialog dialog = LinphoneActivity.instance().displayDialog(getString(R.string.delete_text));
- Button delete = dialog.findViewById(R.id.delete_button);
- Button cancel = dialog.findViewById(R.id.cancel);
+ if (id == R.id.editContact) {
+ LinphoneActivity.instance().editContact(contact);
+ }
+ if (id == R.id.deleteContact) {
+ final Dialog dialog = LinphoneActivity.instance().displayDialog(getString(R.string.delete_text));
+ Button delete = dialog.findViewById(R.id.delete_button);
+ Button cancel = dialog.findViewById(R.id.cancel);
- delete.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View view) {
- contact.delete();
- LinphoneActivity.instance().displayContacts(false);
- dialog.dismiss();
- }
- });
+ delete.setOnClickListener(new OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ contact.delete();
+ LinphoneActivity.instance().displayContacts(false);
+ dialog.dismiss();
+ }
+ });
- cancel.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View view) {
- dialog.dismiss();
+ cancel.setOnClickListener(new OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ dialog.dismiss();
- }
- });
- dialog.show();
- }
- if (id == R.id.back) {
- getFragmentManager().popBackStackImmediate();
- }
- }
+ }
+ });
+ dialog.show();
+ }
+ if (id == R.id.back) {
+ getFragmentManager().popBackStackImmediate();
+ }
+ }
}
diff --git a/src/android/org/linphone/contacts/ContactEditorFragment.java b/src/android/org/linphone/contacts/ContactEditorFragment.java
index f6c47e8a5..d8b42bbe0 100644
--- a/src/android/org/linphone/contacts/ContactEditorFragment.java
+++ b/src/android/org/linphone/contacts/ContactEditorFragment.java
@@ -63,549 +63,549 @@ import java.util.ArrayList;
import java.util.List;
public class ContactEditorFragment extends Fragment {
- private View view;
- private ImageView cancel, deleteContact, ok;
- private ImageView addNumber, addSipAddress, contactPicture;
- private LinearLayout phoneNumbersSection, sipAddressesSection;
- private EditText firstName, lastName, organization;
- private LayoutInflater inflater;
-
- private static final int ADD_PHOTO = 1337;
- private static final int PHOTO_SIZE = 128;
-
- private boolean isNewContact;
- private LinphoneContact contact;
- private List numbersAndAddresses;
- private int firstSipAddressIndex = -1;
- private LinearLayout sipAddresses, numbers;
- private String newSipOrNumberToAdd, newDisplayName;
- private Uri pickedPhotoForContactUri;
- private byte[] photoToAdd;
-
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
- this.inflater = inflater;
-
- contact = null;
- isNewContact = true;
-
- if (getArguments() != null) {
- Serializable obj = getArguments().getSerializable("Contact");
- if (obj != null) {
- contact = (LinphoneContact) obj;
- isNewContact = false;
- if (getArguments().getString("NewSipAdress") != null) {
- newSipOrNumberToAdd = getArguments().getString("NewSipAdress");
- }if (getArguments().getString("NewDisplayName") != null) {
- newDisplayName = getArguments().getString("NewDisplayName");
- }
- } else if (getArguments().getString("NewSipAdress") != null) {
- newSipOrNumberToAdd = getArguments().getString("NewSipAdress");
- if (getArguments().getString("NewDisplayName") != null) {
- newDisplayName = getArguments().getString("NewDisplayName");
- }
- }
- }
-
- view = inflater.inflate(R.layout.contact_edit, container, false);
-
- phoneNumbersSection = (LinearLayout) view.findViewById(R.id.phone_numbers);
- if (getResources().getBoolean(R.bool.hide_phone_numbers_in_editor) || !ContactsManager.getInstance().hasContactsAccess()) {
- //Currently linphone friends don't support phone numbers, so hide them
- phoneNumbersSection.setVisibility(View.GONE);
- }
-
- sipAddressesSection = (LinearLayout) view.findViewById(R.id.sip_addresses);
- if (getResources().getBoolean(R.bool.hide_sip_addresses_in_editor)) {
- sipAddressesSection.setVisibility(View.GONE);
- }
-
- deleteContact = (ImageView) view.findViewById(R.id.delete_contact);
-
- cancel = (ImageView) view.findViewById(R.id.cancel);
- cancel.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- getFragmentManager().popBackStackImmediate();
- }
- });
-
- ok = (ImageView) view.findViewById(R.id.ok);
- ok.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- if (isNewContact) {
- boolean areAllFielsEmpty = true;
- for (LinphoneNumberOrAddress nounoa : numbersAndAddresses) {
- if (nounoa.getValue() != null && !nounoa.getValue().equals("")) {
- areAllFielsEmpty = false;
- break;
- }
- }
- if (areAllFielsEmpty) {
- getFragmentManager().popBackStackImmediate();
- return;
- }
- contact = LinphoneContact.createContact();
- }
- contact.setFirstNameAndLastName(firstName.getText().toString(), lastName.getText().toString());
- if (photoToAdd != null) {
- contact.setPhoto(photoToAdd);
- }
- for (LinphoneNumberOrAddress noa : numbersAndAddresses) {
- if (noa.isSIPAddress() && noa.getValue() != null) {
- noa.setValue(LinphoneUtils.getFullAddressFromUsername(noa.getValue()));
- }
- contact.addOrUpdateNumberOrAddress(noa);
- }
- contact.setOrganization(organization.getText().toString());
- contact.save();
- getFragmentManager().popBackStackImmediate();
- }
- });
-
- lastName = (EditText) view.findViewById(R.id.contactLastName);
- // Hack to display keyboard when touching focused edittext on Nexus One
- if (Version.sdkStrictlyBelow(Version.API11_HONEYCOMB_30)) {
- lastName.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- InputMethodManager imm = (InputMethodManager) LinphoneActivity.instance().getSystemService(Context.INPUT_METHOD_SERVICE);
- imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
- }
- });
- }
- lastName.addTextChangedListener(new TextWatcher() {
- @Override
- public void onTextChanged(CharSequence s, int start, int before, int count) {
- if (lastName.getText().length() > 0 || firstName.getText().length() > 0) {
- ok.setEnabled(true);
- } else {
- ok.setEnabled(false);
- }
- }
-
- @Override
- public void beforeTextChanged(CharSequence s, int start, int count, int after) {
- }
-
- @Override
- public void afterTextChanged(Editable s) {
- }
- });
-
- firstName = (EditText) view.findViewById(R.id.contactFirstName);
- firstName.addTextChangedListener(new TextWatcher() {
- @Override
- public void onTextChanged(CharSequence s, int start, int before, int count) {
- if (firstName.getText().length() > 0 || lastName.getText().length() > 0) {
- ok.setEnabled(true);
- } else {
- ok.setEnabled(false);
- }
- }
-
- @Override
- public void beforeTextChanged(CharSequence s, int start, int count, int after) {
- }
-
- @Override
- public void afterTextChanged(Editable s) {
- }
- });
-
-
- organization = (EditText) view.findViewById(R.id.contactOrganization);
- boolean isOrgVisible = getResources().getBoolean(R.bool.display_contact_organization);
- if (!isOrgVisible) {
- organization.setVisibility(View.GONE);
- view.findViewById(R.id.contactOrganizationTitle).setVisibility(View.GONE);
- } else {
- if (!isNewContact) {
- organization.setText(contact.getOrganization());
- }
- }
-
- if (!isNewContact) {
- String fn = contact.getFirstName();
- String ln = contact.getLastName();
- if (fn != null || ln != null) {
- firstName.setText(fn);
- lastName.setText(ln);
- } else {
- lastName.setText(contact.getFullName());
- firstName.setText("");
- }
-
- deleteContact.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- final Dialog dialog = LinphoneActivity.instance().displayDialog(getString(R.string.delete_text));
- Button delete = (Button) dialog.findViewById(R.id.delete_button);
- Button cancel = (Button) dialog.findViewById(R.id.cancel);
-
- delete.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View view) {
- contact.delete();
- LinphoneActivity.instance().displayContacts(false);
- dialog.dismiss();
- }
- });
-
- cancel.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View view) {
- dialog.dismiss();
-
- }
- });
- dialog.show();
- }
- });
- } else {
- deleteContact.setVisibility(View.INVISIBLE);
- }
-
- contactPicture = (ImageView) view.findViewById(R.id.contact_picture);
- if (contact != null) {
- LinphoneUtils.setImagePictureFromUri(getActivity(), contactPicture, contact.getPhotoUri(), contact.getThumbnailUri());
- } else {
- contactPicture.setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap());
- }
-
- contactPicture.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View view) {
- pickImage();
- LinphoneActivity.instance().checkAndRequestCameraPermission();
- }
- });
-
- numbersAndAddresses = new ArrayList();
- sipAddresses = initSipAddressFields(contact);
- numbers = initNumbersFields(contact);
-
- addSipAddress = (ImageView) view.findViewById(R.id.add_address_field);
- if (getResources().getBoolean(R.bool.allow_only_one_sip_address)) {
- addSipAddress.setVisibility(View.GONE);
- }
- addSipAddress.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View view) {
- addEmptyRowToAllowNewNumberOrAddress(sipAddresses,true);
- }
- });
-
- addNumber = (ImageView) view.findViewById(R.id.add_number_field);
- if (getResources().getBoolean(R.bool.allow_only_one_phone_number)) {
- addNumber.setVisibility(View.GONE);
- }
- addNumber.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View view) {
- addEmptyRowToAllowNewNumberOrAddress(numbers,false);
- }
- });
-
- lastName.requestFocus();
-
- return view;
- }
-
- @Override
- public void onResume() {
- super.onResume();
-
- if(LinphoneActivity.isInstanciated()){
- LinphoneActivity.instance().hideTabBar(false);
- }
-
- // Force hide keyboard
- getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
- }
-
- @Override
- public void onPause() {
- // Force hide keyboard
- InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
- View view = getActivity().getCurrentFocus();
- if (imm != null && view != null) {
- imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
- }
-
- super.onPause();
- }
-
- private void pickImage() {
- pickedPhotoForContactUri = null;
- final List cameraIntents = new ArrayList();
- final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
- File file = new File(Environment.getExternalStorageDirectory(), getString(R.string.temp_photo_name));
- pickedPhotoForContactUri = Uri.fromFile(file);
- captureIntent.putExtra("outputX", PHOTO_SIZE);
- captureIntent.putExtra("outputY", PHOTO_SIZE);
- captureIntent.putExtra("aspectX", 0);
- captureIntent.putExtra("aspectY", 0);
- captureIntent.putExtra("scale", true);
- captureIntent.putExtra("return-data", false);
- captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, pickedPhotoForContactUri);
- cameraIntents.add(captureIntent);
-
- final Intent galleryIntent = new Intent();
- galleryIntent.setType("image/*");
- galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
-
- final Intent chooserIntent = Intent.createChooser(galleryIntent, getString(R.string.image_picker_title));
- chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
-
- startActivityForResult(chooserIntent, ADD_PHOTO);
- }
-
- @Override
- public void onActivityResult(int requestCode, int resultCode, Intent data) {
- if (requestCode == ADD_PHOTO && resultCode == Activity.RESULT_OK) {
- if (data != null && data.getExtras() != null && data.getExtras().get("data") != null) {
- Bitmap bm = (Bitmap) data.getExtras().get("data");
- editContactPicture(null, bm);
- }
- else if (data != null && data.getData() != null) {
- Uri selectedImageUri = data.getData();
- try {
- Bitmap selectedImage = MediaStore.Images.Media.getBitmap(LinphoneManager.getInstance().getContext().getContentResolver(), selectedImageUri);
- selectedImage = Bitmap.createScaledBitmap(selectedImage, PHOTO_SIZE, PHOTO_SIZE, false);
- editContactPicture(null, selectedImage);
- } catch (IOException e) { Log.e(e); }
- }
- else if (pickedPhotoForContactUri != null) {
- String filePath = pickedPhotoForContactUri.getPath();
- editContactPicture(filePath, null);
- }
- else {
- File file = new File(Environment.getExternalStorageDirectory(), getString(R.string.temp_photo_name));
- if (file.exists()) {
- pickedPhotoForContactUri = Uri.fromFile(file);
- String filePath = pickedPhotoForContactUri.getPath();
- editContactPicture(filePath, null);
- }
- }
- } else {
- super.onActivityResult(requestCode, resultCode, data);
- }
- }
-
- private void editContactPicture(String filePath, Bitmap image) {
- if (image == null) {
- image = BitmapFactory.decodeFile(filePath);
- }
-
- Bitmap scaledPhoto;
- int size = getThumbnailSize();
- if (size > 0) {
- scaledPhoto = Bitmap.createScaledBitmap(image, size, size, false);
- } else {
- scaledPhoto = Bitmap.createBitmap(image);
- }
- image.recycle();
-
- ByteArrayOutputStream stream = new ByteArrayOutputStream();
- scaledPhoto.compress(Bitmap.CompressFormat.PNG , 0, stream);
- contactPicture.setImageBitmap(scaledPhoto);
- photoToAdd = stream.toByteArray();
- }
-
- private int getThumbnailSize() {
- int value = -1;
- Cursor c = LinphoneActivity.instance().getContentResolver().query(DisplayPhoto.CONTENT_MAX_DIMENSIONS_URI, new String[] { DisplayPhoto.THUMBNAIL_MAX_DIM }, null, null, null);
- try {
- c.moveToFirst();
- value = c.getInt(0);
- } catch (Exception e) {
- Log.e(e);
- }
- return value;
- }
-
- private LinearLayout initNumbersFields(final LinphoneContact contact) {
- LinearLayout controls = (LinearLayout) view.findViewById(R.id.controls_numbers);
- controls.removeAllViews();
-
- if (contact != null) {
- for (LinphoneNumberOrAddress numberOrAddress : contact.getNumbersOrAddresses()) {
- if (!numberOrAddress.isSIPAddress()) {
- View view = displayNumberOrAddress(controls, numberOrAddress.getValue(), false);
- if (view != null)
- controls.addView(view);
- }
- }
- }
-
- if (newSipOrNumberToAdd != null) {
- boolean isSip = LinphoneUtils.isStrictSipAddress(newSipOrNumberToAdd) || !LinphoneUtils.isNumberAddress(newSipOrNumberToAdd);
- if(!isSip) {
- View view = displayNumberOrAddress(controls, newSipOrNumberToAdd, false);
- if (view != null)
- controls.addView(view);
- }
- }
-
- if (newDisplayName != null) {
- EditText lastNameEditText = (EditText) view.findViewById(R.id.contactLastName);
- if (view != null)
- lastNameEditText.setText(newDisplayName);
- }
-
- if (controls.getChildCount() == 0) {
- addEmptyRowToAllowNewNumberOrAddress(controls,false);
- }
-
- return controls;
- }
-
- private LinearLayout initSipAddressFields(final LinphoneContact contact) {
- LinearLayout controls = (LinearLayout) view.findViewById(R.id.controls_sip_address);
- controls.removeAllViews();
-
- if (contact != null) {
- for (LinphoneNumberOrAddress numberOrAddress : contact.getNumbersOrAddresses()) {
- if (numberOrAddress.isSIPAddress()) {
- View view = displayNumberOrAddress(controls, numberOrAddress.getValue(), true);
- if (view != null)
- controls.addView(view);
- }
- }
- }
-
- if (newSipOrNumberToAdd != null) {
- boolean isSip = LinphoneUtils.isStrictSipAddress(newSipOrNumberToAdd) || !LinphoneUtils.isNumberAddress(newSipOrNumberToAdd);
- if (isSip) {
- View view = displayNumberOrAddress(controls, newSipOrNumberToAdd, true);
- if (view != null)
- controls.addView(view);
- }
- }
-
- if (controls.getChildCount() == 0) {
- addEmptyRowToAllowNewNumberOrAddress(controls,true);
- }
-
- return controls;
- }
-
- private View displayNumberOrAddress(final LinearLayout controls, String numberOrAddress, boolean isSIP) {
- return displayNumberOrAddress(controls, numberOrAddress, isSIP, false);
- }
-
- @SuppressLint("InflateParams")
- private View displayNumberOrAddress(final LinearLayout controls, String numberOrAddress, boolean isSIP, boolean forceAddNumber) {
- String displayNumberOrAddress = numberOrAddress;
- if (isSIP) {
- if (firstSipAddressIndex == -1) {
- firstSipAddressIndex = controls.getChildCount();
- }
- displayNumberOrAddress = LinphoneUtils.getDisplayableUsernameFromAddress(numberOrAddress);
- }
- if ((getResources().getBoolean(R.bool.hide_phone_numbers_in_editor) && !isSIP) || (getResources().getBoolean(R.bool.hide_sip_addresses_in_editor) && isSIP)) {
- if (forceAddNumber)
- isSIP = !isSIP; // If number can't be displayed because we hide a sort of number, change that category
- else
- return null;
- }
-
- LinphoneNumberOrAddress tempNounoa;
- if (forceAddNumber) {
- tempNounoa = new LinphoneNumberOrAddress(null, isSIP);
- } else {
- if(isNewContact || newSipOrNumberToAdd != null) {
- tempNounoa = new LinphoneNumberOrAddress(numberOrAddress, isSIP);
- } else {
- tempNounoa = new LinphoneNumberOrAddress(null, isSIP, numberOrAddress);
- }
- }
- final LinphoneNumberOrAddress nounoa = tempNounoa;
- numbersAndAddresses.add(nounoa);
-
- final View view = inflater.inflate(R.layout.contact_edit_row, null);
-
- final EditText noa = (EditText) view.findViewById(R.id.numoraddr);
- if (!isSIP) {
- noa.setInputType(InputType.TYPE_CLASS_PHONE);
- }
- noa.setText(displayNumberOrAddress);
- noa.addTextChangedListener(new TextWatcher() {
- @Override
- public void onTextChanged(CharSequence s, int start, int before, int count) {
- nounoa.setValue(noa.getText().toString());
- }
-
- @Override
- public void beforeTextChanged(CharSequence s, int start, int count, int after) {
- }
-
- @Override
- public void afterTextChanged(Editable s) {
- }
- });
- if (forceAddNumber) {
- nounoa.setValue(noa.getText().toString());
- }
-
- ImageView delete = (ImageView) view.findViewById(R.id.delete_field);
- if ((getResources().getBoolean(R.bool.allow_only_one_phone_number) && !isSIP) || (getResources().getBoolean(R.bool.allow_only_one_sip_address) && isSIP)) {
- delete.setVisibility(View.GONE);
- }
- delete.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- if (contact != null) {
- contact.removeNumberOrAddress(nounoa);
- }
- numbersAndAddresses.remove(nounoa);
- view.setVisibility(View.GONE);
-
- }
- });
- return view;
- }
-
- @SuppressLint("InflateParams")
- private void addEmptyRowToAllowNewNumberOrAddress(final LinearLayout controls, final boolean isSip) {
- final View view = inflater.inflate(R.layout.contact_edit_row, null);
- final LinphoneNumberOrAddress nounoa = new LinphoneNumberOrAddress(null, isSip);
-
- final EditText noa = (EditText) view.findViewById(R.id.numoraddr);
- numbersAndAddresses.add(nounoa);
- noa.setHint(isSip ? getString(R.string.sip_address) : getString(R.string.phone_number));
- if (!isSip) {
- noa.setInputType(InputType.TYPE_CLASS_PHONE);
- }
- noa.requestFocus();
- noa.addTextChangedListener(new TextWatcher() {
- @Override
- public void onTextChanged(CharSequence s, int start, int before, int count) {
- nounoa.setValue(noa.getText().toString());
- }
-
- @Override
- public void beforeTextChanged(CharSequence s, int start, int count, int after) {
- }
-
- @Override
- public void afterTextChanged(Editable s) {
- }
- });
-
- final ImageView delete = (ImageView) view.findViewById(R.id.delete_field);
- if ((getResources().getBoolean(R.bool.allow_only_one_phone_number) && !isSip) || (getResources().getBoolean(R.bool.allow_only_one_sip_address) && isSip)) {
- delete.setVisibility(View.GONE);
- }
- delete.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- numbersAndAddresses.remove(nounoa);
- view.setVisibility(View.GONE);
- }
- });
-
- controls.addView(view);
- }
+ private View view;
+ private ImageView cancel, deleteContact, ok;
+ private ImageView addNumber, addSipAddress, contactPicture;
+ private LinearLayout phoneNumbersSection, sipAddressesSection;
+ private EditText firstName, lastName, organization;
+ private LayoutInflater inflater;
+
+ private static final int ADD_PHOTO = 1337;
+ private static final int PHOTO_SIZE = 128;
+
+ private boolean isNewContact;
+ private LinphoneContact contact;
+ private List numbersAndAddresses;
+ private int firstSipAddressIndex = -1;
+ private LinearLayout sipAddresses, numbers;
+ private String newSipOrNumberToAdd, newDisplayName;
+ private Uri pickedPhotoForContactUri;
+ private byte[] photoToAdd;
+
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ this.inflater = inflater;
+
+ contact = null;
+ isNewContact = true;
+
+ if (getArguments() != null) {
+ Serializable obj = getArguments().getSerializable("Contact");
+ if (obj != null) {
+ contact = (LinphoneContact) obj;
+ isNewContact = false;
+ if (getArguments().getString("NewSipAdress") != null) {
+ newSipOrNumberToAdd = getArguments().getString("NewSipAdress");
+ }
+ if (getArguments().getString("NewDisplayName") != null) {
+ newDisplayName = getArguments().getString("NewDisplayName");
+ }
+ } else if (getArguments().getString("NewSipAdress") != null) {
+ newSipOrNumberToAdd = getArguments().getString("NewSipAdress");
+ if (getArguments().getString("NewDisplayName") != null) {
+ newDisplayName = getArguments().getString("NewDisplayName");
+ }
+ }
+ }
+
+ view = inflater.inflate(R.layout.contact_edit, container, false);
+
+ phoneNumbersSection = (LinearLayout) view.findViewById(R.id.phone_numbers);
+ if (getResources().getBoolean(R.bool.hide_phone_numbers_in_editor) || !ContactsManager.getInstance().hasContactsAccess()) {
+ //Currently linphone friends don't support phone numbers, so hide them
+ phoneNumbersSection.setVisibility(View.GONE);
+ }
+
+ sipAddressesSection = (LinearLayout) view.findViewById(R.id.sip_addresses);
+ if (getResources().getBoolean(R.bool.hide_sip_addresses_in_editor)) {
+ sipAddressesSection.setVisibility(View.GONE);
+ }
+
+ deleteContact = (ImageView) view.findViewById(R.id.delete_contact);
+
+ cancel = (ImageView) view.findViewById(R.id.cancel);
+ cancel.setOnClickListener(new OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ getFragmentManager().popBackStackImmediate();
+ }
+ });
+
+ ok = (ImageView) view.findViewById(R.id.ok);
+ ok.setOnClickListener(new OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (isNewContact) {
+ boolean areAllFielsEmpty = true;
+ for (LinphoneNumberOrAddress nounoa : numbersAndAddresses) {
+ if (nounoa.getValue() != null && !nounoa.getValue().equals("")) {
+ areAllFielsEmpty = false;
+ break;
+ }
+ }
+ if (areAllFielsEmpty) {
+ getFragmentManager().popBackStackImmediate();
+ return;
+ }
+ contact = LinphoneContact.createContact();
+ }
+ contact.setFirstNameAndLastName(firstName.getText().toString(), lastName.getText().toString());
+ if (photoToAdd != null) {
+ contact.setPhoto(photoToAdd);
+ }
+ for (LinphoneNumberOrAddress noa : numbersAndAddresses) {
+ if (noa.isSIPAddress() && noa.getValue() != null) {
+ noa.setValue(LinphoneUtils.getFullAddressFromUsername(noa.getValue()));
+ }
+ contact.addOrUpdateNumberOrAddress(noa);
+ }
+ contact.setOrganization(organization.getText().toString());
+ contact.save();
+ getFragmentManager().popBackStackImmediate();
+ }
+ });
+
+ lastName = (EditText) view.findViewById(R.id.contactLastName);
+ // Hack to display keyboard when touching focused edittext on Nexus One
+ if (Version.sdkStrictlyBelow(Version.API11_HONEYCOMB_30)) {
+ lastName.setOnClickListener(new OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ InputMethodManager imm = (InputMethodManager) LinphoneActivity.instance().getSystemService(Context.INPUT_METHOD_SERVICE);
+ imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
+ }
+ });
+ }
+ lastName.addTextChangedListener(new TextWatcher() {
+ @Override
+ public void onTextChanged(CharSequence s, int start, int before, int count) {
+ if (lastName.getText().length() > 0 || firstName.getText().length() > 0) {
+ ok.setEnabled(true);
+ } else {
+ ok.setEnabled(false);
+ }
+ }
+
+ @Override
+ public void beforeTextChanged(CharSequence s, int start, int count, int after) {
+ }
+
+ @Override
+ public void afterTextChanged(Editable s) {
+ }
+ });
+
+ firstName = (EditText) view.findViewById(R.id.contactFirstName);
+ firstName.addTextChangedListener(new TextWatcher() {
+ @Override
+ public void onTextChanged(CharSequence s, int start, int before, int count) {
+ if (firstName.getText().length() > 0 || lastName.getText().length() > 0) {
+ ok.setEnabled(true);
+ } else {
+ ok.setEnabled(false);
+ }
+ }
+
+ @Override
+ public void beforeTextChanged(CharSequence s, int start, int count, int after) {
+ }
+
+ @Override
+ public void afterTextChanged(Editable s) {
+ }
+ });
+
+
+ organization = (EditText) view.findViewById(R.id.contactOrganization);
+ boolean isOrgVisible = getResources().getBoolean(R.bool.display_contact_organization);
+ if (!isOrgVisible) {
+ organization.setVisibility(View.GONE);
+ view.findViewById(R.id.contactOrganizationTitle).setVisibility(View.GONE);
+ } else {
+ if (!isNewContact) {
+ organization.setText(contact.getOrganization());
+ }
+ }
+
+ if (!isNewContact) {
+ String fn = contact.getFirstName();
+ String ln = contact.getLastName();
+ if (fn != null || ln != null) {
+ firstName.setText(fn);
+ lastName.setText(ln);
+ } else {
+ lastName.setText(contact.getFullName());
+ firstName.setText("");
+ }
+
+ deleteContact.setOnClickListener(new OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ final Dialog dialog = LinphoneActivity.instance().displayDialog(getString(R.string.delete_text));
+ Button delete = (Button) dialog.findViewById(R.id.delete_button);
+ Button cancel = (Button) dialog.findViewById(R.id.cancel);
+
+ delete.setOnClickListener(new OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ contact.delete();
+ LinphoneActivity.instance().displayContacts(false);
+ dialog.dismiss();
+ }
+ });
+
+ cancel.setOnClickListener(new OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ dialog.dismiss();
+
+ }
+ });
+ dialog.show();
+ }
+ });
+ } else {
+ deleteContact.setVisibility(View.INVISIBLE);
+ }
+
+ contactPicture = (ImageView) view.findViewById(R.id.contact_picture);
+ if (contact != null) {
+ LinphoneUtils.setImagePictureFromUri(getActivity(), contactPicture, contact.getPhotoUri(), contact.getThumbnailUri());
+ } else {
+ contactPicture.setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap());
+ }
+
+ contactPicture.setOnClickListener(new OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ pickImage();
+ LinphoneActivity.instance().checkAndRequestCameraPermission();
+ }
+ });
+
+ numbersAndAddresses = new ArrayList();
+ sipAddresses = initSipAddressFields(contact);
+ numbers = initNumbersFields(contact);
+
+ addSipAddress = (ImageView) view.findViewById(R.id.add_address_field);
+ if (getResources().getBoolean(R.bool.allow_only_one_sip_address)) {
+ addSipAddress.setVisibility(View.GONE);
+ }
+ addSipAddress.setOnClickListener(new OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ addEmptyRowToAllowNewNumberOrAddress(sipAddresses, true);
+ }
+ });
+
+ addNumber = (ImageView) view.findViewById(R.id.add_number_field);
+ if (getResources().getBoolean(R.bool.allow_only_one_phone_number)) {
+ addNumber.setVisibility(View.GONE);
+ }
+ addNumber.setOnClickListener(new OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ addEmptyRowToAllowNewNumberOrAddress(numbers, false);
+ }
+ });
+
+ lastName.requestFocus();
+
+ return view;
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+
+ if (LinphoneActivity.isInstanciated()) {
+ LinphoneActivity.instance().hideTabBar(false);
+ }
+
+ // Force hide keyboard
+ getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
+ }
+
+ @Override
+ public void onPause() {
+ // Force hide keyboard
+ InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
+ View view = getActivity().getCurrentFocus();
+ if (imm != null && view != null) {
+ imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
+ }
+
+ super.onPause();
+ }
+
+ private void pickImage() {
+ pickedPhotoForContactUri = null;
+ final List cameraIntents = new ArrayList();
+ final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
+ File file = new File(Environment.getExternalStorageDirectory(), getString(R.string.temp_photo_name));
+ pickedPhotoForContactUri = Uri.fromFile(file);
+ captureIntent.putExtra("outputX", PHOTO_SIZE);
+ captureIntent.putExtra("outputY", PHOTO_SIZE);
+ captureIntent.putExtra("aspectX", 0);
+ captureIntent.putExtra("aspectY", 0);
+ captureIntent.putExtra("scale", true);
+ captureIntent.putExtra("return-data", false);
+ captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, pickedPhotoForContactUri);
+ cameraIntents.add(captureIntent);
+
+ final Intent galleryIntent = new Intent();
+ galleryIntent.setType("image/*");
+ galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
+
+ final Intent chooserIntent = Intent.createChooser(galleryIntent, getString(R.string.image_picker_title));
+ chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
+
+ startActivityForResult(chooserIntent, ADD_PHOTO);
+ }
+
+ @Override
+ public void onActivityResult(int requestCode, int resultCode, Intent data) {
+ if (requestCode == ADD_PHOTO && resultCode == Activity.RESULT_OK) {
+ if (data != null && data.getExtras() != null && data.getExtras().get("data") != null) {
+ Bitmap bm = (Bitmap) data.getExtras().get("data");
+ editContactPicture(null, bm);
+ } else if (data != null && data.getData() != null) {
+ Uri selectedImageUri = data.getData();
+ try {
+ Bitmap selectedImage = MediaStore.Images.Media.getBitmap(LinphoneManager.getInstance().getContext().getContentResolver(), selectedImageUri);
+ selectedImage = Bitmap.createScaledBitmap(selectedImage, PHOTO_SIZE, PHOTO_SIZE, false);
+ editContactPicture(null, selectedImage);
+ } catch (IOException e) {
+ Log.e(e);
+ }
+ } else if (pickedPhotoForContactUri != null) {
+ String filePath = pickedPhotoForContactUri.getPath();
+ editContactPicture(filePath, null);
+ } else {
+ File file = new File(Environment.getExternalStorageDirectory(), getString(R.string.temp_photo_name));
+ if (file.exists()) {
+ pickedPhotoForContactUri = Uri.fromFile(file);
+ String filePath = pickedPhotoForContactUri.getPath();
+ editContactPicture(filePath, null);
+ }
+ }
+ } else {
+ super.onActivityResult(requestCode, resultCode, data);
+ }
+ }
+
+ private void editContactPicture(String filePath, Bitmap image) {
+ if (image == null) {
+ image = BitmapFactory.decodeFile(filePath);
+ }
+
+ Bitmap scaledPhoto;
+ int size = getThumbnailSize();
+ if (size > 0) {
+ scaledPhoto = Bitmap.createScaledBitmap(image, size, size, false);
+ } else {
+ scaledPhoto = Bitmap.createBitmap(image);
+ }
+ image.recycle();
+
+ ByteArrayOutputStream stream = new ByteArrayOutputStream();
+ scaledPhoto.compress(Bitmap.CompressFormat.PNG, 0, stream);
+ contactPicture.setImageBitmap(scaledPhoto);
+ photoToAdd = stream.toByteArray();
+ }
+
+ private int getThumbnailSize() {
+ int value = -1;
+ Cursor c = LinphoneActivity.instance().getContentResolver().query(DisplayPhoto.CONTENT_MAX_DIMENSIONS_URI, new String[]{DisplayPhoto.THUMBNAIL_MAX_DIM}, null, null, null);
+ try {
+ c.moveToFirst();
+ value = c.getInt(0);
+ } catch (Exception e) {
+ Log.e(e);
+ }
+ return value;
+ }
+
+ private LinearLayout initNumbersFields(final LinphoneContact contact) {
+ LinearLayout controls = (LinearLayout) view.findViewById(R.id.controls_numbers);
+ controls.removeAllViews();
+
+ if (contact != null) {
+ for (LinphoneNumberOrAddress numberOrAddress : contact.getNumbersOrAddresses()) {
+ if (!numberOrAddress.isSIPAddress()) {
+ View view = displayNumberOrAddress(controls, numberOrAddress.getValue(), false);
+ if (view != null)
+ controls.addView(view);
+ }
+ }
+ }
+
+ if (newSipOrNumberToAdd != null) {
+ boolean isSip = LinphoneUtils.isStrictSipAddress(newSipOrNumberToAdd) || !LinphoneUtils.isNumberAddress(newSipOrNumberToAdd);
+ if (!isSip) {
+ View view = displayNumberOrAddress(controls, newSipOrNumberToAdd, false);
+ if (view != null)
+ controls.addView(view);
+ }
+ }
+
+ if (newDisplayName != null) {
+ EditText lastNameEditText = (EditText) view.findViewById(R.id.contactLastName);
+ if (view != null)
+ lastNameEditText.setText(newDisplayName);
+ }
+
+ if (controls.getChildCount() == 0) {
+ addEmptyRowToAllowNewNumberOrAddress(controls, false);
+ }
+
+ return controls;
+ }
+
+ private LinearLayout initSipAddressFields(final LinphoneContact contact) {
+ LinearLayout controls = (LinearLayout) view.findViewById(R.id.controls_sip_address);
+ controls.removeAllViews();
+
+ if (contact != null) {
+ for (LinphoneNumberOrAddress numberOrAddress : contact.getNumbersOrAddresses()) {
+ if (numberOrAddress.isSIPAddress()) {
+ View view = displayNumberOrAddress(controls, numberOrAddress.getValue(), true);
+ if (view != null)
+ controls.addView(view);
+ }
+ }
+ }
+
+ if (newSipOrNumberToAdd != null) {
+ boolean isSip = LinphoneUtils.isStrictSipAddress(newSipOrNumberToAdd) || !LinphoneUtils.isNumberAddress(newSipOrNumberToAdd);
+ if (isSip) {
+ View view = displayNumberOrAddress(controls, newSipOrNumberToAdd, true);
+ if (view != null)
+ controls.addView(view);
+ }
+ }
+
+ if (controls.getChildCount() == 0) {
+ addEmptyRowToAllowNewNumberOrAddress(controls, true);
+ }
+
+ return controls;
+ }
+
+ private View displayNumberOrAddress(final LinearLayout controls, String numberOrAddress, boolean isSIP) {
+ return displayNumberOrAddress(controls, numberOrAddress, isSIP, false);
+ }
+
+ @SuppressLint("InflateParams")
+ private View displayNumberOrAddress(final LinearLayout controls, String numberOrAddress, boolean isSIP, boolean forceAddNumber) {
+ String displayNumberOrAddress = numberOrAddress;
+ if (isSIP) {
+ if (firstSipAddressIndex == -1) {
+ firstSipAddressIndex = controls.getChildCount();
+ }
+ displayNumberOrAddress = LinphoneUtils.getDisplayableUsernameFromAddress(numberOrAddress);
+ }
+ if ((getResources().getBoolean(R.bool.hide_phone_numbers_in_editor) && !isSIP) || (getResources().getBoolean(R.bool.hide_sip_addresses_in_editor) && isSIP)) {
+ if (forceAddNumber)
+ isSIP = !isSIP; // If number can't be displayed because we hide a sort of number, change that category
+ else
+ return null;
+ }
+
+ LinphoneNumberOrAddress tempNounoa;
+ if (forceAddNumber) {
+ tempNounoa = new LinphoneNumberOrAddress(null, isSIP);
+ } else {
+ if (isNewContact || newSipOrNumberToAdd != null) {
+ tempNounoa = new LinphoneNumberOrAddress(numberOrAddress, isSIP);
+ } else {
+ tempNounoa = new LinphoneNumberOrAddress(null, isSIP, numberOrAddress);
+ }
+ }
+ final LinphoneNumberOrAddress nounoa = tempNounoa;
+ numbersAndAddresses.add(nounoa);
+
+ final View view = inflater.inflate(R.layout.contact_edit_row, null);
+
+ final EditText noa = (EditText) view.findViewById(R.id.numoraddr);
+ if (!isSIP) {
+ noa.setInputType(InputType.TYPE_CLASS_PHONE);
+ }
+ noa.setText(displayNumberOrAddress);
+ noa.addTextChangedListener(new TextWatcher() {
+ @Override
+ public void onTextChanged(CharSequence s, int start, int before, int count) {
+ nounoa.setValue(noa.getText().toString());
+ }
+
+ @Override
+ public void beforeTextChanged(CharSequence s, int start, int count, int after) {
+ }
+
+ @Override
+ public void afterTextChanged(Editable s) {
+ }
+ });
+ if (forceAddNumber) {
+ nounoa.setValue(noa.getText().toString());
+ }
+
+ ImageView delete = (ImageView) view.findViewById(R.id.delete_field);
+ if ((getResources().getBoolean(R.bool.allow_only_one_phone_number) && !isSIP) || (getResources().getBoolean(R.bool.allow_only_one_sip_address) && isSIP)) {
+ delete.setVisibility(View.GONE);
+ }
+ delete.setOnClickListener(new OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (contact != null) {
+ contact.removeNumberOrAddress(nounoa);
+ }
+ numbersAndAddresses.remove(nounoa);
+ view.setVisibility(View.GONE);
+
+ }
+ });
+ return view;
+ }
+
+ @SuppressLint("InflateParams")
+ private void addEmptyRowToAllowNewNumberOrAddress(final LinearLayout controls, final boolean isSip) {
+ final View view = inflater.inflate(R.layout.contact_edit_row, null);
+ final LinphoneNumberOrAddress nounoa = new LinphoneNumberOrAddress(null, isSip);
+
+ final EditText noa = (EditText) view.findViewById(R.id.numoraddr);
+ numbersAndAddresses.add(nounoa);
+ noa.setHint(isSip ? getString(R.string.sip_address) : getString(R.string.phone_number));
+ if (!isSip) {
+ noa.setInputType(InputType.TYPE_CLASS_PHONE);
+ }
+ noa.requestFocus();
+ noa.addTextChangedListener(new TextWatcher() {
+ @Override
+ public void onTextChanged(CharSequence s, int start, int before, int count) {
+ nounoa.setValue(noa.getText().toString());
+ }
+
+ @Override
+ public void beforeTextChanged(CharSequence s, int start, int count, int after) {
+ }
+
+ @Override
+ public void afterTextChanged(Editable s) {
+ }
+ });
+
+ final ImageView delete = (ImageView) view.findViewById(R.id.delete_field);
+ if ((getResources().getBoolean(R.bool.allow_only_one_phone_number) && !isSip) || (getResources().getBoolean(R.bool.allow_only_one_sip_address) && isSip)) {
+ delete.setVisibility(View.GONE);
+ }
+ delete.setOnClickListener(new OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ numbersAndAddresses.remove(nounoa);
+ view.setVisibility(View.GONE);
+ }
+ });
+
+ controls.addView(view);
+ }
}
\ No newline at end of file
diff --git a/src/android/org/linphone/contacts/ContactsListAdapter.java b/src/android/org/linphone/contacts/ContactsListAdapter.java
index 3125753e9..13ad6a86c 100644
--- a/src/android/org/linphone/contacts/ContactsListAdapter.java
+++ b/src/android/org/linphone/contacts/ContactsListAdapter.java
@@ -87,6 +87,7 @@ public class ContactsListAdapter extends SelectableAdapter 0) {
- ContactsListAdapter mAdapt = (ContactsListAdapter)contactsList.getAdapter();
- LinphoneActivity.instance().displayContact((LinphoneContact) mAdapt.getItem(0), false);
- } else {
- LinphoneActivity.instance().displayEmptyFragment();
- }
- }
+ public void displayFirstContact() {
+ if (contactsList != null && contactsList.getAdapter() != null && contactsList.getAdapter().getItemCount() > 0) {
+ ContactsListAdapter mAdapt = (ContactsListAdapter) contactsList.getAdapter();
+ LinphoneActivity.instance().displayContact((LinphoneContact) mAdapt.getItem(0), false);
+ } else {
+ LinphoneActivity.instance().displayEmptyFragment();
+ }
+ }
- private void searchContacts(String search) {
- boolean isEditionEnabled = false;
- if (search == null || search.length() == 0) {
- changeContactsAdapter();
- return;
- }
- changeContactsToggle();
- mContactAdapter.setmIsSearchMode(true);
+ private void searchContacts(String search) {
+ boolean isEditionEnabled = false;
+ if (search == null || search.length() == 0) {
+ changeContactsAdapter();
+ return;
+ }
+ changeContactsToggle();
+ mContactAdapter.setmIsSearchMode(true);
- List listContact;
+ List listContact;
- if (onlyDisplayLinphoneContacts) {
- listContact = ContactsManager.getInstance().getSIPContacts(search);
- } else {
- listContact = ContactsManager.getInstance().getContacts(search);
- }
- if(mContactAdapter != null && mContactAdapter.isEditionEnabled()) {
- isEditionEnabled=true;
- }
+ if (onlyDisplayLinphoneContacts) {
+ listContact = ContactsManager.getInstance().getSIPContacts(search);
+ } else {
+ listContact = ContactsManager.getInstance().getContacts(search);
+ }
+ if (mContactAdapter != null && mContactAdapter.isEditionEnabled()) {
+ isEditionEnabled = true;
+ }
- mContactAdapter = new ContactsListAdapter(mContext, listContact, this, mSelectionHelper);
+ mContactAdapter = new ContactsListAdapter(mContext, listContact, this, mSelectionHelper);
// contactsList.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
- mSelectionHelper.setAdapter(mContactAdapter);
- if(isEditionEnabled) {
- mSelectionHelper.enterEditionMode();
- }
- contactsList.setAdapter(mContactAdapter);
- }
+ mSelectionHelper.setAdapter(mContactAdapter);
+ if (isEditionEnabled) {
+ mSelectionHelper.enterEditionMode();
+ }
+ contactsList.setAdapter(mContactAdapter);
+ }
- private void changeContactsAdapter() {
- changeContactsToggle();
- List listContact;
+ private void changeContactsAdapter() {
+ changeContactsToggle();
+ List listContact;
- noSipContact.setVisibility(View.GONE);
- noContact.setVisibility(View.GONE);
- contactsList.setVisibility(View.VISIBLE);
- boolean isEditionEnabled = false;
- if(searchField.getText().toString() == "") {
- if (onlyDisplayLinphoneContacts) {
- listContact = ContactsManager.getInstance().getSIPContacts();
- } else {
- listContact = ContactsManager.getInstance().getContacts();
- }
+ noSipContact.setVisibility(View.GONE);
+ noContact.setVisibility(View.GONE);
+ contactsList.setVisibility(View.VISIBLE);
+ boolean isEditionEnabled = false;
+ if (searchField.getText().toString() == "") {
+ if (onlyDisplayLinphoneContacts) {
+ listContact = ContactsManager.getInstance().getSIPContacts();
+ } else {
+ listContact = ContactsManager.getInstance().getContacts();
+ }
- }else{
- if (onlyDisplayLinphoneContacts) {
- listContact = ContactsManager.getInstance().getSIPContacts(searchField.getText().toString());
- } else {
- listContact = ContactsManager.getInstance().getContacts(searchField.getText().toString());
- }
- }
+ } else {
+ if (onlyDisplayLinphoneContacts) {
+ listContact = ContactsManager.getInstance().getSIPContacts(searchField.getText().toString());
+ } else {
+ listContact = ContactsManager.getInstance().getContacts(searchField.getText().toString());
+ }
+ }
- if(mContactAdapter != null && mContactAdapter.isEditionEnabled()) {
- isEditionEnabled=true;
- }
+ if (mContactAdapter != null && mContactAdapter.isEditionEnabled()) {
+ isEditionEnabled = true;
+ }
- mContactAdapter = new ContactsListAdapter(mContext, listContact, this, mSelectionHelper);
+ mContactAdapter = new ContactsListAdapter(mContext, listContact, this, mSelectionHelper);
- mSelectionHelper.setAdapter(mContactAdapter);
+ mSelectionHelper.setAdapter(mContactAdapter);
- if(isEditionEnabled) {
- mSelectionHelper.enterEditionMode();
- }
- contactsList.setAdapter(mContactAdapter);
- edit.setEnabled(true);
+ if (isEditionEnabled) {
+ mSelectionHelper.enterEditionMode();
+ }
+ contactsList.setAdapter(mContactAdapter);
+ edit.setEnabled(true);
- mContactAdapter.notifyDataSetChanged();
+ mContactAdapter.notifyDataSetChanged();
- if (mContactAdapter.getItemCount() > 0) {
- contactsFetchInProgress.setVisibility(View.GONE);
- }
- ContactsManager.getInstance().setLinphoneContactsPrefered(onlyDisplayLinphoneContacts);
- }
+ if (mContactAdapter.getItemCount() > 0) {
+ contactsFetchInProgress.setVisibility(View.GONE);
+ }
+ ContactsManager.getInstance().setLinphoneContactsPrefered(onlyDisplayLinphoneContacts);
+ }
- private void changeContactsToggle() {
- if (onlyDisplayLinphoneContacts) {
- allContacts.setEnabled(true);
- allContactsSelected.setVisibility(View.INVISIBLE);
- linphoneContacts.setEnabled(false);
- linphoneContactsSelected.setVisibility(View.VISIBLE);
- } else {
- allContacts.setEnabled(false);
- allContactsSelected.setVisibility(View.VISIBLE);
- linphoneContacts.setEnabled(true);
- linphoneContactsSelected.setVisibility(View.INVISIBLE);
- }
- }
+ private void changeContactsToggle() {
+ if (onlyDisplayLinphoneContacts) {
+ allContacts.setEnabled(true);
+ allContactsSelected.setVisibility(View.INVISIBLE);
+ linphoneContacts.setEnabled(false);
+ linphoneContactsSelected.setVisibility(View.VISIBLE);
+ } else {
+ allContacts.setEnabled(false);
+ allContactsSelected.setVisibility(View.VISIBLE);
+ linphoneContacts.setEnabled(true);
+ linphoneContactsSelected.setVisibility(View.INVISIBLE);
+ }
+ }
- @Override
- public void onItemClick(AdapterView> adapter, View view, int position, long id) {
- LinphoneContact contact = (LinphoneContact) adapter.getItemAtPosition(position);
- if (editOnClick) {
- editConsumed = true;
- LinphoneActivity.instance().editContact(contact, sipAddressToAdd);
- } else {
- lastKnownPosition = layoutManager.findFirstVisibleItemPosition();
- LinphoneActivity.instance().displayContact(contact, onlyDisplayChatAddress);
- }
- }
+ @Override
+ public void onItemClick(AdapterView> adapter, View view, int position, long id) {
+ LinphoneContact contact = (LinphoneContact) adapter.getItemAtPosition(position);
+ if (editOnClick) {
+ editConsumed = true;
+ LinphoneActivity.instance().editContact(contact, sipAddressToAdd);
+ } else {
+ lastKnownPosition = layoutManager.findFirstVisibleItemPosition();
+ LinphoneActivity.instance().displayContact(contact, onlyDisplayChatAddress);
+ }
+ }
- @Override
- public void onItemClicked(int position) {
- LinphoneContact contact = (LinphoneContact) mContactAdapter.getItem(position);
+ @Override
+ public void onItemClicked(int position) {
+ LinphoneContact contact = (LinphoneContact) mContactAdapter.getItem(position);
- if (mContactAdapter.isEditionEnabled()) {
- mContactAdapter.toggleSelection(position);
+ if (mContactAdapter.isEditionEnabled()) {
+ mContactAdapter.toggleSelection(position);
- } else if (editOnClick) {
- editConsumed = true;
- LinphoneActivity.instance().editContact(contact, sipAddressToAdd);
- } else {
- lastKnownPosition = layoutManager.findFirstVisibleItemPosition();
- LinphoneActivity.instance().displayContact(contact, onlyDisplayChatAddress);
- }
- }
+ } else if (editOnClick) {
+ editConsumed = true;
+ LinphoneActivity.instance().editContact(contact, sipAddressToAdd);
+ } else {
+ lastKnownPosition = layoutManager.findFirstVisibleItemPosition();
+ LinphoneActivity.instance().displayContact(contact, onlyDisplayChatAddress);
+ }
+ }
- @Override
- public boolean onItemLongClicked(int position) {
- if (!mContactAdapter.isEditionEnabled()) {
- mSelectionHelper.enterEditionMode();
- }
- mContactAdapter.toggleSelection(position);
- return true;
- }
+ @Override
+ public boolean onItemLongClicked(int position) {
+ if (!mContactAdapter.isEditionEnabled()) {
+ mSelectionHelper.enterEditionMode();
+ }
+ mContactAdapter.toggleSelection(position);
+ return true;
+ }
- @Override
- public void onResume() {
- super.onResume();
- ContactsManager.addContactsListener(this);
+ @Override
+ public void onResume() {
+ super.onResume();
+ ContactsManager.addContactsListener(this);
- if (editConsumed) {
- editOnClick = false;
- sipAddressToAdd = null;
- }
+ if (editConsumed) {
+ editOnClick = false;
+ sipAddressToAdd = null;
+ }
- if (searchField != null && searchField.getText().toString().length() > 0) {
- if (contactsFetchInProgress != null) contactsFetchInProgress.setVisibility(View.GONE);
- }
+ if (searchField != null && searchField.getText().toString().length() > 0) {
+ if (contactsFetchInProgress != null) contactsFetchInProgress.setVisibility(View.GONE);
+ }
- if (LinphoneActivity.isInstanciated()) {
- LinphoneActivity.instance().selectMenu(FragmentsAvailable.CONTACTS_LIST);
- LinphoneActivity.instance().hideTabBar(false);
- onlyDisplayLinphoneContacts = ContactsManager.getInstance().isLinphoneContactsPrefered();
- }
- changeContactsToggle();
- invalidate();
- }
+ if (LinphoneActivity.isInstanciated()) {
+ LinphoneActivity.instance().selectMenu(FragmentsAvailable.CONTACTS_LIST);
+ LinphoneActivity.instance().hideTabBar(false);
+ onlyDisplayLinphoneContacts = ContactsManager.getInstance().isLinphoneContactsPrefered();
+ }
+ changeContactsToggle();
+ invalidate();
+ }
- @Override
- public void onPause() {
- ContactsManager.removeContactsListener(this);
- super.onPause();
- }
+ @Override
+ public void onPause() {
+ ContactsManager.removeContactsListener(this);
+ super.onPause();
+ }
- @Override
- public void onContactsUpdated() {
- if (!LinphoneActivity.isInstanciated() || LinphoneActivity.instance().getCurrentFragment() != FragmentsAvailable.CONTACTS_LIST)
- return;
- ContactsListAdapter adapter = (ContactsListAdapter)contactsList.getAdapter();
- if (adapter != null) {
- if (onlyDisplayLinphoneContacts) {
- adapter.updateDataSet(ContactsManager.getInstance().getSIPContacts());
- } else {
- adapter.updateDataSet(ContactsManager.getInstance().getContacts());
- }
- contactsFetchInProgress.setVisibility(View.GONE);
- }
- }
+ @Override
+ public void onContactsUpdated() {
+ if (!LinphoneActivity.isInstanciated() || LinphoneActivity.instance().getCurrentFragment() != FragmentsAvailable.CONTACTS_LIST)
+ return;
+ ContactsListAdapter adapter = (ContactsListAdapter) contactsList.getAdapter();
+ if (adapter != null) {
+ if (onlyDisplayLinphoneContacts) {
+ adapter.updateDataSet(ContactsManager.getInstance().getSIPContacts());
+ } else {
+ adapter.updateDataSet(ContactsManager.getInstance().getContacts());
+ }
+ contactsFetchInProgress.setVisibility(View.GONE);
+ }
+ }
- public void invalidate() {
- if (searchField != null && searchField.getText().toString().length() > 0) {
- searchContacts(searchField.getText().toString());
- } else {
- changeContactsAdapter();
- }
- contactsList.scrollToPosition(lastKnownPosition);
- }
+ public void invalidate() {
+ if (searchField != null && searchField.getText().toString().length() > 0) {
+ searchContacts(searchField.getText().toString());
+ } else {
+ changeContactsAdapter();
+ }
+ contactsList.scrollToPosition(lastKnownPosition);
+ }
- @Override
- public void onDeleteSelection(Object[] objectsToDelete) {
- ArrayList ids = new ArrayList();
- int size = mContactAdapter.getSelectedItemCount();
- for (int i = size - 1; i >= 0; i--) {
- LinphoneContact contact = (LinphoneContact)objectsToDelete[i];
- if (contact.isAndroidContact()) {
- contact.deleteFriend();
- ids.add(contact.getAndroidId());
- } else {
- contact.delete();
- }
- }
- ContactsManager.getInstance().deleteMultipleContactsAtOnce(ids);
- }
+ @Override
+ public void onDeleteSelection(Object[] objectsToDelete) {
+ ArrayList ids = new ArrayList();
+ int size = mContactAdapter.getSelectedItemCount();
+ for (int i = size - 1; i >= 0; i--) {
+ LinphoneContact contact = (LinphoneContact) objectsToDelete[i];
+ if (contact.isAndroidContact()) {
+ contact.deleteFriend();
+ ids.add(contact.getAndroidId());
+ } else {
+ contact.delete();
+ }
+ }
+ ContactsManager.getInstance().deleteMultipleContactsAtOnce(ids);
+ }
}
diff --git a/src/android/org/linphone/contacts/ContactsManager.java b/src/android/org/linphone/contacts/ContactsManager.java
index 8e82f8879..25c47b1f6 100644
--- a/src/android/org/linphone/contacts/ContactsManager.java
+++ b/src/android/org/linphone/contacts/ContactsManager.java
@@ -60,568 +60,570 @@ import java.util.Set;
import java.util.concurrent.TimeUnit;
public class ContactsManager extends ContentObserver implements FriendListListener {
- private static ContactsManager instance;
-
- private List contacts, sipContacts;
- private MagicSearch magicSearch;
- private boolean preferLinphoneContacts = false, isContactPresenceDisabled = true;
- private ContentResolver contentResolver;
- private Context context;
- private HashMap androidContactsCache;
- private Bitmap defaultAvatar;
- private Handler handler;
-
- private static ArrayList contactsUpdatedListeners;
- public static void addContactsListener(ContactsUpdatedListener listener) {
- contactsUpdatedListeners.add(listener);
- }
- public static void removeContactsListener(ContactsUpdatedListener listener) {
- contactsUpdatedListeners.remove(listener);
- }
-
- private ContactsManager(Handler handler) {
- super(handler);
- this.handler = handler;
- defaultAvatar = BitmapFactory.decodeResource(LinphoneService.instance().getResources(), R.drawable.avatar);
- androidContactsCache = new HashMap<>();
- contactsUpdatedListeners = new ArrayList<>();
- contacts = new ArrayList<>();
- sipContacts = new ArrayList<>();
- if (LinphoneManager.getLcIfManagerNotDestroyedOrNull() != null) {
- magicSearch = LinphoneManager.getLcIfManagerNotDestroyedOrNull().createMagicSearch();
- }
- }
-
- public void destroy() {
- Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- if (lc != null) {
- for (FriendList list : lc.getFriendsLists()) {
- list.setListener(null);
- }
- }
- defaultAvatar.recycle();
- instance = null;
- }
-
- public MagicSearch getMagicSearch() {
- return magicSearch;
- }
-
- public boolean contactsFetchedOnce() {
- return contacts.size() > 0;
- }
-
- public Bitmap getDefaultAvatarBitmap() {
- return defaultAvatar;
- }
-
- @Override
- public void onChange(boolean selfChange) {
- onChange(selfChange, null);
- }
-
-
- @Override
- public void onChange(boolean selfChange, Uri uri) {
- fetchContactsSync();
- }
-
- public ContentResolver getContentResolver() {
- if (contentResolver == null) {
- contentResolver = context.getContentResolver();
- }
- return contentResolver;
- }
-
- public static final ContactsManager getInstance() {
- if (instance == null) instance = new ContactsManager(LinphoneService.instance().mHandler);
- return instance;
- }
-
- public synchronized boolean hasContacts() {
- return contacts.size() > 0;
- }
-
- public synchronized List getContacts() {
- return contacts;
- }
-
- public synchronized List getSIPContacts() {
- return sipContacts;
- }
-
- public synchronized List getContacts(String search) {
- search = search.toLowerCase(Locale.getDefault());
- List searchContactsBegin = new ArrayList();
- List searchContactsContain = new ArrayList();
- for (LinphoneContact contact : contacts) {
- if (contact.getFullName() != null) {
- if (contact.getFullName().toLowerCase(Locale.getDefault()).startsWith(search)) {
- searchContactsBegin.add(contact);
- } else if (contact.getFullName().toLowerCase(Locale.getDefault()).contains(search)) {
- searchContactsContain.add(contact);
- }
- }
- }
- searchContactsBegin.addAll(searchContactsContain);
- return searchContactsBegin;
- }
-
- public synchronized List getSIPContacts(String search) {
- search = search.toLowerCase(Locale.getDefault());
- List searchContactsBegin = new ArrayList();
- List searchContactsContain = new ArrayList();
- for (LinphoneContact contact : sipContacts) {
- if (contact.getFullName() != null) {
- if (contact.getFullName().toLowerCase(Locale.getDefault()).startsWith(search)) {
- searchContactsBegin.add(contact);
- } else if (contact.getFullName().toLowerCase(Locale.getDefault()).contains(search)) {
- searchContactsContain.add(contact);
- }
- }
- }
- searchContactsBegin.addAll(searchContactsContain);
- return searchContactsBegin;
- }
-
- public void enableContactsAccess() {
- LinphonePreferences.instance().disableFriendsStorage();
- }
-
- public boolean hasContactsAccess() {
- if (context == null) {
- context = LinphoneManager.getInstance().getContext();
- }
- if (context == null) {
- return false;
- }
- boolean contactsR = (PackageManager.PERMISSION_GRANTED ==
- context.getPackageManager().checkPermission(android.Manifest.permission.READ_CONTACTS, context.getPackageName()));
- context.getPackageManager();
- return contactsR && !context.getResources().getBoolean(R.bool.force_use_of_linphone_friends);
- }
-
- public void setLinphoneContactsPrefered(boolean isPrefered) {
- preferLinphoneContacts = isPrefered;
- }
-
- public boolean isLinphoneContactsPrefered() {
- return preferLinphoneContacts;
- }
-
- public boolean isContactPresenceDisabled() {
- return isContactPresenceDisabled;
- }
-
- public void initializeContactManager(Context context, ContentResolver contentResolver) {
- this.context = context;
- this.contentResolver = contentResolver;
- }
-
- public void initializeSyncAccount(Context context, ContentResolver contentResolver) {
- initializeContactManager(context, contentResolver);
- AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
-
- Account[] accounts = accountManager.getAccountsByType(context.getPackageName());
-
- if (accounts != null && accounts.length == 0) {
- Account newAccount = new Account(context.getString(R.string.sync_account_name), context.getPackageName());
- try {
- accountManager.addAccountExplicitly(newAccount, null, null);
- } catch (Exception e) {
- Log.e(e);
- }
- }
- initializeContactManager(context, contentResolver);
- }
-
- public synchronized LinphoneContact findContactFromAddress(Address address) {
- if (address == null) return null;
- Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- Friend lf = lc.findFriend(address);
- if (lf != null) {
- LinphoneContact contact = (LinphoneContact)lf.getUserData();
- return contact;
- }
- return findContactFromPhoneNumber(address.getUsername());
- }
-
- public synchronized LinphoneContact findContactFromPhoneNumber(String phoneNumber) {
- Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- ProxyConfig lpc = null;
- if (lc != null) {
- lpc = lc.getDefaultProxyConfig();
- }
- if (lpc == null) return null;
- String normalized = lpc.normalizePhoneNumber(phoneNumber);
- if (normalized == null) normalized = phoneNumber;
-
- Address addr = lpc.normalizeSipUri(normalized);
- if (addr == null) {
- return null;
- }
- addr.setUriParam("user", "phone");
- Friend lf = lc.findFriend(addr); // Without this, the hashmap inside liblinphone won't find it...
- if (lf != null) {
- LinphoneContact contact = (LinphoneContact)lf.getUserData();
- return contact;
- }
- return null;
- }
-
- public synchronized void setContacts(List c) {
- if (contacts.isEmpty() || contacts.size() > c.size()) {
- contacts = c;
- } else {
- for (LinphoneContact contact : c) {
- if (!contacts.contains(contact)) {
- contacts.add(contact);
- }
- }
- }
- Collections.sort(contacts);
- }
-
- public synchronized void setSipContacts(List c) {
- if (sipContacts.isEmpty() || sipContacts.size() > c.size()) {
- sipContacts = c;
- } else {
- for (LinphoneContact contact : c) {
- if (!sipContacts.contains(contact)) {
- sipContacts.add(contact);
- }
- }
- }
- Collections.sort(sipContacts);
- }
-
- public synchronized void refreshSipContact(Friend lf) {
- LinphoneContact contact = (LinphoneContact)lf.getUserData();
- if (contact != null && !sipContacts.contains(contact)) {
- sipContacts.add(contact);
- }
- }
-
- public void fetchContactsAsync() {
- handler.post(new Runnable() {
- @Override
- public void run() {
- fetchContactsSync();
- }
- });
- }
-
- private synchronized void fetchContactsSync() {
- List contacts = new ArrayList<>();
- List sipContacts = new ArrayList<>();
- Date contactsTime = new Date();
- androidContactsCache.clear();
-
- Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- if (lc != null) {
- for (FriendList list : lc.getFriendsLists()) {
- for (Friend friend : list.getFriends()) {
- LinphoneContact contact = (LinphoneContact) friend.getUserData();
- if (contact != null) {
- contact.clearAddresses();
- if (contact.hasAddress()) {
- sipContacts.add(contact);
- }
- contacts.add(contact);
- if (contact.getAndroidId() != null) {
- androidContactsCache.put(contact.getAndroidId(), contact);
- }
- } else {
- if (friend.getRefKey() != null) {
- // Friend has a refkey and but no LinphoneContact => represents a native contact stored in db from a previous version of Linphone, remove it
- list.removeFriend(friend);
- } else {
- // No refkey so it's a standalone contact
- contact = new LinphoneContact();
- contact.setFriend(friend);
- contact.refresh();
- if (contact.hasAddress()) {
- sipContacts.add(contact);
- }
- contacts.add(contact);
- }
- }
- }
- }
- }
-
- long timeElapsed = (new Date()).getTime() - contactsTime.getTime();
- String time = String.format("%02d:%02d",
- TimeUnit.MILLISECONDS.toMinutes(timeElapsed),
- TimeUnit.MILLISECONDS.toSeconds(timeElapsed) -
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(timeElapsed)));
- Log.i("[ContactsManager] Step 0 for " + contacts.size() + " contacts: " + time + " elapsed since starting");
-
- if (hasContactsAccess()) {
- List nativeIds = new ArrayList();
- Cursor c = getContactsCursor();
- if (c != null) {
- while (c.moveToNext()) {
- String id = c.getString(c.getColumnIndex(Data.CONTACT_ID));
- String displayName = c.getString(c.getColumnIndex(Data.DISPLAY_NAME_PRIMARY));
-
- nativeIds.add(id);
- boolean created = false;
- LinphoneContact contact = androidContactsCache.get(id);
- if (contact == null) {
- created = true;
- contact = new LinphoneContact();
- contact.setAndroidId(id);
- }
-
- contact.setFullName(displayName);
- /*contact.getAndroidIds();*/
- if (created) {
- contacts.add(contact);
- androidContactsCache.put(id, contact);
- }
- }
- c.close();
- }
-
- boolean isOrgVisible = LinphoneManager.getInstance().getContext().getResources().getBoolean(R.bool.display_contact_organization);
- if (isOrgVisible) {
- c = getOrganizationCursor();
- if (c != null) {
- while (c.moveToNext()) {
- String id = c.getString(c.getColumnIndex(ContactsContract.Data.CONTACT_ID));
- String org = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));
- LinphoneContact contact = androidContactsCache.get(id);
- if (contact != null) {
- contact.setOrganization(org);
- }
- }
- c.close();
- }
- }
-
- for (LinphoneContact contact : androidContactsCache.values()) {
- String id = contact.getAndroidId();
- if (id != null && !nativeIds.contains(id)) {
- // Has been removed since last fetch
- for (FriendList list : lc.getFriendsLists()) {
- list.removeFriend(contact.getFriend());
- }
- contacts.remove(contact);
- }
- }
- nativeIds.clear();
-
- timeElapsed = (new Date()).getTime() - contactsTime.getTime();
- time = String.format("%02d:%02d",
- TimeUnit.MILLISECONDS.toMinutes(timeElapsed),
- TimeUnit.MILLISECONDS.toSeconds(timeElapsed) -
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(timeElapsed)));
- Log.i("[ContactsManager] Step 1 for " + contacts.size() + " contacts: " + time + " elapsed since starting");
-
- c = getPhonesCursor();
- if (c != null) {
- while (c.moveToNext()) {
- String id = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
- String number = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
- LinphoneContact contact = androidContactsCache.get(id);
- if (contact != null) {
- contact.addNumberOrAddress(new LinphoneNumberOrAddress(number, false));
- }
- }
- c.close();
- }
- c = getSipCursor();
- if (c != null) {
- while (c.moveToNext()) {
- String id = c.getString(c.getColumnIndex(ContactsContract.Data.CONTACT_ID));
- String sip = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS));
- LinphoneContact contact = androidContactsCache.get(id);
- if (contact != null) {
- contact.addNumberOrAddress(new LinphoneNumberOrAddress(sip, true));
- if (!sipContacts.contains(contact)) {
- sipContacts.add(contact);
- }
- }
- }
- c.close();
- }
-
- timeElapsed = (new Date()).getTime() - contactsTime.getTime();
- time = String.format("%02d:%02d",
- TimeUnit.MILLISECONDS.toMinutes(timeElapsed),
- TimeUnit.MILLISECONDS.toSeconds(timeElapsed) -
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(timeElapsed)));
- Log.i("[ContactsManager] Step 2 for " + contacts.size() + " contacts: " + time + " elapsed since starting");
-
- for (LinphoneContact contact : contacts) {
- // Create the Friends matching the native contacts
- contact.createOrUpdateFriendFromNativeContact();
- }
- timeElapsed = (new Date()).getTime() - contactsTime.getTime();
- time = String.format("%02d:%02d",
- TimeUnit.MILLISECONDS.toMinutes(timeElapsed),
- TimeUnit.MILLISECONDS.toSeconds(timeElapsed) -
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(timeElapsed)));
- Log.i("[ContactsManager] Step 3 for " + contacts.size() + " contacts: " + time + " elapsed since starting");
-
- androidContactsCache.clear();
- } else {
- Log.w("[Permission] Read contacts permission wasn't granted, only fetch Friends");
- }
-
- setContacts(contacts);
- setSipContacts(sipContacts);
-
- if (LinphonePreferences.instance() != null && LinphonePreferences.instance().isFriendlistsubscriptionEnabled()) {
- if (getString(R.string.rls_uri) != null) {
- LinphoneManager.getLc().getFriendsLists()[0].setRlsUri(getString(R.string.rls_uri));
- }
- LinphoneManager.getLc().getFriendsLists()[0].updateSubscriptions();
- }
- for (ContactsUpdatedListener listener : contactsUpdatedListeners) {
- listener.onContactsUpdated();
- }
- }
-
- public static String getAddressOrNumberForAndroidContact(ContentResolver resolver, Uri contactUri) {
- // Phone Numbers
- String[] projection = new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER };
- Cursor c = resolver.query(contactUri, projection, null, null, null);
- if (c != null) {
- while (c.moveToNext()) {
- int numberIndex = c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
- String number = c.getString(numberIndex);
- c.close();
- return number;
- }
- }
-
- // SIP addresses
- projection = new String[] { ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS };
- c = resolver.query(contactUri, projection, null, null, null);
- if (c != null) {
- while (c.moveToNext()) {
- int numberIndex = c.getColumnIndex(ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS);
- String address = c.getString(numberIndex);
- c.close();
- return address;
- }
- c.close();
- }
- return null;
- }
-
- public void delete(String id) {
- ArrayList ids = new ArrayList();
- ids.add(id);
- deleteMultipleContactsAtOnce(ids);
- }
-
- public void deleteMultipleContactsAtOnce(List ids) {
- String select = ContactsContract.Data.CONTACT_ID + " = ?";
- ArrayList ops = new ArrayList<>();
-
- for (String id : ids) {
- String[] args = new String[] { id };
- ops.add(ContentProviderOperation.newDelete(ContactsContract.RawContacts.CONTENT_URI).withSelection(select, args).build());
- }
-
- try {
- getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
- } catch (Exception e) {
- Log.e(e);
- }
- }
-
- public String getString(int resourceID) {
- if (context == null) return null;
- return context.getString(resourceID);
- }
-
- private Cursor getContactsCursor() {
- String req = "(" + Data.MIMETYPE + " = '" + CommonDataKinds.Phone.CONTENT_ITEM_TYPE
- + "' AND " + CommonDataKinds.Phone.NUMBER + " IS NOT NULL "
- + " OR (" + Data.MIMETYPE + " = '" + CommonDataKinds.SipAddress.CONTENT_ITEM_TYPE
- + "' AND " + CommonDataKinds.SipAddress.SIP_ADDRESS + " IS NOT NULL))";
- String[] projection = new String[] { Data.CONTACT_ID, Data.DISPLAY_NAME_PRIMARY };
- String query = Data.DISPLAY_NAME_PRIMARY + " IS NOT NULL AND (" + req + ")";
-
- Cursor cursor = getContentResolver().query(Data.CONTENT_URI, projection, query, null, " lower(" + Data.DISPLAY_NAME_PRIMARY + ") COLLATE UNICODE ASC");
- if (cursor == null) {
- return cursor;
- }
-
- MatrixCursor result = new MatrixCursor(cursor.getColumnNames());
- Set groupBy = new HashSet();
- while (cursor.moveToNext()) {
- String name = cursor.getString(cursor.getColumnIndex(Data.DISPLAY_NAME_PRIMARY));
- if (!groupBy.contains(name)) {
- groupBy.add(name);
- Object[] newRow = new Object[cursor.getColumnCount()];
-
- int contactID = cursor.getColumnIndex(Data.CONTACT_ID);
- int displayName = cursor.getColumnIndex(Data.DISPLAY_NAME_PRIMARY);
-
- newRow[contactID] = cursor.getString(contactID);
- newRow[displayName] = cursor.getString(displayName);
- result.addRow(newRow);
- }
- }
- cursor.close();
- return result;
- }
-
- private Cursor getPhonesCursor() {
- Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
- new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.CONTACT_ID },
- null, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " ASC");
- return cursor;
- }
-
- private Cursor getSipCursor() {
- String select = ContactsContract.Data.MIMETYPE + "=?";
- String[] projection = new String[] { ContactsContract.Data.CONTACT_ID, ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS };
- Cursor c = getContentResolver().query(ContactsContract.Data.CONTENT_URI, projection, select, new String[]{ ContactsContract.CommonDataKinds.SipAddress.CONTENT_ITEM_TYPE }, null);
- return c;
- }
-
- private Cursor getOrganizationCursor() {
- String select = ContactsContract.Data.MIMETYPE + "=?";
- String[] projection = new String[] { ContactsContract.Data.CONTACT_ID, ContactsContract.CommonDataKinds.Organization.COMPANY };
- Cursor c = getContentResolver().query(ContactsContract.Data.CONTENT_URI, projection, select, new String[]{ ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE }, null);
- return c;
- }
-
- @Override
- public void onContactCreated(FriendList list, Friend lf) {
-
- }
-
- @Override
- public void onContactDeleted(FriendList list, Friend lf) {
-
- }
-
- @Override
- public void onContactUpdated(FriendList list, Friend newFriend, Friend oldFriend) {
-
- }
-
- @Override
- public void onSyncStatusChanged(FriendList list, FriendList.SyncStatus status, String msg) {
-
- }
-
- @Override
- public void onPresenceReceived(FriendList list, Friend[] friends) {
- for (Friend lf : friends) {
- ContactsManager.getInstance().refreshSipContact(lf);
- }
-
- Collections.sort(sipContacts);
- for (ContactsUpdatedListener listener : contactsUpdatedListeners) {
- listener.onContactsUpdated();
- }
- }
+ private static ContactsManager instance;
+
+ private List contacts, sipContacts;
+ private MagicSearch magicSearch;
+ private boolean preferLinphoneContacts = false, isContactPresenceDisabled = true;
+ private ContentResolver contentResolver;
+ private Context context;
+ private HashMap androidContactsCache;
+ private Bitmap defaultAvatar;
+ private Handler handler;
+
+ private static ArrayList contactsUpdatedListeners;
+
+ public static void addContactsListener(ContactsUpdatedListener listener) {
+ contactsUpdatedListeners.add(listener);
+ }
+
+ public static void removeContactsListener(ContactsUpdatedListener listener) {
+ contactsUpdatedListeners.remove(listener);
+ }
+
+ private ContactsManager(Handler handler) {
+ super(handler);
+ this.handler = handler;
+ defaultAvatar = BitmapFactory.decodeResource(LinphoneService.instance().getResources(), R.drawable.avatar);
+ androidContactsCache = new HashMap<>();
+ contactsUpdatedListeners = new ArrayList<>();
+ contacts = new ArrayList<>();
+ sipContacts = new ArrayList<>();
+ if (LinphoneManager.getLcIfManagerNotDestroyedOrNull() != null) {
+ magicSearch = LinphoneManager.getLcIfManagerNotDestroyedOrNull().createMagicSearch();
+ }
+ }
+
+ public void destroy() {
+ Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ if (lc != null) {
+ for (FriendList list : lc.getFriendsLists()) {
+ list.setListener(null);
+ }
+ }
+ defaultAvatar.recycle();
+ instance = null;
+ }
+
+ public MagicSearch getMagicSearch() {
+ return magicSearch;
+ }
+
+ public boolean contactsFetchedOnce() {
+ return contacts.size() > 0;
+ }
+
+ public Bitmap getDefaultAvatarBitmap() {
+ return defaultAvatar;
+ }
+
+ @Override
+ public void onChange(boolean selfChange) {
+ onChange(selfChange, null);
+ }
+
+
+ @Override
+ public void onChange(boolean selfChange, Uri uri) {
+ fetchContactsSync();
+ }
+
+ public ContentResolver getContentResolver() {
+ if (contentResolver == null) {
+ contentResolver = context.getContentResolver();
+ }
+ return contentResolver;
+ }
+
+ public static final ContactsManager getInstance() {
+ if (instance == null) instance = new ContactsManager(LinphoneService.instance().mHandler);
+ return instance;
+ }
+
+ public synchronized boolean hasContacts() {
+ return contacts.size() > 0;
+ }
+
+ public synchronized List getContacts() {
+ return contacts;
+ }
+
+ public synchronized List getSIPContacts() {
+ return sipContacts;
+ }
+
+ public synchronized List getContacts(String search) {
+ search = search.toLowerCase(Locale.getDefault());
+ List searchContactsBegin = new ArrayList();
+ List searchContactsContain = new ArrayList();
+ for (LinphoneContact contact : contacts) {
+ if (contact.getFullName() != null) {
+ if (contact.getFullName().toLowerCase(Locale.getDefault()).startsWith(search)) {
+ searchContactsBegin.add(contact);
+ } else if (contact.getFullName().toLowerCase(Locale.getDefault()).contains(search)) {
+ searchContactsContain.add(contact);
+ }
+ }
+ }
+ searchContactsBegin.addAll(searchContactsContain);
+ return searchContactsBegin;
+ }
+
+ public synchronized List getSIPContacts(String search) {
+ search = search.toLowerCase(Locale.getDefault());
+ List searchContactsBegin = new ArrayList();
+ List searchContactsContain = new ArrayList();
+ for (LinphoneContact contact : sipContacts) {
+ if (contact.getFullName() != null) {
+ if (contact.getFullName().toLowerCase(Locale.getDefault()).startsWith(search)) {
+ searchContactsBegin.add(contact);
+ } else if (contact.getFullName().toLowerCase(Locale.getDefault()).contains(search)) {
+ searchContactsContain.add(contact);
+ }
+ }
+ }
+ searchContactsBegin.addAll(searchContactsContain);
+ return searchContactsBegin;
+ }
+
+ public void enableContactsAccess() {
+ LinphonePreferences.instance().disableFriendsStorage();
+ }
+
+ public boolean hasContactsAccess() {
+ if (context == null) {
+ context = LinphoneManager.getInstance().getContext();
+ }
+ if (context == null) {
+ return false;
+ }
+ boolean contactsR = (PackageManager.PERMISSION_GRANTED ==
+ context.getPackageManager().checkPermission(android.Manifest.permission.READ_CONTACTS, context.getPackageName()));
+ context.getPackageManager();
+ return contactsR && !context.getResources().getBoolean(R.bool.force_use_of_linphone_friends);
+ }
+
+ public void setLinphoneContactsPrefered(boolean isPrefered) {
+ preferLinphoneContacts = isPrefered;
+ }
+
+ public boolean isLinphoneContactsPrefered() {
+ return preferLinphoneContacts;
+ }
+
+ public boolean isContactPresenceDisabled() {
+ return isContactPresenceDisabled;
+ }
+
+ public void initializeContactManager(Context context, ContentResolver contentResolver) {
+ this.context = context;
+ this.contentResolver = contentResolver;
+ }
+
+ public void initializeSyncAccount(Context context, ContentResolver contentResolver) {
+ initializeContactManager(context, contentResolver);
+ AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
+
+ Account[] accounts = accountManager.getAccountsByType(context.getPackageName());
+
+ if (accounts != null && accounts.length == 0) {
+ Account newAccount = new Account(context.getString(R.string.sync_account_name), context.getPackageName());
+ try {
+ accountManager.addAccountExplicitly(newAccount, null, null);
+ } catch (Exception e) {
+ Log.e(e);
+ }
+ }
+ initializeContactManager(context, contentResolver);
+ }
+
+ public synchronized LinphoneContact findContactFromAddress(Address address) {
+ if (address == null) return null;
+ Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ Friend lf = lc.findFriend(address);
+ if (lf != null) {
+ LinphoneContact contact = (LinphoneContact) lf.getUserData();
+ return contact;
+ }
+ return findContactFromPhoneNumber(address.getUsername());
+ }
+
+ public synchronized LinphoneContact findContactFromPhoneNumber(String phoneNumber) {
+ Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ ProxyConfig lpc = null;
+ if (lc != null) {
+ lpc = lc.getDefaultProxyConfig();
+ }
+ if (lpc == null) return null;
+ String normalized = lpc.normalizePhoneNumber(phoneNumber);
+ if (normalized == null) normalized = phoneNumber;
+
+ Address addr = lpc.normalizeSipUri(normalized);
+ if (addr == null) {
+ return null;
+ }
+ addr.setUriParam("user", "phone");
+ Friend lf = lc.findFriend(addr); // Without this, the hashmap inside liblinphone won't find it...
+ if (lf != null) {
+ LinphoneContact contact = (LinphoneContact) lf.getUserData();
+ return contact;
+ }
+ return null;
+ }
+
+ public synchronized void setContacts(List c) {
+ if (contacts.isEmpty() || contacts.size() > c.size()) {
+ contacts = c;
+ } else {
+ for (LinphoneContact contact : c) {
+ if (!contacts.contains(contact)) {
+ contacts.add(contact);
+ }
+ }
+ }
+ Collections.sort(contacts);
+ }
+
+ public synchronized void setSipContacts(List c) {
+ if (sipContacts.isEmpty() || sipContacts.size() > c.size()) {
+ sipContacts = c;
+ } else {
+ for (LinphoneContact contact : c) {
+ if (!sipContacts.contains(contact)) {
+ sipContacts.add(contact);
+ }
+ }
+ }
+ Collections.sort(sipContacts);
+ }
+
+ public synchronized void refreshSipContact(Friend lf) {
+ LinphoneContact contact = (LinphoneContact) lf.getUserData();
+ if (contact != null && !sipContacts.contains(contact)) {
+ sipContacts.add(contact);
+ }
+ }
+
+ public void fetchContactsAsync() {
+ handler.post(new Runnable() {
+ @Override
+ public void run() {
+ fetchContactsSync();
+ }
+ });
+ }
+
+ private synchronized void fetchContactsSync() {
+ List contacts = new ArrayList<>();
+ List sipContacts = new ArrayList<>();
+ Date contactsTime = new Date();
+ androidContactsCache.clear();
+
+ Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ if (lc != null) {
+ for (FriendList list : lc.getFriendsLists()) {
+ for (Friend friend : list.getFriends()) {
+ LinphoneContact contact = (LinphoneContact) friend.getUserData();
+ if (contact != null) {
+ contact.clearAddresses();
+ if (contact.hasAddress()) {
+ sipContacts.add(contact);
+ }
+ contacts.add(contact);
+ if (contact.getAndroidId() != null) {
+ androidContactsCache.put(contact.getAndroidId(), contact);
+ }
+ } else {
+ if (friend.getRefKey() != null) {
+ // Friend has a refkey and but no LinphoneContact => represents a native contact stored in db from a previous version of Linphone, remove it
+ list.removeFriend(friend);
+ } else {
+ // No refkey so it's a standalone contact
+ contact = new LinphoneContact();
+ contact.setFriend(friend);
+ contact.refresh();
+ if (contact.hasAddress()) {
+ sipContacts.add(contact);
+ }
+ contacts.add(contact);
+ }
+ }
+ }
+ }
+ }
+
+ long timeElapsed = (new Date()).getTime() - contactsTime.getTime();
+ String time = String.format("%02d:%02d",
+ TimeUnit.MILLISECONDS.toMinutes(timeElapsed),
+ TimeUnit.MILLISECONDS.toSeconds(timeElapsed) -
+ TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(timeElapsed)));
+ Log.i("[ContactsManager] Step 0 for " + contacts.size() + " contacts: " + time + " elapsed since starting");
+
+ if (hasContactsAccess()) {
+ List nativeIds = new ArrayList();
+ Cursor c = getContactsCursor();
+ if (c != null) {
+ while (c.moveToNext()) {
+ String id = c.getString(c.getColumnIndex(Data.CONTACT_ID));
+ String displayName = c.getString(c.getColumnIndex(Data.DISPLAY_NAME_PRIMARY));
+
+ nativeIds.add(id);
+ boolean created = false;
+ LinphoneContact contact = androidContactsCache.get(id);
+ if (contact == null) {
+ created = true;
+ contact = new LinphoneContact();
+ contact.setAndroidId(id);
+ }
+
+ contact.setFullName(displayName);
+ /*contact.getAndroidIds();*/
+ if (created) {
+ contacts.add(contact);
+ androidContactsCache.put(id, contact);
+ }
+ }
+ c.close();
+ }
+
+ boolean isOrgVisible = LinphoneManager.getInstance().getContext().getResources().getBoolean(R.bool.display_contact_organization);
+ if (isOrgVisible) {
+ c = getOrganizationCursor();
+ if (c != null) {
+ while (c.moveToNext()) {
+ String id = c.getString(c.getColumnIndex(ContactsContract.Data.CONTACT_ID));
+ String org = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));
+ LinphoneContact contact = androidContactsCache.get(id);
+ if (contact != null) {
+ contact.setOrganization(org);
+ }
+ }
+ c.close();
+ }
+ }
+
+ for (LinphoneContact contact : androidContactsCache.values()) {
+ String id = contact.getAndroidId();
+ if (id != null && !nativeIds.contains(id)) {
+ // Has been removed since last fetch
+ for (FriendList list : lc.getFriendsLists()) {
+ list.removeFriend(contact.getFriend());
+ }
+ contacts.remove(contact);
+ }
+ }
+ nativeIds.clear();
+
+ timeElapsed = (new Date()).getTime() - contactsTime.getTime();
+ time = String.format("%02d:%02d",
+ TimeUnit.MILLISECONDS.toMinutes(timeElapsed),
+ TimeUnit.MILLISECONDS.toSeconds(timeElapsed) -
+ TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(timeElapsed)));
+ Log.i("[ContactsManager] Step 1 for " + contacts.size() + " contacts: " + time + " elapsed since starting");
+
+ c = getPhonesCursor();
+ if (c != null) {
+ while (c.moveToNext()) {
+ String id = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
+ String number = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
+ LinphoneContact contact = androidContactsCache.get(id);
+ if (contact != null) {
+ contact.addNumberOrAddress(new LinphoneNumberOrAddress(number, false));
+ }
+ }
+ c.close();
+ }
+ c = getSipCursor();
+ if (c != null) {
+ while (c.moveToNext()) {
+ String id = c.getString(c.getColumnIndex(ContactsContract.Data.CONTACT_ID));
+ String sip = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS));
+ LinphoneContact contact = androidContactsCache.get(id);
+ if (contact != null) {
+ contact.addNumberOrAddress(new LinphoneNumberOrAddress(sip, true));
+ if (!sipContacts.contains(contact)) {
+ sipContacts.add(contact);
+ }
+ }
+ }
+ c.close();
+ }
+
+ timeElapsed = (new Date()).getTime() - contactsTime.getTime();
+ time = String.format("%02d:%02d",
+ TimeUnit.MILLISECONDS.toMinutes(timeElapsed),
+ TimeUnit.MILLISECONDS.toSeconds(timeElapsed) -
+ TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(timeElapsed)));
+ Log.i("[ContactsManager] Step 2 for " + contacts.size() + " contacts: " + time + " elapsed since starting");
+
+ for (LinphoneContact contact : contacts) {
+ // Create the Friends matching the native contacts
+ contact.createOrUpdateFriendFromNativeContact();
+ }
+ timeElapsed = (new Date()).getTime() - contactsTime.getTime();
+ time = String.format("%02d:%02d",
+ TimeUnit.MILLISECONDS.toMinutes(timeElapsed),
+ TimeUnit.MILLISECONDS.toSeconds(timeElapsed) -
+ TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(timeElapsed)));
+ Log.i("[ContactsManager] Step 3 for " + contacts.size() + " contacts: " + time + " elapsed since starting");
+
+ androidContactsCache.clear();
+ } else {
+ Log.w("[Permission] Read contacts permission wasn't granted, only fetch Friends");
+ }
+
+ setContacts(contacts);
+ setSipContacts(sipContacts);
+
+ if (LinphonePreferences.instance() != null && LinphonePreferences.instance().isFriendlistsubscriptionEnabled()) {
+ if (getString(R.string.rls_uri) != null) {
+ LinphoneManager.getLc().getFriendsLists()[0].setRlsUri(getString(R.string.rls_uri));
+ }
+ LinphoneManager.getLc().getFriendsLists()[0].updateSubscriptions();
+ }
+ for (ContactsUpdatedListener listener : contactsUpdatedListeners) {
+ listener.onContactsUpdated();
+ }
+ }
+
+ public static String getAddressOrNumberForAndroidContact(ContentResolver resolver, Uri contactUri) {
+ // Phone Numbers
+ String[] projection = new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER};
+ Cursor c = resolver.query(contactUri, projection, null, null, null);
+ if (c != null) {
+ while (c.moveToNext()) {
+ int numberIndex = c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
+ String number = c.getString(numberIndex);
+ c.close();
+ return number;
+ }
+ }
+
+ // SIP addresses
+ projection = new String[]{ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS};
+ c = resolver.query(contactUri, projection, null, null, null);
+ if (c != null) {
+ while (c.moveToNext()) {
+ int numberIndex = c.getColumnIndex(ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS);
+ String address = c.getString(numberIndex);
+ c.close();
+ return address;
+ }
+ c.close();
+ }
+ return null;
+ }
+
+ public void delete(String id) {
+ ArrayList ids = new ArrayList();
+ ids.add(id);
+ deleteMultipleContactsAtOnce(ids);
+ }
+
+ public void deleteMultipleContactsAtOnce(List ids) {
+ String select = ContactsContract.Data.CONTACT_ID + " = ?";
+ ArrayList ops = new ArrayList<>();
+
+ for (String id : ids) {
+ String[] args = new String[]{id};
+ ops.add(ContentProviderOperation.newDelete(ContactsContract.RawContacts.CONTENT_URI).withSelection(select, args).build());
+ }
+
+ try {
+ getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
+ } catch (Exception e) {
+ Log.e(e);
+ }
+ }
+
+ public String getString(int resourceID) {
+ if (context == null) return null;
+ return context.getString(resourceID);
+ }
+
+ private Cursor getContactsCursor() {
+ String req = "(" + Data.MIMETYPE + " = '" + CommonDataKinds.Phone.CONTENT_ITEM_TYPE
+ + "' AND " + CommonDataKinds.Phone.NUMBER + " IS NOT NULL "
+ + " OR (" + Data.MIMETYPE + " = '" + CommonDataKinds.SipAddress.CONTENT_ITEM_TYPE
+ + "' AND " + CommonDataKinds.SipAddress.SIP_ADDRESS + " IS NOT NULL))";
+ String[] projection = new String[]{Data.CONTACT_ID, Data.DISPLAY_NAME_PRIMARY};
+ String query = Data.DISPLAY_NAME_PRIMARY + " IS NOT NULL AND (" + req + ")";
+
+ Cursor cursor = getContentResolver().query(Data.CONTENT_URI, projection, query, null, " lower(" + Data.DISPLAY_NAME_PRIMARY + ") COLLATE UNICODE ASC");
+ if (cursor == null) {
+ return cursor;
+ }
+
+ MatrixCursor result = new MatrixCursor(cursor.getColumnNames());
+ Set groupBy = new HashSet();
+ while (cursor.moveToNext()) {
+ String name = cursor.getString(cursor.getColumnIndex(Data.DISPLAY_NAME_PRIMARY));
+ if (!groupBy.contains(name)) {
+ groupBy.add(name);
+ Object[] newRow = new Object[cursor.getColumnCount()];
+
+ int contactID = cursor.getColumnIndex(Data.CONTACT_ID);
+ int displayName = cursor.getColumnIndex(Data.DISPLAY_NAME_PRIMARY);
+
+ newRow[contactID] = cursor.getString(contactID);
+ newRow[displayName] = cursor.getString(displayName);
+ result.addRow(newRow);
+ }
+ }
+ cursor.close();
+ return result;
+ }
+
+ private Cursor getPhonesCursor() {
+ Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
+ new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.CONTACT_ID},
+ null, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " ASC");
+ return cursor;
+ }
+
+ private Cursor getSipCursor() {
+ String select = ContactsContract.Data.MIMETYPE + "=?";
+ String[] projection = new String[]{ContactsContract.Data.CONTACT_ID, ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS};
+ Cursor c = getContentResolver().query(ContactsContract.Data.CONTENT_URI, projection, select, new String[]{ContactsContract.CommonDataKinds.SipAddress.CONTENT_ITEM_TYPE}, null);
+ return c;
+ }
+
+ private Cursor getOrganizationCursor() {
+ String select = ContactsContract.Data.MIMETYPE + "=?";
+ String[] projection = new String[]{ContactsContract.Data.CONTACT_ID, ContactsContract.CommonDataKinds.Organization.COMPANY};
+ Cursor c = getContentResolver().query(ContactsContract.Data.CONTENT_URI, projection, select, new String[]{ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE}, null);
+ return c;
+ }
+
+ @Override
+ public void onContactCreated(FriendList list, Friend lf) {
+
+ }
+
+ @Override
+ public void onContactDeleted(FriendList list, Friend lf) {
+
+ }
+
+ @Override
+ public void onContactUpdated(FriendList list, Friend newFriend, Friend oldFriend) {
+
+ }
+
+ @Override
+ public void onSyncStatusChanged(FriendList list, FriendList.SyncStatus status, String msg) {
+
+ }
+
+ @Override
+ public void onPresenceReceived(FriendList list, Friend[] friends) {
+ for (Friend lf : friends) {
+ ContactsManager.getInstance().refreshSipContact(lf);
+ }
+
+ Collections.sort(sipContacts);
+ for (ContactsUpdatedListener listener : contactsUpdatedListeners) {
+ listener.onContactsUpdated();
+ }
+ }
}
diff --git a/src/android/org/linphone/contacts/LinphoneContact.java b/src/android/org/linphone/contacts/LinphoneContact.java
index 9c175c05c..4cf76cc83 100644
--- a/src/android/org/linphone/contacts/LinphoneContact.java
+++ b/src/android/org/linphone/contacts/LinphoneContact.java
@@ -19,23 +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.io.Serializable;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Locale;
-
-import org.linphone.LinphoneManager;
-import org.linphone.R;
-import org.linphone.core.Address;
-import org.linphone.core.Core;
-import org.linphone.core.Friend;
-import org.linphone.core.SubscribePolicy;
-import org.linphone.core.FriendList;
-import org.linphone.core.PresenceBasicStatus;
-import org.linphone.core.PresenceModel;
-import org.linphone.mediastream.Log;
-
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.ContentUris;
@@ -45,731 +28,748 @@ import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds;
+import org.linphone.LinphoneManager;
+import org.linphone.R;
+import org.linphone.core.Address;
+import org.linphone.core.Core;
+import org.linphone.core.Friend;
+import org.linphone.core.FriendList;
+import org.linphone.core.PresenceBasicStatus;
+import org.linphone.core.PresenceModel;
+import org.linphone.core.SubscribePolicy;
+import org.linphone.mediastream.Log;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Locale;
+
public class LinphoneContact implements Serializable, Comparable {
- private static final long serialVersionUID = 9015568163905205244L;
-
- private transient Friend friend;
- private String fullName, firstName, lastName, androidId, androidRawId, androidTagId, organization;
- private transient Uri photoUri, thumbnailUri;
- private List addresses;
- private transient ArrayList changesToCommit;
- private transient ArrayList changesToCommit2;
- private boolean hasSipAddress;
-
- public LinphoneContact() {
- addresses = new ArrayList<>();
- androidId = null;
- thumbnailUri = null;
- photoUri = null;
- changesToCommit = new ArrayList<>();
- changesToCommit2 = new ArrayList<>();
- hasSipAddress = false;
- }
-
- @Override
- public int compareTo(LinphoneContact contact) {
- String fullName = getFullName() != null ? getFullName().toUpperCase(Locale.getDefault()) : "";
- String contactFullName = contact.getFullName() != null ? contact.getFullName().toUpperCase(Locale.getDefault()) : "";
- return fullName.compareTo(contactFullName);
- }
-
- @Override
- public boolean equals(Object obj) {
- if (obj.getClass() != LinphoneContact.class) return false;
- LinphoneContact contact = (LinphoneContact) obj;
- return (this.compareTo(contact) == 0);
- }
-
- public void setFullName(String name) {
- fullName = name;
- }
-
- public String getFullName() {
- return fullName;
- }
-
- public void setFirstNameAndLastName(String fn, String ln) {
- if (fn != null && fn.length() == 0 && ln != null && ln.length() == 0) return;
-
- if (isAndroidContact()) {
- if (firstName != null || lastName != null) {
- String select = ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "='" + ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE + "'";
- String[] args = new String[]{ getAndroidId() };
-
- changesToCommit.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
- .withSelection(select, args)
- .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
- .withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, fn)
- .withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, ln)
- .build()
- );
- } else {
- changesToCommit.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
- .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
- .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
- .withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, fn)
- .withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, ln)
- .build());
- }
- }
-
- firstName = fn;
- lastName = ln;
- if (firstName != null && lastName != null && firstName.length() > 0 && lastName.length() > 0) {
- fullName = firstName + " " + lastName;
- } else if (firstName != null && firstName.length() > 0) {
- fullName = firstName;
- } else if (lastName != null && lastName.length() > 0) {
- fullName = lastName;
- }
- }
-
- public String getFirstName() {
- return firstName;
- }
-
- public String getLastName() {
- return lastName;
- }
-
- public String getOrganization() {
- return organization;
- }
-
- public void setOrganization(String org) {
- if (isAndroidContact()) {
- if (androidRawId != null) {
- String select = ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "='" + ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE + "'";
- String[] args = new String[]{ getAndroidId() };
-
- if (organization != null) {
- changesToCommit.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
- .withSelection(select, args)
- .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
- .withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, org)
- .build());
- } else {
- changesToCommit.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
- .withValue(ContactsContract.Data.RAW_CONTACT_ID, androidRawId)
- .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
- .withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, org)
- .build());
- }
- } else {
- changesToCommit.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
- .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
- .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
- .withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, org)
- .build());
- }
- }
-
- organization = org;
- }
-
- public boolean hasPhoto() {
- return photoUri != null;
- }
-
- public void setPhotoUri(Uri uri) {
- if (uri.equals(photoUri)) return;
- photoUri = uri;
- }
-
- public Uri getPhotoUri() {
- return photoUri;
- }
-
- public void setThumbnailUri(Uri uri) {
- if (uri.equals(thumbnailUri)) return;
- thumbnailUri = uri;
- }
-
- public Uri getThumbnailUri() {
- return thumbnailUri;
- }
-
- public void setPhoto(byte[] photo) {
- if (photo != null) {
- if (isAndroidContact()) {
- if (androidRawId != null) {
- changesToCommit.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
- .withValue(ContactsContract.Data.RAW_CONTACT_ID, androidRawId)
- .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
- .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, photo)
- .withValue(ContactsContract.Data.IS_PRIMARY, 1)
- .withValue(ContactsContract.Data.IS_SUPER_PRIMARY, 1)
- .build());
- } else {
- changesToCommit.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
- .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
- .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
- .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, photo)
- .build());
- }
- }
- }
- }
-
- public void addNumberOrAddress(LinphoneNumberOrAddress noa) {
- if (noa == null) return;
- if (noa.isSIPAddress()) {
- hasSipAddress = true;
- }
- addresses.add(noa);
- }
-
- public List getNumbersOrAddresses() {
- return addresses;
- }
-
- public boolean hasAddress(String address) {
- for (LinphoneNumberOrAddress noa : getNumbersOrAddresses()) {
- if (noa.isSIPAddress()) {
- String value = noa.getValue();
- if (address.startsWith(value) || value.equals("sip:" + address)) { // Startswith is to workaround the fact the address may have a ;gruu= at the end...
- return true;
- }
- }
- }
- return false;
- }
-
- public boolean hasAddress() {
- return hasSipAddress;
- }
-
- public void removeNumberOrAddress(LinphoneNumberOrAddress noa) {
- if (noa != null && noa.getOldValue() != null) {
- if (isAndroidContact()) {
- String select;
- if (noa.isSIPAddress()) {
- select = ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "='" + ContactsContract.CommonDataKinds.SipAddress.CONTENT_ITEM_TYPE + "' AND " + ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS + "=?";
- } else {
- select = ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "='" + ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "' AND " + ContactsContract.CommonDataKinds.Phone.NUMBER + "=?";
- }
- String[] args = new String[]{ getAndroidId(), noa.getOldValue() };
-
- changesToCommit.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
- .withSelection(select, args)
- .build());
-
- if (androidTagId != null && noa.isSIPAddress()) {
- select = ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.DATA1 + "=?";
- args = new String[] { androidTagId, noa.getOldValue() };
-
- changesToCommit.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
- .withSelection(select, args)
- .build());
- }
- }
-
- if (isFriend()) {
- if (noa.isSIPAddress()) {
- if (!noa.getOldValue().startsWith("sip:")) {
- noa.setOldValue("sip:" + noa.getOldValue());
- }
- }
- LinphoneNumberOrAddress toRemove = null;
- for (LinphoneNumberOrAddress address : addresses) {
- if (noa.getOldValue().equals(address.getValue()) && noa.isSIPAddress() == address.isSIPAddress()) {
- toRemove = address;
- break;
- }
- }
- if (toRemove != null) {
- addresses.remove(toRemove);
- }
- }
- }
- }
-
- public void addOrUpdateNumberOrAddress(LinphoneNumberOrAddress noa) {
- if (noa != null && noa.getValue() != null) {
- if (isAndroidContact()) {
- if (noa.getOldValue() == null) {
- ContentValues values = new ContentValues();
- if (noa.isSIPAddress()) {
- values.put(ContactsContract.Data.MIMETYPE, CommonDataKinds.SipAddress.CONTENT_ITEM_TYPE);
- values.put(ContactsContract.CommonDataKinds.SipAddress.DATA, noa.getValue());
- values.put(CommonDataKinds.SipAddress.TYPE, CommonDataKinds.SipAddress.TYPE_CUSTOM);
- values.put(CommonDataKinds.SipAddress.LABEL, ContactsManager.getInstance().getString(R.string.addressbook_label));
- } else {
- values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
- values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, noa.getValue());
- values.put(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM);
- values.put(ContactsContract.CommonDataKinds.Phone.LABEL, ContactsManager.getInstance().getString(R.string.addressbook_label));
- }
- if (androidRawId != null) {
- changesToCommit.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
- .withValue(ContactsContract.Data.RAW_CONTACT_ID, androidRawId)
- .withValues(values)
- .build());
- } else {
- changesToCommit.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
- .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
- .withValues(values)
- .build());
- }
-
- if (noa.isSIPAddress() && LinphoneManager.getInstance().getContext().getResources().getBoolean(R.bool.use_linphone_tag)) {
- if (androidTagId != null) {
- changesToCommit.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
- .withValue(ContactsContract.Data.RAW_CONTACT_ID, androidTagId)
- .withValue(ContactsContract.Data.MIMETYPE, ContactsManager.getInstance().getString(R.string.sync_mimetype))
- .withValue(ContactsContract.Data.DATA1, noa.getValue())
- .withValue(ContactsContract.Data.DATA2, ContactsManager.getInstance().getString(R.string.app_name))
- .withValue(ContactsContract.Data.DATA3, noa.getValue())
- .build());
- } else {
- changesToCommit2.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
- .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
- .withValue(ContactsContract.Data.MIMETYPE, ContactsManager.getInstance().getString(R.string.sync_mimetype))
- .withValue(ContactsContract.Data.DATA1, noa.getValue())
- .withValue(ContactsContract.Data.DATA2, ContactsManager.getInstance().getString(R.string.app_name))
- .withValue(ContactsContract.Data.DATA3, noa.getValue())
- .build());
- }
- }
- } else {
- ContentValues values = new ContentValues();
- String select;
- String[] args = new String[] { getAndroidId(), noa.getOldValue() };
-
- if (noa.isSIPAddress()) {
- select = ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "='" + ContactsContract.CommonDataKinds.SipAddress.CONTENT_ITEM_TYPE + "' AND " + ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS + "=?";
- values.put(ContactsContract.Data.MIMETYPE, CommonDataKinds.SipAddress.CONTENT_ITEM_TYPE);
- values.put(ContactsContract.CommonDataKinds.SipAddress.DATA, noa.getValue());
- } else {
- select = ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "='" + ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "' AND " + ContactsContract.CommonDataKinds.Phone.NUMBER + "=?";
- values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
- values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, noa.getValue());
- }
- changesToCommit.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
- .withSelection(select, args)
- .withValues(values)
- .build());
-
- if (noa.isSIPAddress() && LinphoneManager.getInstance().getContext().getResources().getBoolean(R.bool.use_linphone_tag)) {
- if (androidTagId != null) {
- changesToCommit.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
- .withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.DATA1 + "=? ", new String[] { androidTagId, noa.getOldValue() })
- .withValue(ContactsContract.Data.DATA1, noa.getValue())
- .withValue(ContactsContract.Data.DATA2, ContactsManager.getInstance().getString(R.string.app_name))
- .withValue(ContactsContract.Data.DATA3, noa.getValue())
- .build());
- } else {
- changesToCommit2.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
- .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
- .withValue(ContactsContract.Data.MIMETYPE, ContactsManager.getInstance().getString(R.string.sync_mimetype))
- .withValue(ContactsContract.Data.DATA1, noa.getValue())
- .withValue(ContactsContract.Data.DATA2, ContactsManager.getInstance().getString(R.string.app_name))
- .withValue(ContactsContract.Data.DATA3, noa.getValue())
- .build());
- }
- }
- }
- }
- if (isFriend()) {
- if (noa.isSIPAddress()) {
- if (!noa.getValue().startsWith("sip:")) {
- noa.setValue("sip:" + noa.getValue());
- }
- }
- if (noa.getOldValue() != null) {
- if (noa.isSIPAddress()) {
- if (!noa.getOldValue().startsWith("sip:")) {
- noa.setOldValue("sip:" + noa.getOldValue());
- }
- }
- for (LinphoneNumberOrAddress address : addresses) {
- if (noa.getOldValue().equals(address.getValue()) && noa.isSIPAddress() == address.isSIPAddress()) {
- address.setValue(noa.getValue());
- break;
- }
- }
- } else {
- addresses.add(noa);
- }
- }
- }
- }
-
- public void setAndroidId(String id) {
- androidId = id;
- setThumbnailUri(getContactThumbnailPictureUri());
- setPhotoUri(getContactPictureUri());
- }
-
- public String getAndroidId() {
- return androidId;
- }
-
- public Friend getFriend() {
- return friend;
- }
-
- private void createOrUpdateFriend() {
- boolean created = false;
- Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- if (lc == null) return;
-
- if (!isFriend()) {
- friend = lc.createFriend();
- friend.enableSubscribes(false);
- friend.setIncSubscribePolicy(SubscribePolicy.SPDeny);
- if (isAndroidContact()) {
- friend.setRefKey(getAndroidId());
- }
- friend.setUserData(this);
- created = true;
- }
- if (isFriend()) {
- friend.edit();
- friend.setName(fullName);
- friend.getVcard().setFamilyName(lastName);
- friend.getVcard().setGivenName(firstName);
- if (organization != null) {
- friend.getVcard().setOrganization(organization);
- }
-
- if (!created) {
- for (Address address : friend.getAddresses()) {
- friend.removeAddress(address);
- }
- for (String phone : friend.getPhoneNumbers()) {
- friend.removePhoneNumber(phone);
- }
- }
- for (LinphoneNumberOrAddress noa : addresses) {
- if (noa.isSIPAddress()) {
- Address addr = lc.interpretUrl(noa.getValue());
- if (addr != null) {
- friend.addAddress(addr);
- }
- } else {
- friend.addPhoneNumber(noa.getValue());
- }
- }
- friend.done();
- }
- if (created) {
- lc.addFriend(friend);
- }
-
- if (!ContactsManager.getInstance().hasContactsAccess()) {
- // This refresh is only needed if app has no contacts permission to refresh the list of Friends.
- // Otherwise contacts will be refreshed due to changes in native contact and the handler in ContactsManager
- ContactsManager.getInstance().fetchContactsAsync();
- }
- }
-
- public void save() {
- if (isAndroidContact() && ContactsManager.getInstance().hasContactsAccess() && changesToCommit.size() > 0) {
- try {
- ContactsManager.getInstance().getContentResolver().applyBatch(ContactsContract.AUTHORITY, changesToCommit);
- createLinphoneTagIfNeeded();
- } catch (Exception e) {
- Log.e(e);
- } finally {
- changesToCommit = new ArrayList<>();
- changesToCommit2 = new ArrayList<>();
- }
- }
-
- createOrUpdateFriend();
- }
-
- public void delete() {
- if (isAndroidContact()) {
- String select = ContactsContract.Data.CONTACT_ID + " = ?";
- String[] args = new String[] { getAndroidId() };
- changesToCommit.add(ContentProviderOperation.newDelete(ContactsContract.RawContacts.CONTENT_URI).withSelection(select, args).build());
- save();
- ContactsManager.getInstance().delete(getAndroidId());
- }
- if (isFriend()) {
- deleteFriend();
- }
- }
-
- public void deleteFriend() {
- Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- if (friend != null && lc != null) {
- for (FriendList list : lc.getFriendsLists()) {
- list.removeFriend(friend);
- }
- }
- }
-
- public void clearAddresses() {
- addresses.clear();
- }
-
- public void refresh() {
- addresses = new ArrayList<>();
- if (isAndroidContact()) {
- getContactNames();
- getNativeContactOrganization();
- getAndroidIds();
- hasSipAddress = false;
- for (LinphoneNumberOrAddress noa : getAddressesAndNumbersForAndroidContact()) {
- addNumberOrAddress(noa);
- }
- } else if (isFriend()) {
- fullName = friend.getName();
- lastName = friend.getVcard().getFamilyName();
- firstName = friend.getVcard().getGivenName();
- thumbnailUri = null;
- photoUri = null;
- hasSipAddress = friend.getAddress() != null;
- organization = friend.getVcard().getOrganization();
-
- Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
- if (lc != null && lc.vcardSupported()) {
- for (Address addr : friend.getAddresses()) {
- if (addr != null) {
- addNumberOrAddress(new LinphoneNumberOrAddress(addr.asStringUriOnly(), true));
- }
- }
- for (String tel : friend.getPhoneNumbers()) {
- if (tel != null) {
- addNumberOrAddress(new LinphoneNumberOrAddress(tel, false));
- }
- }
- } else {
- Address addr = friend.getAddress();
- addNumberOrAddress(new LinphoneNumberOrAddress(addr.asStringUriOnly(), true));
- }
- }
- }
-
- public void createOrUpdateFriendFromNativeContact() {
- if (isAndroidContact()) {
- createOrUpdateFriend();
- }
- }
-
- public boolean isAndroidContact() {
- return androidId != null;
- }
-
- public boolean isFriend() {
- return friend != null;
- }
-
- public boolean isInFriendList() {
- if (friend == null) return false;
- for (LinphoneNumberOrAddress noa : addresses) {
- PresenceModel pm = friend.getPresenceModelForUriOrTel(noa.getValue());
- if (pm != null && pm.getBasicStatus().equals(PresenceBasicStatus.Open)) {
- return true;
- }
- }
- return false;
- }
-
- public String getPresenceModelForUriOrTel(String uri) {
- if (friend != null && friend.getPresenceModelForUriOrTel(uri) != null) {
- return friend.getPresenceModelForUriOrTel(uri).getContact();
- }
- return null;
- }
-
- public void setFriend(Friend f) {
- friend = f;
- friend.setUserData(this);
- }
-
- public void getAndroidIds() {
- androidRawId = findRawContactID();
- if (LinphoneManager.getInstance().getContext().getResources().getBoolean(R.bool.use_linphone_tag)) {
- androidTagId = findLinphoneRawContactId();
- }
- }
-
- public static LinphoneContact createContact() {
- if (ContactsManager.getInstance().hasContactsAccess()) {
- return createAndroidContact();
- }
- return createFriend();
- }
-
- private Uri getContactThumbnailPictureUri() {
- Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(getAndroidId()));
- return Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
- }
-
- private Uri getContactPictureUri() {
- Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(getAndroidId()));
- return Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.DISPLAY_PHOTO);
- }
-
- private void getContactNames() {
- ContentResolver resolver = ContactsManager.getInstance().getContentResolver();
- String[] proj = new String[]{ ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME };
- String select = ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?";
- String[] args = new String[]{ getAndroidId(), ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE };
- Cursor c = resolver.query(ContactsContract.Data.CONTENT_URI, proj, select, args, null);
- if (c != null) {
- if (c.moveToFirst()) {
- firstName = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
- lastName = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
- }
- c.close();
- }
- }
-
- private void getNativeContactOrganization() {
- ContentResolver resolver = ContactsManager.getInstance().getContentResolver();
- String[] proj = new String[]{ ContactsContract.CommonDataKinds.Organization.COMPANY };
- String select = ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?";
- String[] args = new String[]{ getAndroidId(), ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE };
- Cursor c = resolver.query(ContactsContract.Data.CONTENT_URI, proj, select, args, null);
- if (c != null) {
- if (c.moveToFirst()) {
- organization = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));
- }
- c.close();
- }
- }
-
- private String findRawContactID() {
- ContentResolver resolver = ContactsManager.getInstance().getContentResolver();
- String result = null;
- String[] projection = { ContactsContract.RawContacts._ID };
-
- String selection = ContactsContract.RawContacts.CONTACT_ID + "=?";
- Cursor c = resolver.query(ContactsContract.RawContacts.CONTENT_URI, projection, selection, new String[]{ getAndroidId() }, null);
- if (c != null) {
- if (c.moveToFirst()) {
- result = c.getString(c.getColumnIndex(ContactsContract.RawContacts._ID));
- }
- c.close();
- }
- return result;
- }
-
- private List getAddressesAndNumbersForAndroidContact() {
- List result = new ArrayList();
- ContentResolver resolver = ContactsManager.getInstance().getContentResolver();
-
- String select = ContactsContract.Data.CONTACT_ID + " =? AND (" + ContactsContract.Data.MIMETYPE + "=? OR " + ContactsContract.Data.MIMETYPE + "=?)";
- String[] projection = new String[] { ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS, ContactsContract.Data.MIMETYPE }; // PHONE_NUMBER == SIP_ADDRESS == "data1"...
- Cursor c = resolver.query(ContactsContract.Data.CONTENT_URI, projection, select, new String[]{ getAndroidId(), ContactsContract.CommonDataKinds.SipAddress.CONTENT_ITEM_TYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE }, null);
- if (c != null) {
- while (c.moveToNext()) {
- String mime = c.getString(c.getColumnIndex(ContactsContract.Data.MIMETYPE));
- if (mime != null && mime.length() > 0) {
- boolean found = false;
- boolean isSIP = false;
- if (mime.equals(ContactsContract.CommonDataKinds.SipAddress.CONTENT_ITEM_TYPE)) {
- found = true;
- isSIP = true;
- } else if (mime.equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)) {
- found = true;
- }
-
- if (found) {
- String number = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS)); // PHONE_NUMBER == SIP_ADDRESS == "data1"...
- if (number != null && number.length() > 0) {
- if (isSIP && !number.startsWith("sip:")) {
- number = "sip:" + number;
- }
- if (isSIP && !number.contains("@")) {
- number = number + "@" + ContactsManager.getInstance().getString(R.string.default_domain);
- }
- result.add(new LinphoneNumberOrAddress(number, isSIP));
- }
- }
- }
- }
- c.close();
- }
- Collections.sort(result);
- return result;
- }
-
- private static LinphoneContact createAndroidContact() {
- LinphoneContact contact = new LinphoneContact();
-
- contact.changesToCommit.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
- .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
- .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
- .withValue(ContactsContract.RawContacts.AGGREGATION_MODE, ContactsContract.RawContacts.AGGREGATION_MODE_DEFAULT)
- .build());
- contact.setAndroidId("0");
-
- return contact;
- }
-
- private static LinphoneContact createFriend() {
- LinphoneContact contact = new LinphoneContact();
- Friend friend = LinphoneManager.getLc().createFriend();
- // Disable subscribes for now
- friend.enableSubscribes(false);
- friend.setIncSubscribePolicy(SubscribePolicy.SPDeny);
- contact.friend = friend;
- friend.setUserData(contact);
- return contact;
- }
-
- private String findLinphoneRawContactId() {
- ContentResolver resolver = ContactsManager.getInstance().getContentResolver();
- String result = null;
- String[] projection = { ContactsContract.RawContacts._ID };
-
- String selection = ContactsContract.RawContacts.CONTACT_ID + "=? AND " + ContactsContract.RawContacts.ACCOUNT_TYPE + "=?";
- Cursor c = resolver.query(ContactsContract.RawContacts.CONTENT_URI, projection, selection, new String[] { getAndroidId(), ContactsManager.getInstance().getString(R.string.sync_account_type) }, null);
- if (c != null) {
- if (c.moveToFirst()) {
- result = c.getString(c.getColumnIndex(ContactsContract.RawContacts._ID));
- }
- c.close();
- }
- return result;
- }
-
- private void createLinphoneTagIfNeeded() {
- if (LinphoneManager.getInstance().getContext().getResources().getBoolean(R.bool.use_linphone_tag)) {
- if (androidTagId == null && findLinphoneRawContactId() == null) {
- createLinphoneContactTag();
- }
- }
- }
-
- private void createLinphoneContactTag() {
- ArrayList batch = new ArrayList<>();
-
- batch.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
- .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, ContactsManager.getInstance().getString(R.string.sync_account_type))
- .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, ContactsManager.getInstance().getString(R.string.sync_account_name))
- .withValue(ContactsContract.RawContacts.AGGREGATION_MODE, ContactsContract.RawContacts.AGGREGATION_MODE_DEFAULT)
- .build());
-
- batch.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
- .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
- .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
- .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, getFullName())
- .build());
-
- batch.add(ContentProviderOperation.newUpdate(ContactsContract.AggregationExceptions.CONTENT_URI)
- .withValue(ContactsContract.AggregationExceptions.TYPE, ContactsContract.AggregationExceptions.TYPE_KEEP_TOGETHER)
- .withValue(ContactsContract.AggregationExceptions.RAW_CONTACT_ID1, androidRawId)
- .withValueBackReference(ContactsContract.AggregationExceptions.RAW_CONTACT_ID2, 0)
- .build());
-
- if (changesToCommit2.size() > 0) {
- for(ContentProviderOperation cpo : changesToCommit2) {
- batch.add(cpo);
- }
- }
-
- try {
- ContactsManager.getInstance().getContentResolver().applyBatch(ContactsContract.AUTHORITY, batch);
- androidTagId = findLinphoneRawContactId();
- } catch (Exception e) {
- Log.e(e);
- }
- }
+ private static final long serialVersionUID = 9015568163905205244L;
+
+ private transient Friend friend;
+ private String fullName, firstName, lastName, androidId, androidRawId, androidTagId, organization;
+ private transient Uri photoUri, thumbnailUri;
+ private List addresses;
+ private transient ArrayList changesToCommit;
+ private transient ArrayList changesToCommit2;
+ private boolean hasSipAddress;
+
+ public LinphoneContact() {
+ addresses = new ArrayList<>();
+ androidId = null;
+ thumbnailUri = null;
+ photoUri = null;
+ changesToCommit = new ArrayList<>();
+ changesToCommit2 = new ArrayList<>();
+ hasSipAddress = false;
+ }
+
+ @Override
+ public int compareTo(LinphoneContact contact) {
+ String fullName = getFullName() != null ? getFullName().toUpperCase(Locale.getDefault()) : "";
+ String contactFullName = contact.getFullName() != null ? contact.getFullName().toUpperCase(Locale.getDefault()) : "";
+ return fullName.compareTo(contactFullName);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (obj.getClass() != LinphoneContact.class) return false;
+ LinphoneContact contact = (LinphoneContact) obj;
+ return (this.compareTo(contact) == 0);
+ }
+
+ public void setFullName(String name) {
+ fullName = name;
+ }
+
+ public String getFullName() {
+ return fullName;
+ }
+
+ public void setFirstNameAndLastName(String fn, String ln) {
+ if (fn != null && fn.length() == 0 && ln != null && ln.length() == 0) return;
+
+ if (isAndroidContact()) {
+ if (firstName != null || lastName != null) {
+ String select = ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "='" + ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE + "'";
+ String[] args = new String[]{getAndroidId()};
+
+ changesToCommit.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
+ .withSelection(select, args)
+ .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
+ .withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, fn)
+ .withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, ln)
+ .build()
+ );
+ } else {
+ changesToCommit.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
+ .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
+ .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
+ .withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, fn)
+ .withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, ln)
+ .build());
+ }
+ }
+
+ firstName = fn;
+ lastName = ln;
+ if (firstName != null && lastName != null && firstName.length() > 0 && lastName.length() > 0) {
+ fullName = firstName + " " + lastName;
+ } else if (firstName != null && firstName.length() > 0) {
+ fullName = firstName;
+ } else if (lastName != null && lastName.length() > 0) {
+ fullName = lastName;
+ }
+ }
+
+ public String getFirstName() {
+ return firstName;
+ }
+
+ public String getLastName() {
+ return lastName;
+ }
+
+ public String getOrganization() {
+ return organization;
+ }
+
+ public void setOrganization(String org) {
+ if (isAndroidContact()) {
+ if (androidRawId != null) {
+ String select = ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "='" + ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE + "'";
+ String[] args = new String[]{getAndroidId()};
+
+ if (organization != null) {
+ changesToCommit.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
+ .withSelection(select, args)
+ .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
+ .withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, org)
+ .build());
+ } else {
+ changesToCommit.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
+ .withValue(ContactsContract.Data.RAW_CONTACT_ID, androidRawId)
+ .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
+ .withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, org)
+ .build());
+ }
+ } else {
+ changesToCommit.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
+ .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
+ .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
+ .withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, org)
+ .build());
+ }
+ }
+
+ organization = org;
+ }
+
+ public boolean hasPhoto() {
+ return photoUri != null;
+ }
+
+ public void setPhotoUri(Uri uri) {
+ if (uri.equals(photoUri)) return;
+ photoUri = uri;
+ }
+
+ public Uri getPhotoUri() {
+ return photoUri;
+ }
+
+ public void setThumbnailUri(Uri uri) {
+ if (uri.equals(thumbnailUri)) return;
+ thumbnailUri = uri;
+ }
+
+ public Uri getThumbnailUri() {
+ return thumbnailUri;
+ }
+
+ public void setPhoto(byte[] photo) {
+ if (photo != null) {
+ if (isAndroidContact()) {
+ if (androidRawId != null) {
+ changesToCommit.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
+ .withValue(ContactsContract.Data.RAW_CONTACT_ID, androidRawId)
+ .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
+ .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, photo)
+ .withValue(ContactsContract.Data.IS_PRIMARY, 1)
+ .withValue(ContactsContract.Data.IS_SUPER_PRIMARY, 1)
+ .build());
+ } else {
+ changesToCommit.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
+ .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
+ .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
+ .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, photo)
+ .build());
+ }
+ }
+ }
+ }
+
+ public void addNumberOrAddress(LinphoneNumberOrAddress noa) {
+ if (noa == null) return;
+ if (noa.isSIPAddress()) {
+ hasSipAddress = true;
+ }
+ addresses.add(noa);
+ }
+
+ public List getNumbersOrAddresses() {
+ return addresses;
+ }
+
+ public boolean hasAddress(String address) {
+ for (LinphoneNumberOrAddress noa : getNumbersOrAddresses()) {
+ if (noa.isSIPAddress()) {
+ String value = noa.getValue();
+ if (address.startsWith(value) || value.equals("sip:" + address)) { // Startswith is to workaround the fact the address may have a ;gruu= at the end...
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ public boolean hasAddress() {
+ return hasSipAddress;
+ }
+
+ public void removeNumberOrAddress(LinphoneNumberOrAddress noa) {
+ if (noa != null && noa.getOldValue() != null) {
+ if (isAndroidContact()) {
+ String select;
+ if (noa.isSIPAddress()) {
+ select = ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "='" + ContactsContract.CommonDataKinds.SipAddress.CONTENT_ITEM_TYPE + "' AND " + ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS + "=?";
+ } else {
+ select = ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "='" + ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "' AND " + ContactsContract.CommonDataKinds.Phone.NUMBER + "=?";
+ }
+ String[] args = new String[]{getAndroidId(), noa.getOldValue()};
+
+ changesToCommit.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
+ .withSelection(select, args)
+ .build());
+
+ if (androidTagId != null && noa.isSIPAddress()) {
+ select = ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.DATA1 + "=?";
+ args = new String[]{androidTagId, noa.getOldValue()};
+
+ changesToCommit.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
+ .withSelection(select, args)
+ .build());
+ }
+ }
+
+ if (isFriend()) {
+ if (noa.isSIPAddress()) {
+ if (!noa.getOldValue().startsWith("sip:")) {
+ noa.setOldValue("sip:" + noa.getOldValue());
+ }
+ }
+ LinphoneNumberOrAddress toRemove = null;
+ for (LinphoneNumberOrAddress address : addresses) {
+ if (noa.getOldValue().equals(address.getValue()) && noa.isSIPAddress() == address.isSIPAddress()) {
+ toRemove = address;
+ break;
+ }
+ }
+ if (toRemove != null) {
+ addresses.remove(toRemove);
+ }
+ }
+ }
+ }
+
+ public void addOrUpdateNumberOrAddress(LinphoneNumberOrAddress noa) {
+ if (noa != null && noa.getValue() != null) {
+ if (isAndroidContact()) {
+ if (noa.getOldValue() == null) {
+ ContentValues values = new ContentValues();
+ if (noa.isSIPAddress()) {
+ values.put(ContactsContract.Data.MIMETYPE, CommonDataKinds.SipAddress.CONTENT_ITEM_TYPE);
+ values.put(ContactsContract.CommonDataKinds.SipAddress.DATA, noa.getValue());
+ values.put(CommonDataKinds.SipAddress.TYPE, CommonDataKinds.SipAddress.TYPE_CUSTOM);
+ values.put(CommonDataKinds.SipAddress.LABEL, ContactsManager.getInstance().getString(R.string.addressbook_label));
+ } else {
+ values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
+ values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, noa.getValue());
+ values.put(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM);
+ values.put(ContactsContract.CommonDataKinds.Phone.LABEL, ContactsManager.getInstance().getString(R.string.addressbook_label));
+ }
+ if (androidRawId != null) {
+ changesToCommit.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
+ .withValue(ContactsContract.Data.RAW_CONTACT_ID, androidRawId)
+ .withValues(values)
+ .build());
+ } else {
+ changesToCommit.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
+ .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
+ .withValues(values)
+ .build());
+ }
+
+ if (noa.isSIPAddress() && LinphoneManager.getInstance().getContext().getResources().getBoolean(R.bool.use_linphone_tag)) {
+ if (androidTagId != null) {
+ changesToCommit.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
+ .withValue(ContactsContract.Data.RAW_CONTACT_ID, androidTagId)
+ .withValue(ContactsContract.Data.MIMETYPE, ContactsManager.getInstance().getString(R.string.sync_mimetype))
+ .withValue(ContactsContract.Data.DATA1, noa.getValue())
+ .withValue(ContactsContract.Data.DATA2, ContactsManager.getInstance().getString(R.string.app_name))
+ .withValue(ContactsContract.Data.DATA3, noa.getValue())
+ .build());
+ } else {
+ changesToCommit2.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
+ .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
+ .withValue(ContactsContract.Data.MIMETYPE, ContactsManager.getInstance().getString(R.string.sync_mimetype))
+ .withValue(ContactsContract.Data.DATA1, noa.getValue())
+ .withValue(ContactsContract.Data.DATA2, ContactsManager.getInstance().getString(R.string.app_name))
+ .withValue(ContactsContract.Data.DATA3, noa.getValue())
+ .build());
+ }
+ }
+ } else {
+ ContentValues values = new ContentValues();
+ String select;
+ String[] args = new String[]{getAndroidId(), noa.getOldValue()};
+
+ if (noa.isSIPAddress()) {
+ select = ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "='" + ContactsContract.CommonDataKinds.SipAddress.CONTENT_ITEM_TYPE + "' AND " + ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS + "=?";
+ values.put(ContactsContract.Data.MIMETYPE, CommonDataKinds.SipAddress.CONTENT_ITEM_TYPE);
+ values.put(ContactsContract.CommonDataKinds.SipAddress.DATA, noa.getValue());
+ } else {
+ select = ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "='" + ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "' AND " + ContactsContract.CommonDataKinds.Phone.NUMBER + "=?";
+ values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
+ values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, noa.getValue());
+ }
+ changesToCommit.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
+ .withSelection(select, args)
+ .withValues(values)
+ .build());
+
+ if (noa.isSIPAddress() && LinphoneManager.getInstance().getContext().getResources().getBoolean(R.bool.use_linphone_tag)) {
+ if (androidTagId != null) {
+ changesToCommit.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
+ .withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.DATA1 + "=? ", new String[]{androidTagId, noa.getOldValue()})
+ .withValue(ContactsContract.Data.DATA1, noa.getValue())
+ .withValue(ContactsContract.Data.DATA2, ContactsManager.getInstance().getString(R.string.app_name))
+ .withValue(ContactsContract.Data.DATA3, noa.getValue())
+ .build());
+ } else {
+ changesToCommit2.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
+ .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
+ .withValue(ContactsContract.Data.MIMETYPE, ContactsManager.getInstance().getString(R.string.sync_mimetype))
+ .withValue(ContactsContract.Data.DATA1, noa.getValue())
+ .withValue(ContactsContract.Data.DATA2, ContactsManager.getInstance().getString(R.string.app_name))
+ .withValue(ContactsContract.Data.DATA3, noa.getValue())
+ .build());
+ }
+ }
+ }
+ }
+ if (isFriend()) {
+ if (noa.isSIPAddress()) {
+ if (!noa.getValue().startsWith("sip:")) {
+ noa.setValue("sip:" + noa.getValue());
+ }
+ }
+ if (noa.getOldValue() != null) {
+ if (noa.isSIPAddress()) {
+ if (!noa.getOldValue().startsWith("sip:")) {
+ noa.setOldValue("sip:" + noa.getOldValue());
+ }
+ }
+ for (LinphoneNumberOrAddress address : addresses) {
+ if (noa.getOldValue().equals(address.getValue()) && noa.isSIPAddress() == address.isSIPAddress()) {
+ address.setValue(noa.getValue());
+ break;
+ }
+ }
+ } else {
+ addresses.add(noa);
+ }
+ }
+ }
+ }
+
+ public void setAndroidId(String id) {
+ androidId = id;
+ setThumbnailUri(getContactThumbnailPictureUri());
+ setPhotoUri(getContactPictureUri());
+ }
+
+ public String getAndroidId() {
+ return androidId;
+ }
+
+ public Friend getFriend() {
+ return friend;
+ }
+
+ private void createOrUpdateFriend() {
+ boolean created = false;
+ Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ if (lc == null) return;
+
+ if (!isFriend()) {
+ friend = lc.createFriend();
+ friend.enableSubscribes(false);
+ friend.setIncSubscribePolicy(SubscribePolicy.SPDeny);
+ if (isAndroidContact()) {
+ friend.setRefKey(getAndroidId());
+ }
+ friend.setUserData(this);
+ created = true;
+ }
+ if (isFriend()) {
+ friend.edit();
+ friend.setName(fullName);
+ friend.getVcard().setFamilyName(lastName);
+ friend.getVcard().setGivenName(firstName);
+ if (organization != null) {
+ friend.getVcard().setOrganization(organization);
+ }
+
+ if (!created) {
+ for (Address address : friend.getAddresses()) {
+ friend.removeAddress(address);
+ }
+ for (String phone : friend.getPhoneNumbers()) {
+ friend.removePhoneNumber(phone);
+ }
+ }
+ for (LinphoneNumberOrAddress noa : addresses) {
+ if (noa.isSIPAddress()) {
+ Address addr = lc.interpretUrl(noa.getValue());
+ if (addr != null) {
+ friend.addAddress(addr);
+ }
+ } else {
+ friend.addPhoneNumber(noa.getValue());
+ }
+ }
+ friend.done();
+ }
+ if (created) {
+ lc.addFriend(friend);
+ }
+
+ if (!ContactsManager.getInstance().hasContactsAccess()) {
+ // This refresh is only needed if app has no contacts permission to refresh the list of Friends.
+ // Otherwise contacts will be refreshed due to changes in native contact and the handler in ContactsManager
+ ContactsManager.getInstance().fetchContactsAsync();
+ }
+ }
+
+ public void save() {
+ if (isAndroidContact() && ContactsManager.getInstance().hasContactsAccess() && changesToCommit.size() > 0) {
+ try {
+ ContactsManager.getInstance().getContentResolver().applyBatch(ContactsContract.AUTHORITY, changesToCommit);
+ createLinphoneTagIfNeeded();
+ } catch (Exception e) {
+ Log.e(e);
+ } finally {
+ changesToCommit = new ArrayList<>();
+ changesToCommit2 = new ArrayList<>();
+ }
+ }
+
+ createOrUpdateFriend();
+ }
+
+ public void delete() {
+ if (isAndroidContact()) {
+ String select = ContactsContract.Data.CONTACT_ID + " = ?";
+ String[] args = new String[]{getAndroidId()};
+ changesToCommit.add(ContentProviderOperation.newDelete(ContactsContract.RawContacts.CONTENT_URI).withSelection(select, args).build());
+ save();
+ ContactsManager.getInstance().delete(getAndroidId());
+ }
+ if (isFriend()) {
+ deleteFriend();
+ }
+ }
+
+ public void deleteFriend() {
+ Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ if (friend != null && lc != null) {
+ for (FriendList list : lc.getFriendsLists()) {
+ list.removeFriend(friend);
+ }
+ }
+ }
+
+ public void clearAddresses() {
+ addresses.clear();
+ }
+
+ public void refresh() {
+ addresses = new ArrayList<>();
+ if (isAndroidContact()) {
+ getContactNames();
+ getNativeContactOrganization();
+ getAndroidIds();
+ hasSipAddress = false;
+ for (LinphoneNumberOrAddress noa : getAddressesAndNumbersForAndroidContact()) {
+ addNumberOrAddress(noa);
+ }
+ } else if (isFriend()) {
+ fullName = friend.getName();
+ lastName = friend.getVcard().getFamilyName();
+ firstName = friend.getVcard().getGivenName();
+ thumbnailUri = null;
+ photoUri = null;
+ hasSipAddress = friend.getAddress() != null;
+ organization = friend.getVcard().getOrganization();
+
+ Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
+ if (lc != null && lc.vcardSupported()) {
+ for (Address addr : friend.getAddresses()) {
+ if (addr != null) {
+ addNumberOrAddress(new LinphoneNumberOrAddress(addr.asStringUriOnly(), true));
+ }
+ }
+ for (String tel : friend.getPhoneNumbers()) {
+ if (tel != null) {
+ addNumberOrAddress(new LinphoneNumberOrAddress(tel, false));
+ }
+ }
+ } else {
+ Address addr = friend.getAddress();
+ addNumberOrAddress(new LinphoneNumberOrAddress(addr.asStringUriOnly(), true));
+ }
+ }
+ }
+
+ public void createOrUpdateFriendFromNativeContact() {
+ if (isAndroidContact()) {
+ createOrUpdateFriend();
+ }
+ }
+
+ public boolean isAndroidContact() {
+ return androidId != null;
+ }
+
+ public boolean isFriend() {
+ return friend != null;
+ }
+
+ public boolean isInFriendList() {
+ if (friend == null) return false;
+ for (LinphoneNumberOrAddress noa : addresses) {
+ PresenceModel pm = friend.getPresenceModelForUriOrTel(noa.getValue());
+ if (pm != null && pm.getBasicStatus().equals(PresenceBasicStatus.Open)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public String getPresenceModelForUriOrTel(String uri) {
+ if (friend != null && friend.getPresenceModelForUriOrTel(uri) != null) {
+ return friend.getPresenceModelForUriOrTel(uri).getContact();
+ }
+ return null;
+ }
+
+ public void setFriend(Friend f) {
+ friend = f;
+ friend.setUserData(this);
+ }
+
+ public void getAndroidIds() {
+ androidRawId = findRawContactID();
+ if (LinphoneManager.getInstance().getContext().getResources().getBoolean(R.bool.use_linphone_tag)) {
+ androidTagId = findLinphoneRawContactId();
+ }
+ }
+
+ public static LinphoneContact createContact() {
+ if (ContactsManager.getInstance().hasContactsAccess()) {
+ return createAndroidContact();
+ }
+ return createFriend();
+ }
+
+ private Uri getContactThumbnailPictureUri() {
+ Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(getAndroidId()));
+ return Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
+ }
+
+ private Uri getContactPictureUri() {
+ Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(getAndroidId()));
+ return Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.DISPLAY_PHOTO);
+ }
+
+ private void getContactNames() {
+ ContentResolver resolver = ContactsManager.getInstance().getContentResolver();
+ String[] proj = new String[]{ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME};
+ String select = ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?";
+ String[] args = new String[]{getAndroidId(), ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE};
+ Cursor c = resolver.query(ContactsContract.Data.CONTENT_URI, proj, select, args, null);
+ if (c != null) {
+ if (c.moveToFirst()) {
+ firstName = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
+ lastName = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
+ }
+ c.close();
+ }
+ }
+
+ private void getNativeContactOrganization() {
+ ContentResolver resolver = ContactsManager.getInstance().getContentResolver();
+ String[] proj = new String[]{ContactsContract.CommonDataKinds.Organization.COMPANY};
+ String select = ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?";
+ String[] args = new String[]{getAndroidId(), ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
+ Cursor c = resolver.query(ContactsContract.Data.CONTENT_URI, proj, select, args, null);
+ if (c != null) {
+ if (c.moveToFirst()) {
+ organization = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));
+ }
+ c.close();
+ }
+ }
+
+ private String findRawContactID() {
+ ContentResolver resolver = ContactsManager.getInstance().getContentResolver();
+ String result = null;
+ String[] projection = {ContactsContract.RawContacts._ID};
+
+ String selection = ContactsContract.RawContacts.CONTACT_ID + "=?";
+ Cursor c = resolver.query(ContactsContract.RawContacts.CONTENT_URI, projection, selection, new String[]{getAndroidId()}, null);
+ if (c != null) {
+ if (c.moveToFirst()) {
+ result = c.getString(c.getColumnIndex(ContactsContract.RawContacts._ID));
+ }
+ c.close();
+ }
+ return result;
+ }
+
+ private List getAddressesAndNumbersForAndroidContact() {
+ List result = new ArrayList();
+ ContentResolver resolver = ContactsManager.getInstance().getContentResolver();
+
+ String select = ContactsContract.Data.CONTACT_ID + " =? AND (" + ContactsContract.Data.MIMETYPE + "=? OR " + ContactsContract.Data.MIMETYPE + "=?)";
+ String[] projection = new String[]{ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS, ContactsContract.Data.MIMETYPE}; // PHONE_NUMBER == SIP_ADDRESS == "data1"...
+ Cursor c = resolver.query(ContactsContract.Data.CONTENT_URI, projection, select, new String[]{getAndroidId(), ContactsContract.CommonDataKinds.SipAddress.CONTENT_ITEM_TYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE}, null);
+ if (c != null) {
+ while (c.moveToNext()) {
+ String mime = c.getString(c.getColumnIndex(ContactsContract.Data.MIMETYPE));
+ if (mime != null && mime.length() > 0) {
+ boolean found = false;
+ boolean isSIP = false;
+ if (mime.equals(ContactsContract.CommonDataKinds.SipAddress.CONTENT_ITEM_TYPE)) {
+ found = true;
+ isSIP = true;
+ } else if (mime.equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)) {
+ found = true;
+ }
+
+ if (found) {
+ String number = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS)); // PHONE_NUMBER == SIP_ADDRESS == "data1"...
+ if (number != null && number.length() > 0) {
+ if (isSIP && !number.startsWith("sip:")) {
+ number = "sip:" + number;
+ }
+ if (isSIP && !number.contains("@")) {
+ number = number + "@" + ContactsManager.getInstance().getString(R.string.default_domain);
+ }
+ result.add(new LinphoneNumberOrAddress(number, isSIP));
+ }
+ }
+ }
+ }
+ c.close();
+ }
+ Collections.sort(result);
+ return result;
+ }
+
+ private static LinphoneContact createAndroidContact() {
+ LinphoneContact contact = new LinphoneContact();
+
+ contact.changesToCommit.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
+ .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
+ .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
+ .withValue(ContactsContract.RawContacts.AGGREGATION_MODE, ContactsContract.RawContacts.AGGREGATION_MODE_DEFAULT)
+ .build());
+ contact.setAndroidId("0");
+
+ return contact;
+ }
+
+ private static LinphoneContact createFriend() {
+ LinphoneContact contact = new LinphoneContact();
+ Friend friend = LinphoneManager.getLc().createFriend();
+ // Disable subscribes for now
+ friend.enableSubscribes(false);
+ friend.setIncSubscribePolicy(SubscribePolicy.SPDeny);
+ contact.friend = friend;
+ friend.setUserData(contact);
+ return contact;
+ }
+
+ private String findLinphoneRawContactId() {
+ ContentResolver resolver = ContactsManager.getInstance().getContentResolver();
+ String result = null;
+ String[] projection = {ContactsContract.RawContacts._ID};
+
+ String selection = ContactsContract.RawContacts.CONTACT_ID + "=? AND " + ContactsContract.RawContacts.ACCOUNT_TYPE + "=?";
+ Cursor c = resolver.query(ContactsContract.RawContacts.CONTENT_URI, projection, selection, new String[]{getAndroidId(), ContactsManager.getInstance().getString(R.string.sync_account_type)}, null);
+ if (c != null) {
+ if (c.moveToFirst()) {
+ result = c.getString(c.getColumnIndex(ContactsContract.RawContacts._ID));
+ }
+ c.close();
+ }
+ return result;
+ }
+
+ private void createLinphoneTagIfNeeded() {
+ if (LinphoneManager.getInstance().getContext().getResources().getBoolean(R.bool.use_linphone_tag)) {
+ if (androidTagId == null && findLinphoneRawContactId() == null) {
+ createLinphoneContactTag();
+ }
+ }
+ }
+
+ private void createLinphoneContactTag() {
+ ArrayList batch = new ArrayList<>();
+
+ batch.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
+ .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, ContactsManager.getInstance().getString(R.string.sync_account_type))
+ .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, ContactsManager.getInstance().getString(R.string.sync_account_name))
+ .withValue(ContactsContract.RawContacts.AGGREGATION_MODE, ContactsContract.RawContacts.AGGREGATION_MODE_DEFAULT)
+ .build());
+
+ batch.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
+ .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
+ .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
+ .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, getFullName())
+ .build());
+
+ batch.add(ContentProviderOperation.newUpdate(ContactsContract.AggregationExceptions.CONTENT_URI)
+ .withValue(ContactsContract.AggregationExceptions.TYPE, ContactsContract.AggregationExceptions.TYPE_KEEP_TOGETHER)
+ .withValue(ContactsContract.AggregationExceptions.RAW_CONTACT_ID1, androidRawId)
+ .withValueBackReference(ContactsContract.AggregationExceptions.RAW_CONTACT_ID2, 0)
+ .build());
+
+ if (changesToCommit2.size() > 0) {
+ for (ContentProviderOperation cpo : changesToCommit2) {
+ batch.add(cpo);
+ }
+ }
+
+ try {
+ ContactsManager.getInstance().getContentResolver().applyBatch(ContactsContract.AUTHORITY, batch);
+ androidTagId = findLinphoneRawContactId();
+ } catch (Exception e) {
+ Log.e(e);
+ }
+ }
}
diff --git a/src/android/org/linphone/contacts/LinphoneNumberOrAddress.java b/src/android/org/linphone/contacts/LinphoneNumberOrAddress.java
index 7a65c0fc5..2de664e16 100644
--- a/src/android/org/linphone/contacts/LinphoneNumberOrAddress.java
+++ b/src/android/org/linphone/contacts/LinphoneNumberOrAddress.java
@@ -22,56 +22,56 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import java.io.Serializable;
public class LinphoneNumberOrAddress implements Serializable, Comparable {
- private static final long serialVersionUID = -2301689469730072896L;
+ private static final long serialVersionUID = -2301689469730072896L;
- private boolean isSIPAddress;
- private String value, oldValueForUpdatePurpose;
+ private boolean isSIPAddress;
+ private String value, oldValueForUpdatePurpose;
- public LinphoneNumberOrAddress(String v, boolean isSIP) {
- value = v;
- isSIPAddress = isSIP;
- oldValueForUpdatePurpose = null;
- }
+ public LinphoneNumberOrAddress(String v, boolean isSIP) {
+ value = v;
+ isSIPAddress = isSIP;
+ oldValueForUpdatePurpose = null;
+ }
- public LinphoneNumberOrAddress(String v, boolean isSip, String old) {
- this(v, isSip);
- oldValueForUpdatePurpose = old;
- }
+ public LinphoneNumberOrAddress(String v, boolean isSip, String old) {
+ this(v, isSip);
+ oldValueForUpdatePurpose = old;
+ }
- @Override
- public int compareTo(LinphoneNumberOrAddress noa) {
- String value = noa.getValue();
- if (noa.isSIPAddress() == isSIPAddress() && value != null) {
- return value.compareTo(getValue());
- } else {
- return isSIPAddress() ? -1 : 1;
- }
- }
+ @Override
+ public int compareTo(LinphoneNumberOrAddress noa) {
+ String value = noa.getValue();
+ if (noa.isSIPAddress() == isSIPAddress() && value != null) {
+ return value.compareTo(getValue());
+ } else {
+ return isSIPAddress() ? -1 : 1;
+ }
+ }
- @Override
- public boolean equals(Object obj) {
- if (obj.getClass() != LinphoneNumberOrAddress.class) return false;
- LinphoneNumberOrAddress noa = (LinphoneNumberOrAddress) obj;
- return (this != null && this.compareTo(noa) == 0);
- }
+ @Override
+ public boolean equals(Object obj) {
+ if (obj.getClass() != LinphoneNumberOrAddress.class) return false;
+ LinphoneNumberOrAddress noa = (LinphoneNumberOrAddress) obj;
+ return (this != null && this.compareTo(noa) == 0);
+ }
- public boolean isSIPAddress() {
- return isSIPAddress;
- }
+ public boolean isSIPAddress() {
+ return isSIPAddress;
+ }
- public String getOldValue() {
- return oldValueForUpdatePurpose;
- }
+ public String getOldValue() {
+ return oldValueForUpdatePurpose;
+ }
- public void setOldValue(String v) {
- oldValueForUpdatePurpose = v;
- }
+ public void setOldValue(String v) {
+ oldValueForUpdatePurpose = v;
+ }
- public String getValue() {
- return value;
- }
+ public String getValue() {
+ return value;
+ }
- public void setValue(String v) {
- value = v;
- }
+ public void setValue(String v) {
+ value = v;
+ }
}
diff --git a/src/android/org/linphone/contacts/SearchContactsListAdapter.java b/src/android/org/linphone/contacts/SearchContactsListAdapter.java
index a6954ca46..f2608bbaf 100644
--- a/src/android/org/linphone/contacts/SearchContactsListAdapter.java
+++ b/src/android/org/linphone/contacts/SearchContactsListAdapter.java
@@ -41,249 +41,250 @@ import java.util.ArrayList;
import java.util.List;
public class SearchContactsListAdapter extends RecyclerView.Adapter {
- @SuppressWarnings("unused")
- private static final String TAG = SearchContactsListAdapter.class.getSimpleName();
+ @SuppressWarnings("unused")
+ private static final String TAG = SearchContactsListAdapter.class.getSimpleName();
- public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
- public TextView name;
- public TextView address;
- public ImageView linphoneContact;
- public ImageView isSelect;
- public ImageView avatar;
+ public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
+ public TextView name;
+ public TextView address;
+ public ImageView linphoneContact;
+ public ImageView isSelect;
+ public ImageView avatar;
- private ClickListener mListener;
+ private ClickListener mListener;
- public ViewHolder(View view, ClickListener listener) {
- super(view);
- name = view.findViewById(R.id.contact_name);
- address = view.findViewById(R.id.contact_address);
- linphoneContact = view.findViewById(R.id.contact_linphone);
- isSelect = view.findViewById(R.id.contact_is_select);
- avatar = view.findViewById(R.id.contact_picture);
- mListener = listener;
- view.setOnClickListener(this);
- }
+ public ViewHolder(View view, ClickListener listener) {
+ super(view);
+ name = view.findViewById(R.id.contact_name);
+ address = view.findViewById(R.id.contact_address);
+ linphoneContact = view.findViewById(R.id.contact_linphone);
+ isSelect = view.findViewById(R.id.contact_is_select);
+ avatar = view.findViewById(R.id.contact_picture);
+ mListener = listener;
+ view.setOnClickListener(this);
+ }
- @Override
- public void onClick(View view) {
- if (mListener != null) {
- mListener.onItemClicked(getAdapterPosition());
- }
+ @Override
+ public void onClick(View view) {
+ if (mListener != null) {
+ mListener.onItemClicked(getAdapterPosition());
+ }
- }
- public interface ClickListener {
- void onItemClicked(int position);
- }
- }
+ }
- private List contacts;
- private List contactsSelected;
- private ProgressBar progressBar;
- private boolean mOnlySipContact = false;
- private ViewHolder.ClickListener mListener;
+ public interface ClickListener {
+ void onItemClicked(int position);
+ }
+ }
- public List getContacts() {
- return contacts;
- }
+ private List contacts;
+ private List contactsSelected;
+ private ProgressBar progressBar;
+ private boolean mOnlySipContact = false;
+ private ViewHolder.ClickListener mListener;
- public void setOnlySipContact(boolean enable) {
- mOnlySipContact = enable;
- }
+ public List getContacts() {
+ return contacts;
+ }
- public void setListener(ViewHolder.ClickListener listener) {
- mListener = listener;
- }
+ public void setOnlySipContact(boolean enable) {
+ mOnlySipContact = enable;
+ }
- public SearchContactsListAdapter(List contactsList, ProgressBar pB, ViewHolder.ClickListener clickListener) {
- mListener = clickListener;
- progressBar = pB;
- setContactsSelectedList(null);
- setContactsList(contactsList);
- }
+ public void setListener(ViewHolder.ClickListener listener) {
+ mListener = listener;
+ }
- @NonNull
- @Override
- public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
- View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.search_contact_cell, parent, false);
- return new ViewHolder(v, mListener);
- }
+ public SearchContactsListAdapter(List contactsList, ProgressBar pB, ViewHolder.ClickListener clickListener) {
+ mListener = clickListener;
+ progressBar = pB;
+ setContactsSelectedList(null);
+ setContactsList(contactsList);
+ }
- @Override
- public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
- ContactAddress contact = getItem(position);
- final String a = (contact.getAddressAsDisplayableString().isEmpty()) ? contact.getPhoneNumber() : contact.getAddressAsDisplayableString();
- LinphoneContact c = contact.getContact();
+ @NonNull
+ @Override
+ public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
+ View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.search_contact_cell, parent, false);
+ return new ViewHolder(v, mListener);
+ }
- holder.avatar.setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap());
- if (c != null && c.hasPhoto()) {
- LinphoneUtils.setThumbnailPictureFromUri(LinphoneActivity.instance(), holder.avatar, c.getThumbnailUri());
- }
+ @Override
+ public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
+ ContactAddress contact = getItem(position);
+ final String a = (contact.getAddressAsDisplayableString().isEmpty()) ? contact.getPhoneNumber() : contact.getAddressAsDisplayableString();
+ LinphoneContact c = contact.getContact();
- String address = contact.getAddressAsDisplayableString();
- if (c != null && c.getFullName() != null) {
- if (address == null)
- address = c.getPresenceModelForUriOrTel(a);
- holder.name.setVisibility(View.VISIBLE);
- holder.name.setText(c.getFullName());
- } else if (contact.getAddress() != null) {
- if (contact.getAddress().getUsername() != null) {
- holder.name.setVisibility(View.VISIBLE);
- holder.name.setText(contact.getAddress().getUsername());
- } else if (contact.getAddress().getDisplayName() != null) {
- holder.name.setVisibility(View.VISIBLE);
- holder.name.setText(contact.getAddress().getDisplayName());
- }
- } else if (address != null) {
- Address tmpAddr = Factory.instance().createAddress(address);
- holder.name.setVisibility(View.VISIBLE);
- holder.name.setText((tmpAddr.getDisplayName() != null) ? tmpAddr.getDisplayName() : tmpAddr.getUsername()) ;
- } else {
- holder.name.setVisibility(View.GONE);
- }
- holder.address.setText(a);
- if (holder.linphoneContact != null) {
- if (contact.isLinphoneContact() && c != null && c.isInFriendList() && address != null) {
- holder.linphoneContact.setVisibility(View.VISIBLE);
- } else {
- holder.linphoneContact.setVisibility(View.GONE);
- }
- }
- if (holder.isSelect != null) {
- if (contactIsSelected(contact)) {
- holder.isSelect.setVisibility(View.VISIBLE);
- } else {
- holder.isSelect.setVisibility(View.INVISIBLE);
- }
- }
- }
+ holder.avatar.setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap());
+ if (c != null && c.hasPhoto()) {
+ LinphoneUtils.setThumbnailPictureFromUri(LinphoneActivity.instance(), holder.avatar, c.getThumbnailUri());
+ }
- public long getItemId(int position) {
- return position;
- }
+ String address = contact.getAddressAsDisplayableString();
+ if (c != null && c.getFullName() != null) {
+ if (address == null)
+ address = c.getPresenceModelForUriOrTel(a);
+ holder.name.setVisibility(View.VISIBLE);
+ holder.name.setText(c.getFullName());
+ } else if (contact.getAddress() != null) {
+ if (contact.getAddress().getUsername() != null) {
+ holder.name.setVisibility(View.VISIBLE);
+ holder.name.setText(contact.getAddress().getUsername());
+ } else if (contact.getAddress().getDisplayName() != null) {
+ holder.name.setVisibility(View.VISIBLE);
+ holder.name.setText(contact.getAddress().getDisplayName());
+ }
+ } else if (address != null) {
+ Address tmpAddr = Factory.instance().createAddress(address);
+ holder.name.setVisibility(View.VISIBLE);
+ holder.name.setText((tmpAddr.getDisplayName() != null) ? tmpAddr.getDisplayName() : tmpAddr.getUsername());
+ } else {
+ holder.name.setVisibility(View.GONE);
+ }
+ holder.address.setText(a);
+ if (holder.linphoneContact != null) {
+ if (contact.isLinphoneContact() && c != null && c.isInFriendList() && address != null) {
+ holder.linphoneContact.setVisibility(View.VISIBLE);
+ } else {
+ holder.linphoneContact.setVisibility(View.GONE);
+ }
+ }
+ if (holder.isSelect != null) {
+ if (contactIsSelected(contact)) {
+ holder.isSelect.setVisibility(View.VISIBLE);
+ } else {
+ holder.isSelect.setVisibility(View.INVISIBLE);
+ }
+ }
+ }
- private boolean contactIsSelected(ContactAddress ca) {
- for (ContactAddress c : contactsSelected) {
- Address addr = c.getAddress();
- if (addr.getUsername() != null && ca.getAddress() != null) {
- if (addr.asStringUriOnly().compareTo(ca.getAddress().asStringUriOnly()) == 0) return true;
- } else {
- if (c.getPhoneNumber() != null && ca.getPhoneNumber() != null) {
- if (c.getPhoneNumber().compareTo(ca.getPhoneNumber()) == 0) return true;
- }
- }
- }
- return false;
- }
+ public long getItemId(int position) {
+ return position;
+ }
- public void setContactsList(List contactsList) {
- if (contactsList == null) {
- contacts = getContactsList();
- if (contacts.size() > 0 && progressBar != null)
- progressBar.setVisibility(View.GONE);
- } else {
- contacts = contactsList;
- }
- }
+ private boolean contactIsSelected(ContactAddress ca) {
+ for (ContactAddress c : contactsSelected) {
+ Address addr = c.getAddress();
+ if (addr.getUsername() != null && ca.getAddress() != null) {
+ if (addr.asStringUriOnly().compareTo(ca.getAddress().asStringUriOnly()) == 0)
+ return true;
+ } else {
+ if (c.getPhoneNumber() != null && ca.getPhoneNumber() != null) {
+ if (c.getPhoneNumber().compareTo(ca.getPhoneNumber()) == 0) return true;
+ }
+ }
+ }
+ return false;
+ }
- public void setContactsSelectedList(List contactsList) {
- if (contactsList == null) {
- contactsSelected = new ArrayList<>();
- } else {
- contactsSelected = contactsList;
- }
- }
+ public void setContactsList(List