Code cleaning & code improvements reported by android studio

This commit is contained in:
Sylvain Berfini 2018-12-05 13:35:05 +01:00
parent 9300877d12
commit 3802deee19
133 changed files with 994 additions and 2412 deletions

View file

@ -1,15 +1,15 @@
apply plugin: 'com.android.application' apply plugin: 'com.android.application'
def getPackageName() { static def getPackageName() {
return "org.linphone" return "org.linphone"
} }
def firebaseEnabled() { static def firebaseEnabled() {
File googleFile = new File('app/google-services.json') File googleFile = new File('app/google-services.json')
return googleFile.exists() return googleFile.exists()
} }
def isLocalAarAvailable() { static def isLocalAarAvailable() {
File debugAar = new File('linphone-sdk-android/linphone-sdk-android-debug.aar') File debugAar = new File('linphone-sdk-android/linphone-sdk-android-debug.aar')
File releaseAar = new File('linphone-sdk-android/linphone-sdk-android-release.aar') File releaseAar = new File('linphone-sdk-android/linphone-sdk-android-release.aar')
return debugAar.exists() || releaseAar.exists() return debugAar.exists() || releaseAar.exists()
@ -103,9 +103,9 @@ android {
} }
dependencies { dependencies {
implementation 'com.google.firebase:firebase-messaging:15.0.2' implementation 'com.google.firebase:firebase-messaging:17.3.4'
implementation 'com.android.billingclient:billing:1.2' implementation 'com.android.billingclient:billing:1.2'
implementation 'org.apache.commons:commons-compress:1.16.1' implementation 'org.apache.commons:commons-compress:1.18'
implementation 'androidx.legacy:legacy-support-v4:1.0.0' implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'androidx.recyclerview:recyclerview:1.0.0' implementation 'androidx.recyclerview:recyclerview:1.0.0'
implementation 'androidx.appcompat:appcompat:1.0.2' implementation 'androidx.appcompat:appcompat:1.0.2'

View file

@ -232,7 +232,7 @@
</receiver> </receiver>
<receiver <receiver
android:name=".receivers.BluetoothManager" android:name=".receivers.BluetoothManager"
android:enabled="false"></receiver> android:enabled="false"/>
<receiver android:name=".receivers.BootReceiver"> <receiver android:name=".receivers.BootReceiver">
<intent-filter> <intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" /> <action android:name="android.intent.action.BOOT_COMPLETED" />

View file

@ -85,8 +85,7 @@ import org.linphone.compatibility.Compatibility;
import org.linphone.contacts.ContactAddress; import org.linphone.contacts.ContactAddress;
import org.linphone.contacts.ContactDetailsFragment; import org.linphone.contacts.ContactDetailsFragment;
import org.linphone.contacts.ContactEditorFragment; import org.linphone.contacts.ContactEditorFragment;
import org.linphone.contacts.ContactPicked; import org.linphone.contacts.ContactsFragment;
import org.linphone.contacts.ContactsListFragment;
import org.linphone.contacts.ContactsManager; import org.linphone.contacts.ContactsManager;
import org.linphone.contacts.LinphoneContact; import org.linphone.contacts.LinphoneContact;
import org.linphone.core.Address; import org.linphone.core.Address;
@ -122,9 +121,7 @@ import org.linphone.xmlrpc.XmlRpcHelper;
import org.linphone.xmlrpc.XmlRpcListenerBase; import org.linphone.xmlrpc.XmlRpcListenerBase;
public class LinphoneActivity extends LinphoneGenericActivity public class LinphoneActivity extends LinphoneGenericActivity
implements OnClickListener, implements OnClickListener, ActivityCompat.OnRequestPermissionsResultCallback {
ContactPicked,
ActivityCompat.OnRequestPermissionsResultCallback {
private static final int SETTINGS_ACTIVITY = 123; private static final int SETTINGS_ACTIVITY = 123;
private static final int CALL_ACTIVITY = 19; private static final int CALL_ACTIVITY = 19;
private static final int PERMISSIONS_REQUEST_OVERLAY = 206; private static final int PERMISSIONS_REQUEST_OVERLAY = 206;
@ -146,7 +143,6 @@ public class LinphoneActivity extends LinphoneGenericActivity
private ImageView mCancel; private ImageView mCancel;
private FragmentsAvailable mPendingFragmentTransaction, mCurrentFragment, mLeftFragment; private FragmentsAvailable mPendingFragmentTransaction, mCurrentFragment, mLeftFragment;
private Fragment mFragment; private Fragment mFragment;
private List<FragmentsAvailable> mFragmentsHistory;
private Fragment.SavedState mDialerSavedState; private Fragment.SavedState mDialerSavedState;
private boolean mNewProxyConfig; private boolean mNewProxyConfig;
private boolean mEmptyFragment = false; private boolean mEmptyFragment = false;
@ -163,11 +159,11 @@ public class LinphoneActivity extends LinphoneGenericActivity
private boolean mIsOnBackground = false; private boolean mIsOnBackground = false;
private int mAlwaysChangingPhoneAngle = -1; private int mAlwaysChangingPhoneAngle = -1;
public static final boolean isInstanciated() { public static boolean isInstanciated() {
return sInstance != null; return sInstance != null;
} }
public static final LinphoneActivity instance() { public static LinphoneActivity instance() {
if (sInstance != null) return sInstance; if (sInstance != null) return sInstance;
throw new RuntimeException("LinphoneActivity not instantiated yet"); throw new RuntimeException("LinphoneActivity not instantiated yet");
} }
@ -219,7 +215,6 @@ public class LinphoneActivity extends LinphoneGenericActivity
setContentView(R.layout.main); setContentView(R.layout.main);
sInstance = this; sInstance = this;
mFragmentsHistory = new ArrayList<>();
mPendingFragmentTransaction = FragmentsAvailable.UNKNOW; mPendingFragmentTransaction = FragmentsAvailable.UNKNOW;
initButtons(); initButtons();
@ -262,10 +257,6 @@ public class LinphoneActivity extends LinphoneGenericActivity
if (state.equals(RegistrationState.Failed) && mNewProxyConfig) { if (state.equals(RegistrationState.Failed) && mNewProxyConfig) {
mNewProxyConfig = false; mNewProxyConfig = false;
if (proxy.getError() == Reason.Forbidden) {
// displayCustomToast(getString(R.string.error_bad_credentials),
// Toast.LENGTH_LONG);
}
if (proxy.getError() == Reason.Unauthorized) { if (proxy.getError() == Reason.Unauthorized) {
displayCustomToast( displayCustomToast(
getString(R.string.error_unauthorized), Toast.LENGTH_LONG); getString(R.string.error_unauthorized), Toast.LENGTH_LONG);
@ -400,6 +391,7 @@ public class LinphoneActivity extends LinphoneGenericActivity
DialerFragment dialerFragment = DialerFragment.instance(); DialerFragment dialerFragment = DialerFragment.instance();
mDialerSavedState = getFragmentManager().saveFragmentInstanceState(dialerFragment); mDialerSavedState = getFragmentManager().saveFragmentInstanceState(dialerFragment);
} catch (Exception e) { } catch (Exception e) {
Log.e(e);
} }
} }
@ -413,7 +405,7 @@ public class LinphoneActivity extends LinphoneGenericActivity
break; break;
case CONTACTS_LIST: case CONTACTS_LIST:
checkAndRequestWriteContactsPermission(); checkAndRequestWriteContactsPermission();
mFragment = new ContactsListFragment(); mFragment = new ContactsFragment();
break; break;
case CONTACT_DETAIL: case CONTACT_DETAIL:
mFragment = new ContactDetailsFragment(); mFragment = new ContactDetailsFragment();
@ -478,7 +470,7 @@ public class LinphoneActivity extends LinphoneGenericActivity
((HistoryFragment) mFragment).displayFirstLog(); ((HistoryFragment) mFragment).displayFirstLog();
break; break;
case CONTACTS_LIST: case CONTACTS_LIST:
((ContactsListFragment) mFragment).displayFirstContact(); ((ContactsFragment) mFragment).displayFirstContact();
break; break;
case CHAT_LIST: case CHAT_LIST:
((ChatRoomsFragment) mFragment).displayFirstChat(); ((ChatRoomsFragment) mFragment).displayFirstChat();
@ -584,10 +576,9 @@ public class LinphoneActivity extends LinphoneGenericActivity
getFragmentManager() getFragmentManager()
.popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); .popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
} catch (java.lang.IllegalStateException e) { } catch (java.lang.IllegalStateException e) {
Log.e(e);
} }
} }
mFragmentsHistory.add(mCurrentFragment);
} }
} }
@ -681,11 +672,11 @@ public class LinphoneActivity extends LinphoneGenericActivity
changeCurrentFragment(FragmentsAvailable.CONTACTS_LIST, extras); changeCurrentFragment(FragmentsAvailable.CONTACTS_LIST, extras);
} }
public void displayAbout() { private void displayAbout() {
changeCurrentFragment(FragmentsAvailable.ABOUT, null); changeCurrentFragment(FragmentsAvailable.ABOUT, null);
} }
public void displayRecordings() { private void displayRecordings() {
changeCurrentFragment(FragmentsAvailable.RECORDING_LIST, null); changeCurrentFragment(FragmentsAvailable.RECORDING_LIST, null);
} }
@ -697,11 +688,11 @@ public class LinphoneActivity extends LinphoneGenericActivity
changeCurrentFragment(FragmentsAvailable.CONTACTS_LIST, extras); changeCurrentFragment(FragmentsAvailable.CONTACTS_LIST, extras);
} }
public void displayAssistant() { private void displayAssistant() {
startActivity(new Intent(LinphoneActivity.this, AssistantActivity.class)); startActivity(new Intent(LinphoneActivity.this, AssistantActivity.class));
} }
public void displayInapp() { private void displayInapp() {
startActivity(new Intent(LinphoneActivity.this, InAppPurchaseActivity.class)); startActivity(new Intent(LinphoneActivity.this, InAppPurchaseActivity.class));
} }
@ -930,11 +921,11 @@ public class LinphoneActivity extends LinphoneGenericActivity
mTopBarTitle.setText(""); mTopBarTitle.setText("");
} }
public void showTopBar() { private void showTopBar() {
mTopBar.setVisibility(View.VISIBLE); mTopBar.setVisibility(View.VISIBLE);
} }
public void showTopBarWithTitle(String title) { private void showTopBarWithTitle(String title) {
showTopBar(); showTopBar();
mTopBarTitle.setText(title); mTopBarTitle.setText(title);
} }
@ -1004,7 +995,7 @@ public class LinphoneActivity extends LinphoneGenericActivity
| WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
} }
public void goToDialerFragment() { private void goToDialerFragment() {
Bundle extras = new Bundle(); Bundle extras = new Bundle();
extras.putString("SipUri", ""); extras.putString("SipUri", "");
changeCurrentFragment(FragmentsAvailable.DIALER, extras); changeCurrentFragment(FragmentsAvailable.DIALER, extras);
@ -1019,7 +1010,7 @@ public class LinphoneActivity extends LinphoneGenericActivity
changeCurrentFragment(FragmentsAvailable.SETTINGS, null); changeCurrentFragment(FragmentsAvailable.SETTINGS, null);
} }
public void displayDialer() { private void displayDialer() {
changeCurrentFragment(FragmentsAvailable.DIALER, null); changeCurrentFragment(FragmentsAvailable.DIALER, null);
} }
@ -1053,7 +1044,6 @@ public class LinphoneActivity extends LinphoneGenericActivity
mMissedChats.setVisibility(View.GONE); mMissedChats.setVisibility(View.GONE);
} }
if (mCurrentFragment == FragmentsAvailable.CHAT_LIST if (mCurrentFragment == FragmentsAvailable.CHAT_LIST
&& mFragment != null
&& mFragment instanceof ChatRoomsFragment) { && mFragment instanceof ChatRoomsFragment) {
((ChatRoomsFragment) mFragment).invalidate(); ((ChatRoomsFragment) mFragment).invalidate();
} }
@ -1108,8 +1098,7 @@ public class LinphoneActivity extends LinphoneGenericActivity
return dialog; return dialog;
} }
@Override public void setAddresGoToDialerAndCall(String number, String name) {
public void setAddresGoToDialerAndCall(String number, String name, Uri photo) {
// Bundle extras = new Bundle(); // Bundle extras = new Bundle();
// extras.putString("SipUri", number); // extras.putString("SipUri", number);
// extras.putString("DisplayName", name); // extras.putString("DisplayName", name);
@ -1181,14 +1170,7 @@ public class LinphoneActivity extends LinphoneGenericActivity
changeCurrentFragment(FragmentsAvailable.CONTACT_EDITOR, extras); changeCurrentFragment(FragmentsAvailable.CONTACT_EDITOR, extras);
} }
public void editContact(LinphoneContact contact, String sipAddress) { private void quit() {
Bundle extras = new Bundle();
extras.putSerializable("Contact", contact);
extras.putSerializable("NewSipAdress", sipAddress);
changeCurrentFragment(FragmentsAvailable.CONTACT_EDITOR, extras);
}
public void quit() {
finish(); finish();
stopService(new Intent(Intent.ACTION_MAIN).setClass(this, LinphoneService.class)); stopService(new Intent(Intent.ACTION_MAIN).setClass(this, LinphoneService.class));
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
@ -1272,7 +1254,7 @@ public class LinphoneActivity extends LinphoneGenericActivity
checkAndRequestPermission(Manifest.permission.CAMERA, 0); checkAndRequestPermission(Manifest.permission.CAMERA, 0);
} }
public void checkAndRequestWriteContactsPermission() { private void checkAndRequestWriteContactsPermission() {
checkAndRequestPermission(Manifest.permission.WRITE_CONTACTS, 0); checkAndRequestPermission(Manifest.permission.WRITE_CONTACTS, 0);
} }
@ -1333,7 +1315,7 @@ public class LinphoneActivity extends LinphoneGenericActivity
Manifest.permission.WRITE_SYNC_SETTINGS, PERMISSIONS_REQUEST_SYNC); Manifest.permission.WRITE_SYNC_SETTINGS, PERMISSIONS_REQUEST_SYNC);
} }
public void checkAndRequestPermission(String permission, int result) { private void checkAndRequestPermission(String permission, int result) {
int permissionGranted = getPackageManager().checkPermission(permission, getPackageName()); int permissionGranted = getPackageManager().checkPermission(permission, getPackageName());
Log.i( Log.i(
"[Permission] " "[Permission] "
@ -1550,7 +1532,7 @@ public class LinphoneActivity extends LinphoneGenericActivity
intent.putExtra("msgShared", ""); intent.putExtra("msgShared", "");
} }
if (intent.getStringExtra("fileShared") != null if (intent.getStringExtra("fileShared") != null
&& intent.getStringExtra("fileShared") != "") { && !intent.getStringExtra("fileShared").equals("")) {
displayChat(null, null, intent.getStringExtra("fileShared")); displayChat(null, null, intent.getStringExtra("fileShared"));
intent.putExtra("fileShared", ""); intent.putExtra("fileShared", "");
} }
@ -1704,7 +1686,7 @@ public class LinphoneActivity extends LinphoneGenericActivity
} }
// SIDE MENU // SIDE MENU
public void openOrCloseSideMenu(boolean open) { private void openOrCloseSideMenu(boolean open) {
if (open) { if (open) {
mSideMenu.openDrawer(mSideMenuContent); mSideMenu.openDrawer(mSideMenuContent);
} else { } else {
@ -1712,7 +1694,7 @@ public class LinphoneActivity extends LinphoneGenericActivity
} }
} }
public void initSideMenu() { private void initSideMenu() {
mSideMenu = findViewById(R.id.side_menu); mSideMenu = findViewById(R.id.side_menu);
mSideMenuItems = new ArrayList<>(); mSideMenuItems = new ArrayList<>();
if (!getResources().getBoolean(R.bool.hide_assistant_from_side_menu)) { if (!getResources().getBoolean(R.bool.hide_assistant_from_side_menu)) {
@ -1909,7 +1891,7 @@ public class LinphoneActivity extends LinphoneGenericActivity
} }
@Override @Override
public void onError(String error) {} public void onError() {}
}, },
LinphonePreferences.instance() LinphonePreferences.instance()
.getAccountUsername( .getAccountUsername(
@ -1947,7 +1929,7 @@ public class LinphoneActivity extends LinphoneGenericActivity
} }
@Override @Override
public void onError(String error) {} public void onError() {}
}, },
LinphonePreferences.instance() LinphonePreferences.instance()
.getAccountUsername( .getAccountUsername(
@ -1958,7 +1940,7 @@ public class LinphoneActivity extends LinphoneGenericActivity
} }
} }
public void displayInappNotification(String date) { private void displayInappNotification(String date) {
Timestamp now = new Timestamp(new Date().getTime()); Timestamp now = new Timestamp(new Date().getTime());
if (LinphonePreferences.instance().getInappPopupTime() != null if (LinphonePreferences.instance().getInappPopupTime() != null
&& Long.parseLong(LinphonePreferences.instance().getInappPopupTime()) && Long.parseLong(LinphonePreferences.instance().getInappPopupTime())
@ -2004,7 +1986,7 @@ public class LinphoneActivity extends LinphoneGenericActivity
} }
private class LocalOrientationEventListener extends OrientationEventListener { private class LocalOrientationEventListener extends OrientationEventListener {
public LocalOrientationEventListener(Context context) { LocalOrientationEventListener(Context context) {
super(context); super(context);
} }
@ -2047,7 +2029,7 @@ public class LinphoneActivity extends LinphoneGenericActivity
refresh(); refresh();
} }
public void refresh() { void refresh() {
proxy_list = new ArrayList<>(); proxy_list = new ArrayList<>();
for (ProxyConfig proxyConfig : LinphoneManager.getLc().getProxyConfigList()) { for (ProxyConfig proxyConfig : LinphoneManager.getLc().getProxyConfigList()) {
if (proxyConfig != LinphoneManager.getLc().getDefaultProxyConfig()) { if (proxyConfig != LinphoneManager.getLc().getDefaultProxyConfig()) {
@ -2088,7 +2070,7 @@ public class LinphoneActivity extends LinphoneGenericActivity
address.setText(sipAddress); address.setText(sipAddress);
int nbAccounts = LinphonePreferences.instance().getAccountCount(); int nbAccounts = LinphonePreferences.instance().getAccountCount();
int accountIndex = 0; int accountIndex;
for (int i = 0; i < nbAccounts; i++) { for (int i = 0; i < nbAccounts; i++) {
String username = LinphonePreferences.instance().getAccountUsername(i); String username = LinphonePreferences.instance().getAccountUsername(i);
@ -2106,10 +2088,10 @@ public class LinphoneActivity extends LinphoneGenericActivity
} }
private class MenuItem { private class MenuItem {
public String name; final String name;
public int icon; final int icon;
public MenuItem(String name, int icon) { MenuItem(String name, int icon) {
this.name = name; this.name = name;
this.icon = icon; this.icon = icon;
} }
@ -2120,11 +2102,10 @@ public class LinphoneActivity extends LinphoneGenericActivity
} }
private class MenuAdapter extends ArrayAdapter<MenuItem> { private class MenuAdapter extends ArrayAdapter<MenuItem> {
private List<MenuItem> mItems; private final List<MenuItem> mItems;
private int mResource; private final int mResource;
public MenuAdapter( MenuAdapter(@NonNull Context context, int resource, @NonNull List<MenuItem> objects) {
@NonNull Context context, int resource, @NonNull List<MenuItem> objects) {
super(context, resource, objects); super(context, resource, objects);
mResource = resource; mResource = resource;
mItems = objects; mItems = objects;

View file

@ -72,9 +72,8 @@ public class LinphoneLauncherActivity extends Activity {
} else if (Intent.ACTION_VIEW.equals(action)) { } else if (Intent.ACTION_VIEW.equals(action)) {
if (LinphoneService.isReady()) { if (LinphoneService.isReady()) {
mAddressToCall = mAddressToCall =
ContactsManager.getInstance() ContactsManager.getAddressOrNumberForAndroidContact(
.getAddressOrNumberForAndroidContact( getContentResolver(), intent.getData());
getContentResolver(), intent.getData());
} else { } else {
mUriToResolve = intent.getData(); mUriToResolve = intent.getData();
} }
@ -91,17 +90,7 @@ public class LinphoneLauncherActivity extends Activity {
} }
} }
@Override private void onServiceReady() {
protected void onResume() {
super.onResume();
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
}
protected void onServiceReady() {
final Class<? extends Activity> classToStart; final Class<? extends Activity> classToStart;
/*if (getResources().getBoolean(R.bool.show_tutorials_instead_of_app)) { /*if (getResources().getBoolean(R.bool.show_tutorials_instead_of_app)) {
classToStart = TutorialLauncherActivity.class; classToStart = TutorialLauncherActivity.class;
@ -128,12 +117,11 @@ public class LinphoneLauncherActivity extends Activity {
newIntent.setData(intent.getData()); newIntent.setData(intent.getData());
if (Intent.ACTION_SEND.equals(action) && type != null) { if (Intent.ACTION_SEND.equals(action) && type != null) {
if (("text/plain").equals(type) if (("text/plain").equals(type)
&& (String) intent.getStringExtra(Intent.EXTRA_TEXT) && intent.getStringExtra(Intent.EXTRA_TEXT) != null) {
!= null) {
stringFileShared = intent.getStringExtra(Intent.EXTRA_TEXT); stringFileShared = intent.getStringExtra(Intent.EXTRA_TEXT);
newIntent.putExtra("msgShared", stringFileShared); newIntent.putExtra("msgShared", stringFileShared);
} else { } else {
fileUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM); fileUri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
stringUriFileShared = stringUriFileShared =
FileUtils.getFilePath(getBaseContext(), fileUri); FileUtils.getFilePath(getBaseContext(), fileUri);
newIntent.putExtra("fileShared", stringUriFileShared); newIntent.putExtra("fileShared", stringUriFileShared);
@ -155,9 +143,8 @@ public class LinphoneLauncherActivity extends Activity {
} }
if (mUriToResolve != null) { if (mUriToResolve != null) {
mAddressToCall = mAddressToCall =
ContactsManager.getInstance() ContactsManager.getAddressOrNumberForAndroidContact(
.getAddressOrNumberForAndroidContact( getContentResolver(), mUriToResolve);
getContentResolver(), mUriToResolve);
Log.i( Log.i(
"LinphoneLauncher", "LinphoneLauncher",
"Intent has uri to resolve : " + mUriToResolve.toString()); "Intent has uri to resolve : " + mUriToResolve.toString());

View file

@ -71,6 +71,7 @@ import org.linphone.assistant.AssistantActivity;
import org.linphone.call.CallActivity; import org.linphone.call.CallActivity;
import org.linphone.call.CallIncomingActivity; import org.linphone.call.CallIncomingActivity;
import org.linphone.call.CallManager; import org.linphone.call.CallManager;
import org.linphone.compatibility.Compatibility;
import org.linphone.contacts.ContactsManager; import org.linphone.contacts.ContactsManager;
import org.linphone.contacts.LinphoneContact; import org.linphone.contacts.LinphoneContact;
import org.linphone.core.AccountCreator; import org.linphone.core.AccountCreator;
@ -90,7 +91,6 @@ import org.linphone.core.ConfiguringState;
import org.linphone.core.Content; import org.linphone.core.Content;
import org.linphone.core.Core; import org.linphone.core.Core;
import org.linphone.core.Core.LogCollectionUploadState; import org.linphone.core.Core.LogCollectionUploadState;
import org.linphone.core.CoreException;
import org.linphone.core.CoreListener; import org.linphone.core.CoreListener;
import org.linphone.core.EcCalibratorStatus; import org.linphone.core.EcCalibratorStatus;
import org.linphone.core.Event; import org.linphone.core.Event;
@ -151,7 +151,7 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou
private static LinphoneManager sInstance; private static LinphoneManager sInstance;
private static boolean sExited; private static boolean sExited;
public String configFile; public final String configFile;
public String wizardLoginViewDomain = null; public String wizardLoginViewDomain = null;
/** Called when the activity is first created. */ /** Called when the activity is first created. */
@ -164,21 +164,21 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou
private final String mCallLogDatabaseFile; private final String mCallLogDatabaseFile;
private final String mFriendsDatabaseFile; private final String mFriendsDatabaseFile;
private final String mUserCertsPath; private final String mUserCertsPath;
private Context mServiceContext; private final Context mServiceContext;
private AudioManager mAudioManager; private final AudioManager mAudioManager;
private PowerManager mPowerManager; private final PowerManager mPowerManager;
private Resources mRessources; private final Resources mRessources;
private LinphonePreferences mPrefs; private final LinphonePreferences mPrefs;
private Core mCore; private Core mCore;
private OpenH264DownloadHelper mCodecDownloader; private OpenH264DownloadHelper mCodecDownloader;
private OpenH264DownloadHelperListener mCodecListener; private OpenH264DownloadHelperListener mCodecListener;
private String mBasePath; private final String mBasePath;
private boolean mAudioFocused; private boolean mAudioFocused;
private boolean mEchoTesterIsRunning; private boolean mEchoTesterIsRunning;
private boolean mDozeModeEnabled; private boolean mDozeModeEnabled;
private boolean mCallGsmON; private boolean mCallGsmON;
private int mLastNetworkType = -1; private int mLastNetworkType = -1;
private ConnectivityManager mConnectivityManager; private final ConnectivityManager mConnectivityManager;
private BroadcastReceiver mKeepAliveReceiver; private BroadcastReceiver mKeepAliveReceiver;
private BroadcastReceiver mDozeReceiver; private BroadcastReceiver mDozeReceiver;
private BroadcastReceiver mHookReceiver; private BroadcastReceiver mHookReceiver;
@ -189,23 +189,23 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou
private IntentFilter mHookIntentFilter; private IntentFilter mHookIntentFilter;
private IntentFilter mCallIntentFilter; private IntentFilter mCallIntentFilter;
private IntentFilter mNetworkIntentFilter; private IntentFilter mNetworkIntentFilter;
private Handler mHandler = new Handler(); private final Handler mHandler = new Handler();
private WakeLock mProximityWakelock; private WakeLock mProximityWakelock;
private AccountCreator mAccountCreator; private AccountCreator mAccountCreator;
private SensorManager mSensorManager; private final SensorManager mSensorManager;
private Sensor mProximity; private final Sensor mProximity;
private boolean mProximitySensingEnabled; private boolean mProximitySensingEnabled;
private boolean mHandsetON = false; private boolean mHandsetON = false;
private Address mCurrentChatRoomAddress; private Address mCurrentChatRoomAddress;
private Timer mTimer; private Timer mTimer;
private Map<String, Integer> mUnreadChatsPerRoom; private final Map<String, Integer> mUnreadChatsPerRoom;
private MediaScanner mMediaScanner; private final MediaScanner mMediaScanner;
private Call mRingingCall; private Call mRingingCall;
private MediaPlayer mRingerPlayer; private MediaPlayer mRingerPlayer;
private Vibrator mVibrator; private final Vibrator mVibrator;
private boolean mIsRinging; private boolean mIsRinging;
protected LinphoneManager(Context c) { private LinphoneManager(Context c) {
mUnreadChatsPerRoom = new HashMap(); mUnreadChatsPerRoom = new HashMap();
sExited = false; sExited = false;
mEchoTesterIsRunning = false; mEchoTesterIsRunning = false;
@ -241,7 +241,7 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou
mMediaScanner = new MediaScanner(c); mMediaScanner = new MediaScanner(c);
} }
public static final synchronized LinphoneManager createAndStart(Context c) { public static synchronized void createAndStart(Context c) {
if (sInstance != null) { if (sInstance != null) {
Log.e( Log.e(
"Linphone Manager is already initialized ! Destroying it and creating a new one..."); "Linphone Manager is already initialized ! Destroying it and creating a new one...");
@ -254,11 +254,9 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou
// H264 codec Management - set to auto mode -> MediaCodec >= android 5.0 >= OpenH264 // H264 codec Management - set to auto mode -> MediaCodec >= android 5.0 >= OpenH264
H264Helper.setH264Mode(H264Helper.MODE_AUTO, getLc()); H264Helper.setH264Mode(H264Helper.MODE_AUTO, getLc());
return sInstance;
} }
public static final synchronized LinphoneManager getInstance() { public static synchronized LinphoneManager getInstance() {
if (sInstance != null) return sInstance; if (sInstance != null) return sInstance;
if (sExited) { if (sExited) {
@ -270,11 +268,11 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou
throw new RuntimeException("Linphone Manager should be created before accessed"); throw new RuntimeException("Linphone Manager should be created before accessed");
} }
public static final synchronized Core getLc() { public static synchronized Core getLc() {
return getInstance().mCore; return getInstance().mCore;
} }
public static Boolean isProximitySensorNearby(final SensorEvent event) { private static Boolean isProximitySensorNearby(final SensorEvent event) {
float threshold = 4.001f; // <= 4 cm is near float threshold = 4.001f; // <= 4 cm is near
final float distanceInCm = event.values[0]; final float distanceInCm = event.values[0];
@ -293,7 +291,7 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou
return distanceInCm < threshold; return distanceInCm < threshold;
} }
public static void ContactsManagerDestroy() { private static void ContactsManagerDestroy() {
if (LinphoneManager.sInstance != null && LinphoneManager.sInstance.mServiceContext != null) if (LinphoneManager.sInstance != null && LinphoneManager.sInstance.mServiceContext != null)
LinphoneManager.sInstance LinphoneManager.sInstance
.mServiceContext .mServiceContext
@ -302,7 +300,7 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou
ContactsManager.getInstance().destroy(); ContactsManager.getInstance().destroy();
} }
public static void BluetoothManagerDestroy() { private static void BluetoothManagerDestroy() {
BluetoothManager.getInstance().destroy(); BluetoothManager.getInstance().destroy();
} }
@ -315,7 +313,7 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou
sInstance = null; sInstance = null;
} }
public static boolean reinviteWithVideo() { private static boolean reinviteWithVideo() {
return CallManager.getInstance().reinviteWithVideo(); return CallManager.getInstance().reinviteWithVideo();
} }
@ -329,7 +327,7 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou
return getLc(); return getLc();
} }
public static final boolean isInstanciated() { public static boolean isInstanciated() {
return sInstance != null; return sInstance != null;
} }
@ -351,7 +349,7 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou
mAudioManager.setSpeakerphoneOn(enable); mAudioManager.setSpeakerphoneOn(enable);
} }
public void initOpenH264DownloadHelper() { private void initOpenH264DownloadHelper() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
Log.i("Android >= 5.1 we disable the download of OpenH264"); Log.i("Android >= 5.1 we disable the download of OpenH264");
OpenH264DownloadHelper.setOpenH264DownloadEnabled(false); OpenH264DownloadHelper.setOpenH264DownloadEnabled(false);
@ -362,7 +360,7 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou
mCodecListener = mCodecListener =
new OpenH264DownloadHelperListener() { new OpenH264DownloadHelperListener() {
ProgressDialog progress; ProgressDialog progress;
int ctxt = 0; final int ctxt = 0;
int box = 1; int box = 1;
@Override @Override
@ -491,7 +489,7 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou
} }
} }
public void changeStatusToOffline() { private void changeStatusToOffline() {
Core lc = getLcIfManagerNotDestroyedOrNull(); Core lc = getLcIfManagerNotDestroyedOrNull();
if (isInstanciated() && lc != null) { if (isInstanciated() && lc != null) {
PresenceModel model = lc.getPresenceModel(); PresenceModel model = lc.getPresenceModel();
@ -542,7 +540,7 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou
ProxyConfig lpc = mCore.getDefaultProxyConfig(); ProxyConfig lpc = mCore.getDefaultProxyConfig();
if (mRessources.getBoolean(R.bool.forbid_self_call) if (mRessources.getBoolean(R.bool.forbid_self_call)
&& lpc != null && lpc != null
&& lAddress.asStringUriOnly().equals(lpc.getIdentityAddress())) { && lAddress.weakEqual(lpc.getIdentityAddress())) {
return; return;
} }
lAddress.setDisplayName(displayName); lAddress.setDisplayName(displayName);
@ -592,7 +590,7 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou
LinphoneManager.getLc().setVideoDevice(newDevice); LinphoneManager.getLc().setVideoDevice(newDevice);
} }
public void enableCamera(Call call, boolean enable) { private void enableCamera(Call call, boolean enable) {
if (call != null) { if (call != null) {
call.enableCamera(enable); call.enableCamera(enable);
if (mServiceContext.getResources().getBoolean(R.bool.enable_call_notification)) if (mServiceContext.getResources().getBoolean(R.bool.enable_call_notification))
@ -609,12 +607,13 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou
return; return;
} }
} catch (SettingNotFoundException e) { } catch (SettingNotFoundException e) {
Log.e(e);
} }
getLc().playDtmf(dtmf, -1); getLc().playDtmf(dtmf, -1);
} }
public void terminateCall() { private void terminateCall() {
if (mCore.inCall()) { if (mCore.inCall()) {
mCore.terminateCall(mCore.getCurrentCall()); mCore.terminateCall(mCore.getCurrentCall());
} }
@ -673,7 +672,7 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou
} }
} }
public final synchronized void destroyCore() { private final synchronized void destroyCore() {
sExited = true; sExited = true;
ContactsManagerDestroy(); ContactsManagerDestroy();
BluetoothManagerDestroy(); BluetoothManagerDestroy();
@ -707,8 +706,6 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou
} }
try { try {
dozeManager(false); dozeManager(false);
} catch (IllegalArgumentException iae) {
Log.e(iae);
} catch (Exception e) { } catch (Exception e) {
Log.e(e); Log.e(e);
} }
@ -776,12 +773,12 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou
} }
} }
private synchronized void initLiblinphone(Core lc) throws CoreException { private synchronized void initLiblinphone(Core lc) {
mCore = lc; mCore = lc;
mCore.setZrtpSecretsFile(mBasePath + "/zrtp_secrets"); mCore.setZrtpSecretsFile(mBasePath + "/zrtp_secrets");
String deviceName = LinphoneUtils.getDeviceName(mServiceContext); String deviceName = Compatibility.getDeviceName(mServiceContext);
String appName = mServiceContext.getResources().getString(R.string.user_agent); String appName = mServiceContext.getResources().getString(R.string.user_agent);
String androidVersion = BuildConfig.VERSION_NAME; String androidVersion = BuildConfig.VERSION_NAME;
String userAgent = appName + "/" + androidVersion + " (" + deviceName + ") LinphoneSDK"; String userAgent = appName + "/" + androidVersion + " (" + deviceName + ") LinphoneSDK";
@ -907,14 +904,14 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou
copyFromPackage(R.raw.assistant_create, new File(mDynamicConfigFile).getName()); copyFromPackage(R.raw.assistant_create, new File(mDynamicConfigFile).getName());
} }
public void copyIfNotExist(int ressourceId, String target) throws IOException { private void copyIfNotExist(int ressourceId, String target) throws IOException {
File lFileToCopy = new File(target); File lFileToCopy = new File(target);
if (!lFileToCopy.exists()) { if (!lFileToCopy.exists()) {
copyFromPackage(ressourceId, lFileToCopy.getName()); copyFromPackage(ressourceId, lFileToCopy.getName());
} }
} }
public void copyFromPackage(int ressourceId, String target) throws IOException { private void copyFromPackage(int ressourceId, String target) throws IOException {
FileOutputStream lOutputStream = mServiceContext.openFileOutput(target, 0); FileOutputStream lOutputStream = mServiceContext.openFileOutput(target, 0);
InputStream lInputStream = mRessources.openRawResource(ressourceId); InputStream lInputStream = mRessources.openRawResource(ressourceId);
int readByte; int readByte;
@ -998,7 +995,7 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou
mCore = null; mCore = null;
} }
public void dozeManager(boolean enable) { private void dozeManager(boolean enable) {
if (enable) { if (enable) {
Log.i("[Doze Mode]: register"); Log.i("[Doze Mode]: register");
mServiceContext.registerReceiver(mDozeReceiver, mDozeIntentFilter); mServiceContext.registerReceiver(mDozeReceiver, mDozeIntentFilter);
@ -1068,7 +1065,7 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou
I/Linphone( 8397): Managing tunnel I/Linphone( 8397): Managing tunnel
I/Linphone( 8397): WIFI connected: setting network reachable I/Linphone( 8397): WIFI connected: setting network reachable
*/ */
public void connectivityChanged(ConnectivityManager cm, boolean noConnectivity) { public void connectivityChanged() {
updateNetworkReachability(); updateNetworkReachability();
} }
@ -1241,8 +1238,6 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou
} catch (IllegalArgumentException iae) { } catch (IllegalArgumentException iae) {
Log.e(iae); Log.e(iae);
} catch (CoreException e) {
Log.e(e);
} }
} }
} }
@ -1276,7 +1271,7 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou
mAudioManager.setMode(AudioManager.MODE_NORMAL); mAudioManager.setMode(AudioManager.MODE_NORMAL);
} }
public void setAudioManagerInCallMode() { private void setAudioManagerInCallMode() {
if (mAudioManager.getMode() == AudioManager.MODE_IN_COMMUNICATION) { if (mAudioManager.getMode() == AudioManager.MODE_IN_COMMUNICATION) {
Log.w("[AudioManager] already in MODE_IN_COMMUNICATION, skipping..."); Log.w("[AudioManager] already in MODE_IN_COMMUNICATION, skipping...");
return; return;
@ -1392,7 +1387,7 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou
if (remoteVideo if (remoteVideo
&& !localVideo && !localVideo
&& !autoAcceptCameraPolicy && !autoAcceptCameraPolicy
&& !(LinphoneManager.getLc().getConference() != null)) { && LinphoneManager.getLc().getConference() == null) {
LinphoneManager.getLc().deferCallUpdate(call); LinphoneManager.getLc().deferCallUpdate(call);
} }
} }
@ -1410,7 +1405,7 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou
} }
} }
public void startBluetooth() { private void startBluetooth() {
if (BluetoothManager.getInstance().isBluetoothHeadsetAvailable()) { if (BluetoothManager.getInstance().isBluetoothHeadsetAvailable()) {
BluetoothManager.getInstance().routeAudioToBluetooth(); BluetoothManager.getInstance().routeAudioToBluetooth();
} }
@ -1427,7 +1422,7 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou
public void onCallEncryptionChanged( public void onCallEncryptionChanged(
Core lc, Call call, boolean encrypted, String authenticationToken) {} Core lc, Call call, boolean encrypted, String authenticationToken) {}
public void startEcCalibration() throws CoreException { public void startEcCalibration() {
routeAudioToSpeaker(); routeAudioToSpeaker();
setAudioManagerInCallMode(); setAudioManagerInCallMode();
Log.i("Set audio mode on 'Voice Communication'"); Log.i("Set audio mode on 'Voice Communication'");
@ -1439,25 +1434,23 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou
mAudioManager.setStreamVolume(STREAM_VOICE_CALL, oldVolume, 0); mAudioManager.setStreamVolume(STREAM_VOICE_CALL, oldVolume, 0);
} }
public int startEchoTester() throws CoreException { public int startEchoTester() {
routeAudioToSpeaker(); routeAudioToSpeaker();
setAudioManagerInCallMode(); setAudioManagerInCallMode();
Log.i("Set audio mode on 'Voice Communication'"); Log.i("Set audio mode on 'Voice Communication'");
requestAudioFocus(STREAM_VOICE_CALL); requestAudioFocus(STREAM_VOICE_CALL);
int maxVolume = mAudioManager.getStreamMaxVolume(STREAM_VOICE_CALL); int maxVolume = mAudioManager.getStreamMaxVolume(STREAM_VOICE_CALL);
int sampleRate = 44100; int sampleRate;
mAudioManager.setStreamVolume(STREAM_VOICE_CALL, maxVolume, 0); mAudioManager.setStreamVolume(STREAM_VOICE_CALL, maxVolume, 0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { String sampleRateProperty =
String sampleRateProperty = mAudioManager.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE);
mAudioManager.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE); sampleRate = Integer.parseInt(sampleRateProperty);
sampleRate = Integer.parseInt(sampleRateProperty);
}
mCore.startEchoTester(sampleRate); mCore.startEchoTester(sampleRate);
mEchoTesterIsRunning = true; mEchoTesterIsRunning = true;
return 1; return 1;
} }
public int stopEchoTester() throws CoreException { public int stopEchoTester() {
mEchoTesterIsRunning = false; mEchoTesterIsRunning = false;
mCore.stopEchoTester(); mCore.stopEchoTester();
routeAudioToReceiver(); routeAudioToReceiver();
@ -1607,31 +1600,17 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou
return false; return false;
} }
return acceptCallWithParams(call, params);
}
public boolean acceptCallWithParams(Call call, CallParams params) {
mCore.acceptCallWithParams(call, params); mCore.acceptCallWithParams(call, params);
return true; return true;
} }
public void adjustVolume(int i) { public void adjustVolume(int i) {
if (Build.VERSION.SDK_INT < 15) { // starting from ICS, volume must be adjusted by the application, at least for
int oldVolume = mAudioManager.getStreamVolume(LINPHONE_VOLUME_STREAM); // STREAM_VOICE_CALL volume stream
int maxVolume = mAudioManager.getStreamMaxVolume(LINPHONE_VOLUME_STREAM); mAudioManager.adjustStreamVolume(
LINPHONE_VOLUME_STREAM,
int nextVolume = oldVolume + i; i < 0 ? AudioManager.ADJUST_LOWER : AudioManager.ADJUST_RAISE,
if (nextVolume > maxVolume) nextVolume = maxVolume; AudioManager.FLAG_SHOW_UI);
if (nextVolume < 0) nextVolume = 0;
mCore.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 void isAccountWithAlias() { public void isAccountWithAlias() {

View file

@ -69,11 +69,11 @@ public final class LinphoneService extends Service {
/* Listener needs to be implemented in the Service as it calls /* Listener needs to be implemented in the Service as it calls
* setLatestEventInfo and startActivity() which needs a context. * setLatestEventInfo and startActivity() which needs a context.
*/ */
public static final String START_LINPHONE_LOGS = " ==== Phone information dump ===="; private static final String START_LINPHONE_LOGS = " ==== Phone information dump ====";
private static LinphoneService sInstance; private static LinphoneService sInstance;
public Handler handler = new Handler(); public final Handler handler = new Handler();
private boolean mTestDelayElapsed = true; private boolean mTestDelayElapsed = true;
private CoreListenerStub mListener; private CoreListenerStub mListener;
@ -108,7 +108,7 @@ public final class LinphoneService extends Service {
} }
} }
protected void onBackgroundMode() { private void onBackgroundMode() {
Log.i("App has entered background mode"); Log.i("App has entered background mode");
if (LinphonePreferences.instance() != null if (LinphonePreferences.instance() != null
&& LinphonePreferences.instance().isFriendlistsubscriptionEnabled()) { && LinphonePreferences.instance().isFriendlistsubscriptionEnabled()) {
@ -120,7 +120,7 @@ public final class LinphoneService extends Service {
} }
} }
protected void onForegroundMode() { private void onForegroundMode() {
Log.i("App has left background mode"); Log.i("App has left background mode");
if (LinphonePreferences.instance() != null if (LinphonePreferences.instance() != null
&& LinphonePreferences.instance().isFriendlistsubscriptionEnabled()) { && LinphonePreferences.instance().isFriendlistsubscriptionEnabled()) {
@ -316,7 +316,7 @@ public final class LinphoneService extends Service {
sb.append("SDK=").append(Build.VERSION.SDK_INT).append("\n"); sb.append("SDK=").append(Build.VERSION.SDK_INT).append("\n");
sb.append("Supported ABIs="); sb.append("Supported ABIs=");
for (String abi : Version.getCpuAbis()) { for (String abi : Version.getCpuAbis()) {
sb.append(abi + ", "); sb.append(abi).append(", ");
} }
sb.append("\n"); sb.append("\n");
Log.i(sb.toString()); Log.i(sb.toString());
@ -327,6 +327,7 @@ public final class LinphoneService extends Service {
try { try {
info = getPackageManager().getPackageInfo(getPackageName(), 0); info = getPackageManager().getPackageInfo(getPackageName(), 0);
} catch (NameNotFoundException nnfe) { } catch (NameNotFoundException nnfe) {
Log.e(nnfe);
} }
if (info != null) { if (info != null) {
@ -400,7 +401,7 @@ public final class LinphoneService extends Service {
} }
} }
protected void onIncomingReceived() { private void onIncomingReceived() {
// wakeup linphone // wakeup linphone
startActivity( startActivity(
new Intent() new Intent()
@ -412,7 +413,7 @@ public final class LinphoneService extends Service {
After two days of hard work I ended with the following class, that does the job more or less reliabily. 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 { class ActivityMonitor implements Application.ActivityLifecycleCallbacks {
private ArrayList<Activity> activities = new ArrayList<>(); private final ArrayList<Activity> activities = new ArrayList<>();
private boolean mActive = false; private boolean mActive = false;
private int mRunningActivities = 0; private int mRunningActivities = 0;
private InactivityChecker mLastChecker; private InactivityChecker mLastChecker;
@ -459,9 +460,7 @@ public final class LinphoneService extends Service {
@Override @Override
public synchronized void onActivityDestroyed(Activity activity) { public synchronized void onActivityDestroyed(Activity activity) {
Log.i("Activity destroyed:" + activity); Log.i("Activity destroyed:" + activity);
if (activities.contains(activity)) { activities.remove(activity);
activities.remove(activity);
}
} }
void startInactivityChecker() { void startInactivityChecker() {
@ -488,7 +487,7 @@ public final class LinphoneService extends Service {
class InactivityChecker implements Runnable { class InactivityChecker implements Runnable {
private boolean isCanceled; private boolean isCanceled;
public void cancel() { void cancel() {
isCanceled = true; isCanceled = true;
} }

View file

@ -356,16 +356,16 @@ public class AssistantActivity extends Activity
} }
} }
public void checkAndRequestAudioPermission() { private void checkAndRequestAudioPermission() {
checkAndRequestPermission( checkAndRequestPermission(
Manifest.permission.RECORD_AUDIO, PERMISSIONS_REQUEST_RECORD_AUDIO); Manifest.permission.RECORD_AUDIO, PERMISSIONS_REQUEST_RECORD_AUDIO);
} }
public void checkAndRequestVideoPermission() { private void checkAndRequestVideoPermission() {
checkAndRequestPermission(Manifest.permission.CAMERA, PERMISSIONS_REQUEST_CAMERA); checkAndRequestPermission(Manifest.permission.CAMERA, PERMISSIONS_REQUEST_CAMERA);
} }
public void checkAndRequestPermission(String permission, int result) { private void checkAndRequestPermission(String permission, int result) {
int permissionGranted = getPackageManager().checkPermission(permission, getPackageName()); int permissionGranted = getPackageManager().checkPermission(permission, getPackageName());
Log.i( Log.i(
"[Permission] " "[Permission] "
@ -405,7 +405,7 @@ public class AssistantActivity extends Activity
break; break;
case PERMISSIONS_REQUEST_RECORD_AUDIO: case PERMISSIONS_REQUEST_RECORD_AUDIO:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
launchEchoCancellerCalibration(true); launchEchoCancellerCalibration();
} else { } else {
isEchoCalibrationFinished(); isEchoCalibrationFinished();
} }
@ -413,7 +413,7 @@ public class AssistantActivity extends Activity
} }
} }
private void launchEchoCancellerCalibration(boolean sendEcCalibrationResult) { private void launchEchoCancellerCalibration() {
int recordAudio = int recordAudio =
getPackageManager() getPackageManager()
.checkPermission(Manifest.permission.RECORD_AUDIO, getPackageName()); .checkPermission(Manifest.permission.RECORD_AUDIO, getPackageName());
@ -425,7 +425,7 @@ public class AssistantActivity extends Activity
if (recordAudio == PackageManager.PERMISSION_GRANTED) { if (recordAudio == PackageManager.PERMISSION_GRANTED) {
EchoCancellerCalibrationFragment fragment = new EchoCancellerCalibrationFragment(); EchoCancellerCalibrationFragment fragment = new EchoCancellerCalibrationFragment();
fragment.enableEcCalibrationResultSending(sendEcCalibrationResult); fragment.enableEcCalibrationResultSending(true);
changeFragment(fragment); changeFragment(fragment);
mCurrentFragment = AssistantFragmentsEnum.ECHO_CANCELLER_CALIBRATION; mCurrentFragment = AssistantFragmentsEnum.ECHO_CANCELLER_CALIBRATION;
mBack.setVisibility(View.VISIBLE); mBack.setVisibility(View.VISIBLE);
@ -435,7 +435,7 @@ public class AssistantActivity extends Activity
} }
} }
public void configureProxyConfig(AccountCreator accountCreator) { private void configureProxyConfig(AccountCreator accountCreator) {
Core lc = LinphoneManager.getLc(); Core lc = LinphoneManager.getLc();
ProxyConfig proxyConfig = lc.createProxyConfig(); ProxyConfig proxyConfig = lc.createProxyConfig();
AuthInfo authInfo; AuthInfo authInfo;
@ -526,7 +526,7 @@ public class AssistantActivity extends Activity
} }
} }
public void displayMenu() { private void displayMenu() {
mFragment = new WelcomeFragment(); mFragment = new WelcomeFragment();
changeFragment(mFragment); changeFragment(mFragment);
country = null; country = null;
@ -617,7 +617,7 @@ public class AssistantActivity extends Activity
goToLinphoneActivity(); goToLinphoneActivity();
} }
public void saveCreatedAccount( private void saveCreatedAccount(
String username, String username,
String userid, String userid,
String password, String password,
@ -665,7 +665,7 @@ public class AssistantActivity extends Activity
} }
} }
public void displayRegistrationInProgressDialog() { private void displayRegistrationInProgressDialog() {
if (LinphoneManager.getLc().isNetworkReachable()) { if (LinphoneManager.getLc().isNetworkReachable()) {
mProgress = ProgressDialog.show(this, null, null); mProgress = ProgressDialog.show(this, null, null);
Drawable d = new ColorDrawable(ContextCompat.getColor(this, R.color.colorE)); Drawable d = new ColorDrawable(ContextCompat.getColor(this, R.color.colorE));
@ -741,7 +741,7 @@ public class AssistantActivity extends Activity
mBack.setVisibility(View.VISIBLE); mBack.setVisibility(View.VISIBLE);
} }
public void isAccountVerified(String username) { public void isAccountVerified() {
Toast.makeText(this, getString(R.string.assistant_account_validated), Toast.LENGTH_LONG) Toast.makeText(this, getString(R.string.assistant_account_validated), Toast.LENGTH_LONG)
.show(); .show();
hideKeyboard(); hideKeyboard();
@ -752,7 +752,7 @@ public class AssistantActivity extends Activity
launchDownloadCodec(); launchDownloadCodec();
} }
public Dialog createErrorDialog(ProxyConfig proxy, String message) { private Dialog createErrorDialog(ProxyConfig proxy, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this); AlertDialog.Builder builder = new AlertDialog.Builder(this);
if (message.equals("Forbidden")) { if (message.equals("Forbidden")) {
message = getString(R.string.assistant_error_bad_credentials); message = getString(R.string.assistant_error_bad_credentials);
@ -784,7 +784,7 @@ public class AssistantActivity extends Activity
public void success() { public void success() {
boolean needsEchoCalibration = LinphoneManager.getLc().isEchoCancellerCalibrationRequired(); boolean needsEchoCalibration = LinphoneManager.getLc().isEchoCancellerCalibrationRequired();
if (needsEchoCalibration && mPrefs.isFirstLaunch()) { if (needsEchoCalibration && mPrefs.isFirstLaunch()) {
launchEchoCancellerCalibration(true); launchEchoCancellerCalibration();
} else { } else {
launchDownloadCodec(); launchDownloadCodec();
} }
@ -896,11 +896,11 @@ public class AssistantActivity extends Activity
public class CountryListAdapter extends BaseAdapter implements Filterable { public class CountryListAdapter extends BaseAdapter implements Filterable {
private LayoutInflater mInflater; private LayoutInflater mInflater;
private DialPlan[] allCountries; private final DialPlan[] allCountries;
private List<DialPlan> filteredCountries; private List<DialPlan> filteredCountries;
private Context context; private final Context context;
public CountryListAdapter(Context ctx) { CountryListAdapter(Context ctx) {
context = ctx; context = ctx;
allCountries = Factory.instance().getDialPlans(); allCountries = Factory.instance().getDialPlans();
filteredCountries = new ArrayList<>(Arrays.asList(allCountries)); filteredCountries = new ArrayList<>(Arrays.asList(allCountries));
@ -964,7 +964,7 @@ public class AssistantActivity extends Activity
return new Filter() { return new Filter() {
@Override @Override
protected FilterResults performFiltering(CharSequence constraint) { protected FilterResults performFiltering(CharSequence constraint) {
ArrayList<DialPlan> filteredCountries = new ArrayList<DialPlan>(); ArrayList<DialPlan> filteredCountries = new ArrayList<>();
for (DialPlan c : allCountries) { for (DialPlan c : allCountries) {
if (c.getCountry().toLowerCase().contains(constraint) if (c.getCountry().toLowerCase().contains(constraint)
|| c.getCountryCallingCode().contains(constraint)) { || c.getCountryCallingCode().contains(constraint)) {

View file

@ -36,7 +36,7 @@ import org.linphone.core.tools.OpenH264DownloadHelper;
import org.linphone.core.tools.OpenH264DownloadHelperListener; import org.linphone.core.tools.OpenH264DownloadHelperListener;
public class CodecDownloaderFragment extends Fragment { public class CodecDownloaderFragment extends Fragment {
private Handler mHandler = new Handler(); private final Handler mHandler = new Handler();
private TextView mQuestion; private TextView mQuestion;
private TextView mDownloading; private TextView mDownloading;
private TextView mDownloaded; private TextView mDownloaded;

View file

@ -77,8 +77,7 @@ public class CountryListFragment extends Fragment
@Override @Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
DialPlan c = (DialPlan) view.getTag(); AssistantActivity.instance().country = (DialPlan) view.getTag();
AssistantActivity.instance().country = c;
AssistantActivity.instance().onBackPressed(); AssistantActivity.instance().onBackPressed();
} }

View file

@ -109,7 +109,7 @@ public class CreateAccountActivationFragment extends Fragment
.show(); .show();
} else if (status.equals(AccountCreator.Status.AccountActivated)) { } else if (status.equals(AccountCreator.Status.AccountActivated)) {
AssistantActivity.instance().linphoneLogIn(accountCreator); AssistantActivity.instance().linphoneLogIn(accountCreator);
AssistantActivity.instance().isAccountVerified(mUsername); AssistantActivity.instance().isAccountVerified();
} else { } else {
Toast.makeText( Toast.makeText(
getActivity(), getActivity(),

View file

@ -155,14 +155,14 @@ public class CreateAccountCodeActivationFragment extends Fragment
if (accountCreator.getUsername() != null) { if (accountCreator.getUsername() != null) {
AssistantActivity.instance().linphoneLogIn(accountCreator); AssistantActivity.instance().linphoneLogIn(accountCreator);
if (!mRecoverAccount) { if (!mRecoverAccount) {
AssistantActivity.instance().isAccountVerified(accountCreator.getUsername()); AssistantActivity.instance().isAccountVerified();
} else { } else {
AssistantActivity.instance().success(); AssistantActivity.instance().success();
} }
} else { } else {
AssistantActivity.instance().linphoneLogIn(accountCreator); AssistantActivity.instance().linphoneLogIn(accountCreator);
if (!mRecoverAccount) { if (!mRecoverAccount) {
AssistantActivity.instance().isAccountVerified(accountCreator.getPhoneNumber()); AssistantActivity.instance().isAccountVerified();
} else { } else {
AssistantActivity.instance().success(); AssistantActivity.instance().success();
} }

View file

@ -180,8 +180,8 @@ public class CreateAccountFragment extends Fragment
mUseUsername.setVisibility(View.VISIBLE); mUseUsername.setVisibility(View.VISIBLE);
mUseUsername.setOnCheckedChangeListener(this); mUseUsername.setOnCheckedChangeListener(this);
} }
addPhoneNumberHandler(mPhoneNumberEdit, null); addPhoneNumberHandler(mPhoneNumberEdit);
addPhoneNumberHandler(mDialCode, null); addPhoneNumberHandler(mDialCode);
} }
// Password & email address // Password & email address
@ -205,9 +205,9 @@ public class CreateAccountFragment extends Fragment
} }
} }
addPasswordHandler(mPasswordEdit, null); addPasswordHandler(mPasswordEdit);
addConfirmPasswordHandler(mPasswordEdit, mPasswordConfirmEdit, null); addConfirmPasswordHandler(mPasswordEdit, mPasswordConfirmEdit);
addEmailHandler(mEmailEdit, null); addEmailHandler(mEmailEdit);
} }
// Hide phone number and display username/email/password // Hide phone number and display username/email/password
@ -242,7 +242,7 @@ public class CreateAccountFragment extends Fragment
mAccountCreator.setLanguage(Locale.getDefault().toLanguageTag()); mAccountCreator.setLanguage(Locale.getDefault().toLanguageTag());
} }
addUsernameHandler(mUsernameEdit, null); addUsernameHandler(mUsernameEdit);
mCreateAccount.setEnabled(true); mCreateAccount.setEnabled(true);
mCreateAccount.setOnClickListener(this); mCreateAccount.setOnClickListener(this);
@ -472,7 +472,7 @@ public class CreateAccountFragment extends Fragment
return status; return status;
} }
public void onTextChanged2() { private void onTextChanged2() {
String msg = ""; String msg = "";
mAccountCreator.setUsername(getUsername()); mAccountCreator.setUsername(getUsername());
@ -532,7 +532,7 @@ public class CreateAccountFragment extends Fragment
mSipUri.setText(msg); mSipUri.setText(msg);
} }
private void addPhoneNumberHandler(final EditText field, final ImageView icon) { private void addPhoneNumberHandler(final EditText field) {
field.addTextChangedListener( field.addTextChangedListener(
new TextWatcher() { new TextWatcher() {
public void afterTextChanged(Editable s) { public void afterTextChanged(Editable s) {
@ -560,7 +560,7 @@ public class CreateAccountFragment extends Fragment
}); });
} }
private void addUsernameHandler(final EditText field, final ImageView icon) { private void addUsernameHandler(final EditText field) {
field.addTextChangedListener( field.addTextChangedListener(
new TextWatcher() { new TextWatcher() {
public void afterTextChanged(Editable s) { public void afterTextChanged(Editable s) {
@ -584,7 +584,7 @@ public class CreateAccountFragment extends Fragment
}); });
} }
private void addEmailHandler(final EditText field, final ImageView icon) { private void addEmailHandler(final EditText field) {
field.addTextChangedListener( field.addTextChangedListener(
new TextWatcher() { new TextWatcher() {
public void afterTextChanged(Editable s) { public void afterTextChanged(Editable s) {
@ -609,7 +609,7 @@ public class CreateAccountFragment extends Fragment
}); });
} }
private void addPasswordHandler(final EditText field1, final ImageView icon) { private void addPasswordHandler(final EditText field1) {
TextWatcher passwordListener = TextWatcher passwordListener =
new TextWatcher() { new TextWatcher() {
public void afterTextChanged(Editable s) { public void afterTextChanged(Editable s) {
@ -636,8 +636,7 @@ public class CreateAccountFragment extends Fragment
field1.addTextChangedListener(passwordListener); field1.addTextChangedListener(passwordListener);
} }
private void addConfirmPasswordHandler( private void addConfirmPasswordHandler(final EditText field1, final EditText field2) {
final EditText field1, final EditText field2, final ImageView icon) {
TextWatcher passwordListener = TextWatcher passwordListener =
new TextWatcher() { new TextWatcher() {
public void afterTextChanged(Editable s) { public void afterTextChanged(Editable s) {

View file

@ -29,7 +29,6 @@ import android.view.ViewGroup;
import org.linphone.LinphoneManager; import org.linphone.LinphoneManager;
import org.linphone.R; import org.linphone.R;
import org.linphone.core.Core; import org.linphone.core.Core;
import org.linphone.core.CoreException;
import org.linphone.core.CoreListenerStub; import org.linphone.core.CoreListenerStub;
import org.linphone.core.EcCalibratorStatus; import org.linphone.core.EcCalibratorStatus;
import org.linphone.core.XmlRpcArgType; import org.linphone.core.XmlRpcArgType;
@ -40,7 +39,7 @@ import org.linphone.mediastream.Log;
import org.linphone.settings.LinphonePreferences; import org.linphone.settings.LinphonePreferences;
public class EchoCancellerCalibrationFragment extends Fragment implements XmlRpcRequestListener { public class EchoCancellerCalibrationFragment extends Fragment implements XmlRpcRequestListener {
private Handler mHandler = new Handler(); private final Handler mHandler = new Handler();
private boolean mSendEcCalibrationResult = false; private boolean mSendEcCalibrationResult = false;
private CoreListenerStub mListener; private CoreListenerStub mListener;
private XmlRpcSession mXmlRpcSession; private XmlRpcSession mXmlRpcSession;
@ -80,13 +79,8 @@ public class EchoCancellerCalibrationFragment extends Fragment implements XmlRpc
mXmlRpcSession.createRequest(XmlRpcArgType.None, "add_ec_calibration_result"); mXmlRpcSession.createRequest(XmlRpcArgType.None, "add_ec_calibration_result");
mXmlRpcRequest.setListener(this); mXmlRpcRequest.setListener(this);
try { LinphoneManager.getLc().addListener(mListener);
LinphoneManager.getLc().addListener(mListener); LinphoneManager.getInstance().startEcCalibration();
LinphoneManager.getInstance().startEcCalibration();
} catch (CoreException e) {
Log.e(e, "Unable to calibrate EC");
AssistantActivity.instance().isEchoCalibrationFinished();
}
return view; return view;
} }

View file

@ -195,13 +195,13 @@ public class LinphoneLoginFragment extends Fragment
mAccountCreator.setLanguage(Locale.getDefault().toLanguageTag()); mAccountCreator.setLanguage(Locale.getDefault().toLanguageTag());
} }
addPhoneNumberHandler(mDialCode, null); addPhoneNumberHandler(mDialCode);
addPhoneNumberHandler(mPhoneNumberEdit, null); addPhoneNumberHandler(mPhoneNumberEdit);
return view; return view;
} }
public void linphoneLogIn() { private void linphoneLogIn() {
if (mLogin.getText() == null if (mLogin.getText() == null
|| mLogin.length() == 0 || mLogin.length() == 0
|| mPassword.getText() == null || mPassword.getText() == null
@ -222,7 +222,7 @@ public class LinphoneLoginFragment extends Fragment
mPhoneNumberEdit.getText().toString(), LinphoneUtils.getCountryCode(mDialCode)); mPhoneNumberEdit.getText().toString(), LinphoneUtils.getCountryCode(mDialCode));
} }
private void addPhoneNumberHandler(final EditText field, final ImageView icon) { private void addPhoneNumberHandler(final EditText field) {
field.addTextChangedListener( field.addTextChangedListener(
new TextWatcher() { new TextWatcher() {
public void afterTextChanged(Editable s) { public void afterTextChanged(Editable s) {
@ -253,8 +253,7 @@ public class LinphoneLoginFragment extends Fragment
@Override @Override
public void onResume() { public void onResume() {
super.onResume(); super.onResume();
if (mUseUsername != null && mUseUsername.isChecked()) mRecoverAccount = false; mRecoverAccount = mUseUsername == null || !mUseUsername.isChecked();
else mRecoverAccount = true;
} }
@Override @Override
@ -305,7 +304,7 @@ public class LinphoneLoginFragment extends Fragment
@Override @Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {} public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged2() { private void onTextChanged2() {
int status = getPhoneNumberStatus(); int status = getPhoneNumberStatus();
boolean isOk = status == AccountCreator.PhoneNumberStatus.Ok.toInt(); boolean isOk = status == AccountCreator.PhoneNumberStatus.Ok.toInt();
LinphoneUtils.displayError( LinphoneUtils.displayError(

View file

@ -66,12 +66,12 @@ public class QrCodeFragment extends Fragment {
} }
} }
private void setBackCamera(boolean useBackCamera) { private void setBackCamera() {
int camId = 0; int camId = 0;
AndroidCameraConfiguration.AndroidCamera[] cameras = AndroidCameraConfiguration.AndroidCamera[] cameras =
AndroidCameraConfiguration.retrieveCameras(); AndroidCameraConfiguration.retrieveCameras();
for (AndroidCameraConfiguration.AndroidCamera androidCamera : cameras) { for (AndroidCameraConfiguration.AndroidCamera androidCamera : cameras) {
if (androidCamera.frontFacing == !useBackCamera) camId = androidCamera.id; if (!androidCamera.frontFacing) camId = androidCamera.id;
} }
String[] devices = LinphoneManager.getLc().getVideoDevicesList(); String[] devices = LinphoneManager.getLc().getVideoDevicesList();
String newDevice = devices[camId]; String newDevice = devices[camId];
@ -79,7 +79,7 @@ public class QrCodeFragment extends Fragment {
} }
private void launchQrcodeReader() { private void launchQrcodeReader() {
setBackCamera(true); setBackCamera();
enableQrcodeReader(true); enableQrcodeReader(true);
} }

View file

@ -41,7 +41,7 @@ import org.linphone.mediastream.Log;
import org.linphone.settings.LinphonePreferences; import org.linphone.settings.LinphonePreferences;
public class RemoteProvisioningActivity extends Activity { public class RemoteProvisioningActivity extends Activity {
private Handler mHandler = new Handler(); private final Handler mHandler = new Handler();
private String mConfigUriParam = null; private String mConfigUriParam = null;
private ProgressBar mSpinner; private ProgressBar mSpinner;
private CoreListenerStub mListener; private CoreListenerStub mListener;
@ -92,11 +92,6 @@ public class RemoteProvisioningActivity extends Activity {
super.onPause(); super.onPause();
} }
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override @Override
protected void onNewIntent(Intent intent) { protected void onNewIntent(Intent intent) {
super.onNewIntent(intent); super.onNewIntent(intent);

View file

@ -75,17 +75,15 @@ public class RemoteProvisioningLoginActivity extends Activity implements OnClick
}; };
} }
private void cancelWizard(boolean bypassCheck) { private void cancelWizard() {
if (bypassCheck if (getResources().getBoolean(R.bool.allow_cancel_remote_provisioning_login_activity)) {
|| getResources()
.getBoolean(R.bool.allow_cancel_remote_provisioning_login_activity)) {
LinphonePreferences.instance().disableProvisioningLoginView(); LinphonePreferences.instance().disableProvisioningLoginView();
setResult(bypassCheck ? Activity.RESULT_OK : Activity.RESULT_CANCELED); setResult(Activity.RESULT_CANCELED);
finish(); finish();
} }
} }
private boolean storeAccount(String username, String password, String domain) { private void storeAccount(String username, String password, String domain) {
XmlRpcHelper xmlRpcHelper = new XmlRpcHelper(); XmlRpcHelper xmlRpcHelper = new XmlRpcHelper();
xmlRpcHelper.getRemoteProvisioningFilenameAsync( xmlRpcHelper.getRemoteProvisioningFilenameAsync(
new XmlRpcListenerBase() { new XmlRpcListenerBase() {
@ -95,14 +93,13 @@ public class RemoteProvisioningLoginActivity extends Activity implements OnClick
LinphoneManager.getInstance().restartCore(); LinphoneManager.getInstance().restartCore();
} }
}, },
username.toString(), username,
password.toString(), password,
domain.toString()); domain);
LinphonePreferences.instance().firstLaunchSuccessful(); LinphonePreferences.instance().firstLaunchSuccessful();
setResult(Activity.RESULT_OK); setResult(Activity.RESULT_OK);
finish(); finish();
return true;
} }
@Override @Override
@ -128,7 +125,7 @@ public class RemoteProvisioningLoginActivity extends Activity implements OnClick
int id = v.getId(); int id = v.getId();
if (id == R.id.cancel) { if (id == R.id.cancel) {
cancelWizard(false); cancelWizard();
} }
if (id == R.id.assistant_connect) { if (id == R.id.assistant_connect) {
storeAccount( storeAccount(
@ -140,6 +137,6 @@ public class RemoteProvisioningLoginActivity extends Activity implements OnClick
@Override @Override
public void onBackPressed() { public void onBackPressed() {
cancelWizard(false); cancelWizard();
} }
} }

View file

@ -20,17 +20,16 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/ */
import org.linphone.core.CallParams; import org.linphone.core.CallParams;
import org.linphone.core.Core;
public class BandwidthManager { public class BandwidthManager {
public static final int HIGH_RESOLUTION = 0; private static final int HIGH_RESOLUTION = 0;
public static final int LOW_RESOLUTION = 1; private static final int LOW_RESOLUTION = 1;
public static final int LOW_BANDWIDTH = 2; private static final int LOW_BANDWIDTH = 2;
private static BandwidthManager sInstance; private static BandwidthManager sInstance;
private int currentProfile = HIGH_RESOLUTION; private final int currentProfile = HIGH_RESOLUTION;
private BandwidthManager() { private BandwidthManager() {
// FIXME register a listener on NetworkManager to get notified of network state // FIXME register a listener on NetworkManager to get notified of network state
@ -39,12 +38,12 @@ public class BandwidthManager {
// FIXME initially get those values // FIXME initially get those values
} }
public static final synchronized BandwidthManager getInstance() { public static synchronized BandwidthManager getInstance() {
if (sInstance == null) sInstance = new BandwidthManager(); if (sInstance == null) sInstance = new BandwidthManager();
return sInstance; return sInstance;
} }
public void updateWithProfileSettings(Core lc, CallParams callParams) { public void updateWithProfileSettings(CallParams callParams) {
if (callParams != null) { // in call if (callParams != null) { // in call
// Update video parm if // Update video parm if
if (!isVideoPossible()) { // NO VIDEO if (!isVideoPossible()) { // NO VIDEO
@ -57,7 +56,7 @@ public class BandwidthManager {
} }
} }
public boolean isVideoPossible() { private boolean isVideoPossible() {
return currentProfile != LOW_BANDWIDTH; return currentProfile != LOW_BANDWIDTH;
} }
} }

View file

@ -29,7 +29,6 @@ import android.content.Intent;
import android.content.IntentFilter; import android.content.IntentFilter;
import android.content.pm.ActivityInfo; import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable; import android.graphics.drawable.Drawable;
import android.os.Bundle; import android.os.Bundle;
@ -58,7 +57,7 @@ import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat; import androidx.core.content.ContextCompat;
import androidx.drawerlayout.widget.DrawerLayout; import androidx.drawerlayout.widget.DrawerLayout;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import java.util.Arrays; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Timer; import java.util.Timer;
@ -149,7 +148,7 @@ public class CallActivity extends LinphoneGenericActivity
private CoreListenerStub mListener; private CoreListenerStub mListener;
private DrawerLayout mSideMenu; private DrawerLayout mSideMenu;
private Handler mHandler = new Handler(); private final Handler mHandler = new Handler();
private Timer mTimer; private Timer mTimer;
private TimerTask mTask; private TimerTask mTask;
private HashMap<String, String> mEncoderTexts; private HashMap<String, String> mEncoderTexts;
@ -225,7 +224,7 @@ public class CallActivity extends LinphoneGenericActivity
} }
} else if (state == State.Resuming) { } else if (state == State.Resuming) {
if (LinphonePreferences.instance().isVideoEnabled()) { if (LinphonePreferences.instance().isVideoEnabled()) {
mStatus.refreshStatusItems(call, isVideoEnabled(call)); mStatus.refreshStatusItems(call);
if (call.getCurrentParams().videoEnabled()) { if (call.getCurrentParams().videoEnabled()) {
showVideoView(); showVideoView();
} }
@ -239,7 +238,7 @@ public class CallActivity extends LinphoneGenericActivity
if (mStatus != null) { if (mStatus != null) {
mVideoProgress.setVisibility(View.GONE); mVideoProgress.setVisibility(View.GONE);
mStatus.refreshStatusItems(call, isVideoEnabled(call)); mStatus.refreshStatusItems(call);
} }
} else if (state == State.UpdatedByRemote) { } else if (state == State.UpdatedByRemote) {
// If the correspondent proposes mVideo while audio call // If the correspondent proposes mVideo while audio call
@ -279,8 +278,7 @@ public class CallActivity extends LinphoneGenericActivity
&& !call.getAuthenticationTokenVerified()) { && !call.getAuthenticationTokenVerified()) {
mStatus.showZRTPDialog(call); mStatus.showZRTPDialog(call);
} }
mStatus.refreshStatusItems( mStatus.refreshStatusItems(call);
call, call.getCurrentParams().videoEnabled());
} }
} }
}; };
@ -337,7 +335,7 @@ public class CallActivity extends LinphoneGenericActivity
} }
} }
public void createTimerForDialog(long time) { private void createTimerForDialog(long time) {
mCountDownTimer = mCountDownTimer =
new CountDownTimer(time, 1000) { new CountDownTimer(time, 1000) {
public void onTick(long millisUntilFinished) { public void onTick(long millisUntilFinished) {
@ -494,7 +492,7 @@ public class CallActivity extends LinphoneGenericActivity
LinphoneManager.getInstance().changeStatusToOnThePhone(); LinphoneManager.getInstance().changeStatusToOnThePhone();
} }
public void checkAndRequestPermission(String permission, int result) { private void checkAndRequestPermission(String permission, int result) {
int permissionGranted = getPackageManager().checkPermission(permission, getPackageName()); int permissionGranted = getPackageManager().checkPermission(permission, getPackageName());
Log.i( Log.i(
"[Permission] " "[Permission] "
@ -570,7 +568,7 @@ public class CallActivity extends LinphoneGenericActivity
} }
} }
public void createInCallStats() { private void createInCallStats() {
mSideMenu = findViewById(R.id.side_menu); mSideMenu = findViewById(R.id.side_menu);
mMenu = findViewById(R.id.call_quality); mMenu = findViewById(R.id.call_quality);
@ -596,7 +594,7 @@ public class CallActivity extends LinphoneGenericActivity
private void refreshIncallUi() { private void refreshIncallUi() {
refreshInCallActions(); refreshInCallActions();
refreshCallList(getResources()); refreshCallList();
enableAndRefreshInCallActions(); enableAndRefreshInCallActions();
displayMissedChats(); displayMissedChats();
} }
@ -713,10 +711,6 @@ public class CallActivity extends LinphoneGenericActivity
public void onClick(View v) { public void onClick(View v) {
int id = v.getId(); int id = v.getId();
if (isVideoEnabled(LinphoneManager.getLc().getCurrentCall())) {
// displayVideoCallControlsIfHidden();
}
if (id == R.id.video) { if (id == R.id.video) {
int camera = int camera =
getPackageManager() getPackageManager()
@ -868,7 +862,7 @@ public class CallActivity extends LinphoneGenericActivity
} }
} }
public void displayCustomToast(final String message, final int duration) { private void displayCustomToast(final String message, final int duration) {
LayoutInflater inflater = getLayoutInflater(); LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast, (ViewGroup) findViewById(R.id.toastRoot)); View layout = inflater.inflate(R.layout.toast, (ViewGroup) findViewById(R.id.toastRoot));
@ -962,6 +956,7 @@ public class CallActivity extends LinphoneGenericActivity
try { try {
transaction.commitAllowingStateLoss(); transaction.commitAllowingStateLoss();
} catch (Exception e) { } catch (Exception e) {
Log.e(e);
} }
} }
@ -974,6 +969,7 @@ public class CallActivity extends LinphoneGenericActivity
try { try {
transaction.commitAllowingStateLoss(); transaction.commitAllowingStateLoss();
} catch (Exception e) { } catch (Exception e) {
Log.e(e);
} }
} }
@ -984,7 +980,7 @@ public class CallActivity extends LinphoneGenericActivity
mMicro.setSelected(mIsMicMuted); mMicro.setSelected(mIsMicMuted);
} }
protected void toggleSpeaker() { private void toggleSpeaker() {
mIsSpeakerEnabled = !mIsSpeakerEnabled; mIsSpeakerEnabled = !mIsSpeakerEnabled;
if (LinphoneManager.getLc().getCurrentCall() != null) { if (LinphoneManager.getLc().getCurrentCall() != null) {
if (isVideoEnabled(LinphoneManager.getLc().getCurrentCall())) if (isVideoEnabled(LinphoneManager.getLc().getCurrentCall()))
@ -1001,7 +997,7 @@ public class CallActivity extends LinphoneGenericActivity
} }
} }
public void pauseOrResumeCall(Call call) { private void pauseOrResumeCall(Call call) {
Core lc = LinphoneManager.getLc(); Core lc = LinphoneManager.getLc();
if (call != null && LinphoneManager.getLc().getCurrentCall() == call) { if (call != null && LinphoneManager.getLc().getCurrentCall() == call) {
lc.pauseCall(call); lc.pauseCall(call);
@ -1037,7 +1033,7 @@ public class CallActivity extends LinphoneGenericActivity
} }
} }
public void displayVideoCall(boolean display) { private void displayVideoCall(boolean display) {
if (display) { if (display) {
showStatusBar(); showStatusBar();
mControlsLayout.setVisibility(View.VISIBLE); mControlsLayout.setVisibility(View.VISIBLE);
@ -1157,7 +1153,7 @@ public class CallActivity extends LinphoneGenericActivity
} }
} }
public void goBackToDialer() { private void goBackToDialer() {
Intent intent = new Intent(); Intent intent = new Intent();
intent.setClass(this, LinphoneActivity.class); intent.setClass(this, LinphoneActivity.class);
intent.putExtra("AddCall", true); intent.putExtra("AddCall", true);
@ -1178,7 +1174,7 @@ public class CallActivity extends LinphoneGenericActivity
startActivity(intent); startActivity(intent);
} }
public void acceptCallUpdate(boolean accept) { private void acceptCallUpdate(boolean accept) {
if (mCountDownTimer != null) { if (mCountDownTimer != null) {
mCountDownTimer.cancel(); mCountDownTimer.cancel();
} }
@ -1202,7 +1198,7 @@ public class CallActivity extends LinphoneGenericActivity
startActivity(new Intent(this, CallIncomingActivity.class)); startActivity(new Intent(this, CallIncomingActivity.class));
} }
public void hideStatusBar() { private void hideStatusBar() {
if (isTablet()) { if (isTablet()) {
return; return;
} }
@ -1211,7 +1207,7 @@ public class CallActivity extends LinphoneGenericActivity
findViewById(R.id.fragmentContainer).setPadding(0, 0, 0, 0); findViewById(R.id.fragmentContainer).setPadding(0, 0, 0, 0);
} }
public void showStatusBar() { private void showStatusBar() {
if (isTablet()) { if (isTablet()) {
return; return;
} }
@ -1324,7 +1320,7 @@ public class CallActivity extends LinphoneGenericActivity
private void handleViewIntent() { private void handleViewIntent() {
Intent intent = getIntent(); Intent intent = getIntent();
if (intent != null && intent.getAction() == "android.intent.action.VIEW") { if (intent != null && intent.getAction().equals("android.intent.action.VIEW")) {
Call call = LinphoneManager.getLc().getCurrentCall(); Call call = LinphoneManager.getLc().getCurrentCall();
if (call != null && isVideoEnabled(call)) { if (call != null && isVideoEnabled(call)) {
Player player = call.getPlayer(); Player player = call.getPlayer();
@ -1415,7 +1411,6 @@ public class CallActivity extends LinphoneGenericActivity
mDialog.dismiss(); mDialog.dismiss();
mDialog = null; mDialog = null;
} }
return;
} }
public void bindAudioFragment(CallAudioFragment fragment) { public void bindAudioFragment(CallAudioFragment fragment) {
@ -1434,7 +1429,7 @@ public class CallActivity extends LinphoneGenericActivity
registerCallDurationTimer(null, call); registerCallDurationTimer(null, call);
} }
private void displayPausedCalls(Resources resources, final Call call, int index) { private void displayPausedCalls(final Call call, int index) {
// Control Row // Control Row
LinearLayout callView; LinearLayout callView;
@ -1482,8 +1477,7 @@ public class CallActivity extends LinphoneGenericActivity
} }
} }
private boolean displayCallStatusIconAndReturnCallPaused(LinearLayout callView, Call call) { private void displayCallStatusIconAndReturnCallPaused(LinearLayout callView, Call call) {
boolean isCallPaused, isInConference;
ImageView onCallStateChanged = callView.findViewById(R.id.call_pause); ImageView onCallStateChanged = callView.findViewById(R.id.call_pause);
onCallStateChanged.setTag(call); onCallStateChanged.setTag(call);
onCallStateChanged.setOnClickListener(this); onCallStateChanged.setOnClickListener(this);
@ -1492,19 +1486,10 @@ public class CallActivity extends LinphoneGenericActivity
|| call.getState() == State.PausedByRemote || call.getState() == State.PausedByRemote
|| call.getState() == State.Pausing) { || call.getState() == State.Pausing) {
onCallStateChanged.setSelected(false); onCallStateChanged.setSelected(false);
isCallPaused = true;
isInConference = false;
} else if (call.getState() == State.OutgoingInit } else if (call.getState() == State.OutgoingInit
|| call.getState() == State.OutgoingProgress || call.getState() == State.OutgoingProgress
|| call.getState() == State.OutgoingRinging) { || call.getState() == State.OutgoingRinging) {
isCallPaused = false;
isInConference = false;
} else {
isInConference = mIsConferenceRunning && call.getConference() != null;
isCallPaused = false;
} }
return isCallPaused || isInConference;
} }
private void registerCallDurationTimer(View v, Call call) { private void registerCallDurationTimer(View v, Call call) {
@ -1528,11 +1513,11 @@ public class CallActivity extends LinphoneGenericActivity
timer.start(); timer.start();
} }
public void refreshCallList(Resources resources) { private void refreshCallList() {
mIsConferenceRunning = LinphoneManager.getLc().isInConference(); mIsConferenceRunning = LinphoneManager.getLc().isInConference();
List<Call> pausedCalls = List<Call> pausedCalls =
LinphoneUtils.getCallsInState( LinphoneUtils.getCallsInState(
LinphoneManager.getLc(), Arrays.asList(State.PausedByRemote)); LinphoneManager.getLc(), Collections.singletonList(State.PausedByRemote));
// MultiCalls // MultiCalls
if (LinphoneManager.getLc().getCallsNb() > 1) { if (LinphoneManager.getLc().getCallsNb() > 1) {
@ -1580,8 +1565,8 @@ public class CallActivity extends LinphoneGenericActivity
index++; index++;
} else { } else {
if (call != LinphoneManager.getLc().getCurrentCall() if (call != LinphoneManager.getLc().getCurrentCall()
&& !(call.getConference() != null)) { && call.getConference() == null) {
displayPausedCalls(resources, call, index); displayPausedCalls(call, index);
index++; index++;
} else { } else {
displayCurrentCall(call); displayCurrentCall(call);
@ -1592,7 +1577,7 @@ public class CallActivity extends LinphoneGenericActivity
if (!mIsConferenceRunning) { if (!mIsConferenceRunning) {
if (isConfPaused) { if (isConfPaused) {
mCallsList.setVisibility(View.VISIBLE); mCallsList.setVisibility(View.VISIBLE);
displayPausedCalls(resources, null, index); displayPausedCalls(null, index);
} }
} }
} }
@ -1622,7 +1607,7 @@ public class CallActivity extends LinphoneGenericActivity
LinphoneManager.getLc().addAllToConference(); LinphoneManager.getLc().addAllToConference();
} }
public void pauseOrResumeConference() { private void pauseOrResumeConference() {
Core lc = LinphoneManager.getLc(); Core lc = LinphoneManager.getLc();
mConferenceStatus = findViewById(R.id.conference_pause); mConferenceStatus = findViewById(R.id.conference_pause);
if (mConferenceStatus != null) { if (mConferenceStatus != null) {
@ -1634,7 +1619,7 @@ public class CallActivity extends LinphoneGenericActivity
lc.enterConference(); lc.enterConference();
} }
} }
refreshCallList(getResources()); refreshCallList();
} }
private void displayConferenceParticipant(int index, final Call call) { private void displayConferenceParticipant(int index, final Call call) {
@ -1838,7 +1823,7 @@ public class CallActivity extends LinphoneGenericActivity
} }
} }
public void initCallStatsRefresher(final Call call, final View view) { private void initCallStatsRefresher(final Call call, final View view) {
if (mCallDisplayedInStats == call) return; if (mCallDisplayedInStats == call) return;
if (mTimer != null && mTask != null) { if (mTimer != null && mTask != null) {

View file

@ -30,8 +30,7 @@ public class CallAudioFragment extends Fragment {
@Override @Override
public View onCreateView( public View onCreateView(
LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.audio, container, false); return inflater.inflate(R.layout.audio, container, false);
return view;
} }
@Override @Override

View file

@ -267,7 +267,7 @@ public class CallIncomingActivity extends LinphoneGenericActivity {
} }
private void checkAndRequestCallPermissions() { private void checkAndRequestCallPermissions() {
ArrayList<String> permissionsList = new ArrayList<String>(); ArrayList<String> permissionsList = new ArrayList<>();
int recordAudio = int recordAudio =
getPackageManager() getPackageManager()

View file

@ -34,7 +34,7 @@ public class CallManager {
private static CallManager sInstance; private static CallManager sInstance;
public static final synchronized CallManager getInstance() { public static synchronized CallManager getInstance() {
if (sInstance == null) sInstance = new CallManager(); if (sInstance == null) sInstance = new CallManager();
return sInstance; return sInstance;
} }
@ -57,7 +57,7 @@ public class CallManager {
Core lc = LinphoneManager.getLc(); Core lc = LinphoneManager.getLc();
CallParams params = lc.createCallParams(null); CallParams params = lc.createCallParams(null);
getBandwidthManager().updateWithProfileSettings(lc, params); getBandwidthManager().updateWithProfileSettings(params);
if (videoEnabled && params.videoEnabled()) { if (videoEnabled && params.videoEnabled()) {
params.enableVideo(true); params.enableVideo(true);
@ -96,7 +96,7 @@ public class CallManager {
if (params.videoEnabled()) return false; if (params.videoEnabled()) return false;
// Check if video possible regarding bandwidth limitations // Check if video possible regarding bandwidth limitations
getBandwidthManager().updateWithProfileSettings(lc, params); getBandwidthManager().updateWithProfileSettings(params);
// Abort if not enough bandwidth... // Abort if not enough bandwidth...
if (!params.videoEnabled()) { if (!params.videoEnabled()) {
@ -121,7 +121,7 @@ public class CallManager {
return; return;
} }
CallParams params = lc.createCallParams(lCall); CallParams params = lc.createCallParams(lCall);
getBandwidthManager().updateWithProfileSettings(lc, params); getBandwidthManager().updateWithProfileSettings(params);
lc.updateCall(lCall, null); lc.updateCall(lCall, null);
} }
} }

View file

@ -61,10 +61,6 @@ public class CallOutgoingActivity extends LinphoneGenericActivity implements OnC
private CoreListenerStub mListener; private CoreListenerStub mListener;
private boolean mIsMicMuted, mIsSpeakerEnabled; private boolean mIsMicMuted, mIsSpeakerEnabled;
public static CallOutgoingActivity instance() {
return sInstance;
}
public static boolean isInstanciated() { public static boolean isInstanciated() {
return sInstance != null; return sInstance != null;
} }
@ -152,7 +148,6 @@ public class CallOutgoingActivity extends LinphoneGenericActivity implements OnC
if (LinphoneManager.getLc().getCallsNb() == 0) { if (LinphoneManager.getLc().getCallsNb() == 0) {
finish(); finish();
return;
} }
} }
}; };
@ -266,7 +261,7 @@ public class CallOutgoingActivity extends LinphoneGenericActivity implements OnC
return super.onKeyDown(keyCode, event); return super.onKeyDown(keyCode, event);
} }
public void displayCustomToast(final String message, final int duration) { private void displayCustomToast(final String message, final int duration) {
LayoutInflater inflater = getLayoutInflater(); LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast, (ViewGroup) findViewById(R.id.toastRoot)); View layout = inflater.inflate(R.layout.toast, (ViewGroup) findViewById(R.id.toastRoot));
@ -286,7 +281,7 @@ public class CallOutgoingActivity extends LinphoneGenericActivity implements OnC
} }
private void checkAndRequestCallPermissions() { private void checkAndRequestCallPermissions() {
ArrayList<String> permissionsList = new ArrayList<String>(); ArrayList<String> permissionsList = new ArrayList<>();
int recordAudio = int recordAudio =
getPackageManager() getPackageManager()

View file

@ -19,7 +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. Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/ */
import android.content.Context;
import android.view.View; import android.view.View;
import android.widget.Button; import android.widget.Button;
import android.widget.CheckBox; import android.widget.CheckBox;
@ -36,40 +35,37 @@ public class ChatMessageOldViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener { implements View.OnClickListener {
public String messageId; public String messageId;
public ChatMessage message; public ChatMessage message;
public LinearLayout eventLayout; public final LinearLayout eventLayout;
public TextView eventMessage; public final TextView eventMessage;
public RelativeLayout bubbleLayout; public final RelativeLayout bubbleLayout;
public LinearLayout separatorLayout; public final LinearLayout separatorLayout;
public LinearLayout background; public final LinearLayout background;
public RelativeLayout avatarLayout; public final RelativeLayout avatarLayout;
public TextView contactName; public final TextView contactName;
public ImageView messageStatus; public final ImageView messageStatus;
public ProgressBar messageSendingInProgress; public final ProgressBar messageSendingInProgress;
public LinearLayout imdmLayout; public final LinearLayout imdmLayout;
public ImageView imdmIcon; public final ImageView imdmIcon;
public TextView imdmLabel; public final TextView imdmLabel;
public TextView messageText; public final TextView messageText;
public ImageView messageImage; public final ImageView messageImage;
public RelativeLayout fileTransferLayout; public final RelativeLayout fileTransferLayout;
public ProgressBar fileTransferProgressBar; public final ProgressBar fileTransferProgressBar;
public Button fileTransferAction; public final Button fileTransferAction;
public TextView fileName; public final TextView fileName;
public Button openFileButton; public final Button openFileButton;
public CheckBox delete; public final CheckBox delete;
private Context mContext;
private ChatMessageViewHolderClickListener mListener; private ChatMessageViewHolderClickListener mListener;
public ChatMessageOldViewHolder( public ChatMessageOldViewHolder(View view, ChatMessageViewHolderClickListener listener) {
Context context, View view, ChatMessageViewHolderClickListener listener) {
this(view); this(view);
mContext = context;
mListener = listener; mListener = listener;
view.setOnClickListener(this); view.setOnClickListener(this);
} }

View file

@ -61,28 +61,27 @@ import org.linphone.views.BitmapWorkerTask;
import org.linphone.views.ContactAvatar; import org.linphone.views.ContactAvatar;
public class ChatMessageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { public class ChatMessageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ChatMessage message;
public LinearLayout eventLayout; public final LinearLayout eventLayout;
public TextView eventMessage; public final TextView eventMessage;
public LinearLayout securityEventLayout; public final LinearLayout securityEventLayout;
public TextView securityEventMessage; public final TextView securityEventMessage;
public View rightAnchor; public final View rightAnchor;
public RelativeLayout bubbleLayout; public final RelativeLayout bubbleLayout;
public LinearLayout background; public final LinearLayout background;
public RelativeLayout avatarLayout; public final RelativeLayout avatarLayout;
public ProgressBar sendInProgress; public final ProgressBar sendInProgress;
public TextView timeText; public final TextView timeText;
public ImageView outgoingImdn; public final ImageView outgoingImdn;
public TextView messageText; public final TextView messageText;
public FlexboxLayout pictures; public final FlexboxLayout pictures;
public CheckBox deleteEvent; public final CheckBox deleteEvent;
public CheckBox deleteMessage; public final CheckBox deleteMessage;
private Context mContext; private Context mContext;
private ChatMessageViewHolderClickListener mListener; private ChatMessageViewHolderClickListener mListener;
@ -356,7 +355,7 @@ public class ChatMessageViewHolder extends RecyclerView.ViewHolder implements Vi
if (bitmapWorkerTask != null) { if (bitmapWorkerTask != null) {
final String bitmapData = bitmapWorkerTask.path; final String bitmapData = bitmapWorkerTask.path;
// If bitmapData is not yet set or it differs from the new data // If bitmapData is not yet set or it differs from the new data
if (bitmapData == null || bitmapData != path) { if (bitmapData == null || !bitmapData.equals(path)) {
// Cancel previous task // Cancel previous task
bitmapWorkerTask.cancel(true); bitmapWorkerTask.cancel(true);
} else { } else {

View file

@ -19,6 +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. Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/ */
public interface ChatMessageViewHolderClickListener { interface ChatMessageViewHolderClickListener {
void onItemClicked(int position); void onItemClicked(int position);
} }

View file

@ -41,17 +41,17 @@ import org.linphone.utils.SelectableHelper;
public class ChatMessagesAdapter extends SelectableAdapter<ChatMessageViewHolder> public class ChatMessagesAdapter extends SelectableAdapter<ChatMessageViewHolder>
implements ChatMessagesGenericAdapter { implements ChatMessagesGenericAdapter {
public static int MAX_TIME_TO_GROUP_MESSAGES = 60; private static final int MAX_TIME_TO_GROUP_MESSAGES = 60;
private Context mContext; private final Context mContext;
private List<EventLog> mHistory; private List<EventLog> mHistory;
private List<LinphoneContact> mParticipants; private List<LinphoneContact> mParticipants;
private int mItemResource; private final int mItemResource;
private ChatMessagesFragment mFragment; private final ChatMessagesFragment mFragment;
private List<ChatMessage> mTransientMessages; private final List<ChatMessage> mTransientMessages;
private ChatMessageViewHolderClickListener mClickListener; private final ChatMessageViewHolderClickListener mClickListener;
public ChatMessagesAdapter( public ChatMessagesAdapter(
ChatMessagesFragment fragment, ChatMessagesFragment fragment,
@ -292,10 +292,6 @@ public class ChatMessagesAdapter extends SelectableAdapter<ChatMessageViewHolder
mHistory.clear(); mHistory.clear();
} }
public int getCount() {
return mHistory.size();
}
public Object getItem(int i) { public Object getItem(int i) {
return mHistory.get(i); return mHistory.get(i);
} }

View file

@ -99,7 +99,7 @@ public class ChatMessagesFragment extends Fragment
private static final int ADD_PHOTO = 1337; private static final int ADD_PHOTO = 1337;
private static final int MESSAGES_PER_PAGE = 20; private static final int MESSAGES_PER_PAGE = 20;
private Handler mHandler = new Handler(Looper.getMainLooper()); private final Handler mHandler = new Handler(Looper.getMainLooper());
private ImageView mBackButton, mCallButton, mBackToCallButton, mGroupInfosButton; private ImageView mBackButton, mCallButton, mBackToCallButton, mGroupInfosButton;
private ImageView mAttachImageButton, mSendMessageButton; private ImageView mAttachImageButton, mSendMessageButton;
private TextView mRoomLabel, mParticipantsLabel, mRemoteComposing; private TextView mRoomLabel, mParticipantsLabel, mRemoteComposing;
@ -192,7 +192,7 @@ public class ChatMessagesFragment extends Fragment
public void onClick(View view) { public void onClick(View view) {
LinphoneActivity.instance() LinphoneActivity.instance()
.setAddresGoToDialerAndCall( .setAddresGoToDialerAndCall(
mRemoteParticipantAddress.asString(), null, null); mRemoteParticipantAddress.asString(), null);
} }
}); });
@ -232,9 +232,7 @@ public class ChatMessagesFragment extends Fragment
mRemoteSipAddress.asString(), mRemoteSipAddress.asString(),
participants, participants,
mChatRoom.getSubject(), mChatRoom.getSubject(),
mChatRoom.getMe() != null mChatRoom.getMe() != null && mChatRoom.getMe().isAdmin(),
? mChatRoom.getMe().isAdmin()
: false,
false, false,
null, null,
mChatRoom.hasCapability( mChatRoom.hasCapability(
@ -305,7 +303,7 @@ public class ChatMessagesFragment extends Fragment
mChatScrollListener = mChatScrollListener =
new ChatScrollListener(layoutManager) { new ChatScrollListener(layoutManager) {
@Override @Override
public void onLoadMore(int page, int totalItemsCount, RecyclerView view) { public void onLoadMore(int totalItemsCount) {
loadMoreData(totalItemsCount); loadMoreData(totalItemsCount);
} }
}; };
@ -644,13 +642,13 @@ public class ChatMessagesFragment extends Fragment
.removeOnGlobalLayoutListener(mKeyboardListener); .removeOnGlobalLayoutListener(mKeyboardListener);
} }
public void showKeyboardVisibleMode() { private void showKeyboardVisibleMode() {
LinphoneActivity.instance().hideTabBar(true); LinphoneActivity.instance().hideTabBar(true);
LinphoneActivity.instance().hideStatusBar(); LinphoneActivity.instance().hideStatusBar();
mTopBar.setVisibility(View.GONE); mTopBar.setVisibility(View.GONE);
} }
public void hideKeyboardVisibleMode() { private void hideKeyboardVisibleMode() {
LinphoneActivity.instance() LinphoneActivity.instance()
.hideTabBar( .hideTabBar(
getResources().getBoolean(R.bool.hide_bottom_bar_on_second_level_views)); getResources().getBoolean(R.bool.hide_bottom_bar_on_second_level_views));
@ -883,11 +881,11 @@ public class ChatMessagesFragment extends Fragment
dialog.show(); dialog.show();
} }
public void scrollToBottom() { private void scrollToBottom() {
mChatEventsList.getLayoutManager().scrollToPosition(0); mChatEventsList.getLayoutManager().scrollToPosition(0);
} }
public String getRemoteSipUri() { private String getRemoteSipUri() {
return mRemoteSipUri; return mRemoteSipUri;
} }
@ -911,7 +909,7 @@ public class ChatMessagesFragment extends Fragment
super.onSaveInstanceState(outState); super.onSaveInstanceState(outState);
} }
public void onRestoreInstanceState(Bundle savedInstanceState) { private void onRestoreInstanceState(Bundle savedInstanceState) {
String files[] = savedInstanceState.getStringArray("Files"); String files[] = savedInstanceState.getStringArray("Files");
if (files.length > 0) { if (files.length > 0) {
for (String file : files) { for (String file : files) {
@ -1352,8 +1350,7 @@ public class ChatMessagesFragment extends Fragment
// This is a workaround to prevent a crash from happening while rotating the device // This is a workaround to prevent a crash from happening while rotating the device
private class LinphoneLinearLayoutManager extends LinearLayoutManager { private class LinphoneLinearLayoutManager extends LinearLayoutManager {
public LinphoneLinearLayoutManager( LinphoneLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout); super(context, orientation, reverseLayout);
} }

View file

@ -23,7 +23,7 @@ import java.util.ArrayList;
import org.linphone.contacts.LinphoneContact; import org.linphone.contacts.LinphoneContact;
import org.linphone.core.EventLog; import org.linphone.core.EventLog;
public interface ChatMessagesGenericAdapter { interface ChatMessagesGenericAdapter {
void addToHistory(EventLog log); void addToHistory(EventLog log);
void addAllToHistory(ArrayList<EventLog> logs); void addAllToHistory(ArrayList<EventLog> logs);

View file

@ -67,17 +67,17 @@ import org.linphone.views.ContactAvatar;
public class ChatMessagesOldAdapter extends SelectableAdapter<ChatMessageOldViewHolder> public class ChatMessagesOldAdapter extends SelectableAdapter<ChatMessageOldViewHolder>
implements ChatMessagesGenericAdapter { implements ChatMessagesGenericAdapter {
private static int MARGIN_BETWEEN_MESSAGES = 10; private static final int MARGIN_BETWEEN_MESSAGES = 10;
private static int SIDE_MARGIN = 100; private static final int SIDE_MARGIN = 100;
private Context mContext; private final Context mContext;
private List<EventLog> mHistory; private List<EventLog> mHistory;
private List<LinphoneContact> mParticipants; private List<LinphoneContact> mParticipants;
private int mItemResource; private final int mItemResource;
private Bitmap mDefaultBitmap; private Bitmap mDefaultBitmap;
private ChatMessagesFragment mFragment; private final ChatMessagesFragment mFragment;
private ChatMessageListenerStub mListener; private final ChatMessageListenerStub mListener;
private ChatMessageViewHolderClickListener mClickListener; private final ChatMessageViewHolderClickListener mClickListener;
public ChatMessagesOldAdapter( public ChatMessagesOldAdapter(
ChatMessagesFragment fragment, ChatMessagesFragment fragment,
@ -140,7 +140,7 @@ public class ChatMessagesOldAdapter extends SelectableAdapter<ChatMessageOldView
@Override @Override
public ChatMessageOldViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { public ChatMessageOldViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(mItemResource, parent, false); View v = LayoutInflater.from(parent.getContext()).inflate(mItemResource, parent, false);
ChatMessageOldViewHolder VH = new ChatMessageOldViewHolder(mContext, v, mClickListener); ChatMessageOldViewHolder VH = new ChatMessageOldViewHolder(v, mClickListener);
// Allows onLongClick ContextMenu on bubbles // Allows onLongClick ContextMenu on bubbles
mFragment.registerForContextMenu(v); mFragment.registerForContextMenu(v);
@ -548,10 +548,6 @@ public class ChatMessagesOldAdapter extends SelectableAdapter<ChatMessageOldView
mHistory.clear(); mHistory.clear();
} }
public int getCount() {
return mHistory.size();
}
public Object getItem(int i) { public Object getItem(int i) {
return mHistory.get(i); return mHistory.get(i);
} }
@ -652,7 +648,7 @@ public class ChatMessagesOldAdapter extends SelectableAdapter<ChatMessageOldView
if (bitmapWorkerTask != null) { if (bitmapWorkerTask != null) {
final String bitmapData = bitmapWorkerTask.path; final String bitmapData = bitmapWorkerTask.path;
// If bitmapData is not yet set or it differs from the new data // If bitmapData is not yet set or it differs from the new data
if (bitmapData == null || bitmapData != path) { if (bitmapData == null || !bitmapData.equals(path)) {
// Cancel previous task // Cancel previous task
bitmapWorkerTask.cancel(true); bitmapWorkerTask.cancel(true);
} else { } else {

View file

@ -46,7 +46,8 @@ import org.linphone.R;
import org.linphone.contacts.ContactAddress; import org.linphone.contacts.ContactAddress;
import org.linphone.contacts.ContactsManager; import org.linphone.contacts.ContactsManager;
import org.linphone.contacts.ContactsUpdatedListener; import org.linphone.contacts.ContactsUpdatedListener;
import org.linphone.contacts.SearchContactsListAdapter; import org.linphone.contacts.SearchContactViewHolder;
import org.linphone.contacts.SearchContactsAdapter;
import org.linphone.core.Address; import org.linphone.core.Address;
import org.linphone.core.ChatRoom; import org.linphone.core.ChatRoom;
import org.linphone.core.ChatRoomListenerStub; import org.linphone.core.ChatRoomListenerStub;
@ -59,7 +60,7 @@ import org.linphone.views.ContactSelectView;
public class ChatRoomCreationFragment extends Fragment public class ChatRoomCreationFragment extends Fragment
implements View.OnClickListener, implements View.OnClickListener,
SearchContactsListAdapter.ViewHolder.ClickListener, SearchContactViewHolder.ClickListener,
ContactsUpdatedListener { ContactsUpdatedListener {
private RecyclerView mContactsList; private RecyclerView mContactsList;
private LinearLayout mContactsSelectedLayout; private LinearLayout mContactsSelectedLayout;
@ -71,7 +72,7 @@ public class ChatRoomCreationFragment extends Fragment
private RelativeLayout mSearchLayout, mWaitLayout, mLinphoneContactsToggle, mAllContactsToggle; private RelativeLayout mSearchLayout, mWaitLayout, mLinphoneContactsToggle, mAllContactsToggle;
private SearchView mSearchField; private SearchView mSearchField;
private ProgressBar mContactsFetchInProgress; private ProgressBar mContactsFetchInProgress;
private SearchContactsListAdapter mSearchAdapter; private SearchContactsAdapter mSearchAdapter;
private String mChatRoomSubject, mChatRoomAddress; private String mChatRoomSubject, mChatRoomAddress;
private ChatRoom mChatRoom; private ChatRoom mChatRoom;
private ChatRoomListenerStub mChatRoomCreationListener; private ChatRoomListenerStub mChatRoomCreationListener;
@ -132,8 +133,8 @@ public class ChatRoomCreationFragment extends Fragment
mContactsFetchInProgress.setVisibility(View.VISIBLE); mContactsFetchInProgress.setVisibility(View.VISIBLE);
mSearchAdapter = mSearchAdapter =
new SearchContactsListAdapter( new SearchContactsAdapter(
null, mContactsFetchInProgress, this, mCreateGroupChatRoom == false); null, mContactsFetchInProgress, this, !mCreateGroupChatRoom);
mSearchField = view.findViewById(R.id.searchField); mSearchField = view.findViewById(R.id.searchField);
mSearchField.setOnQueryTextListener( mSearchField.setOnQueryTextListener(
@ -214,8 +215,7 @@ public class ChatRoomCreationFragment extends Fragment
updateListSelected(); updateListSelected();
} }
mOnlyDisplayLinphoneContacts = mOnlyDisplayLinphoneContacts = ContactsManager.getInstance().getSIPContacts().size() > 0;
ContactsManager.getInstance().getSIPContacts().size() > 0 ? true : false;
if (savedInstanceState != null) { if (savedInstanceState != null) {
mOnlyDisplayLinphoneContacts = savedInstanceState.getBoolean("onlySipContact", true); mOnlyDisplayLinphoneContacts = savedInstanceState.getBoolean("onlySipContact", true);
} }
@ -431,7 +431,7 @@ public class ChatRoomCreationFragment extends Fragment
@Override @Override
public void onSaveInstanceState(Bundle outState) { public void onSaveInstanceState(Bundle outState) {
if (mContactsSelected != null && mContactsSelected.size() > 0) { if (mContactsSelected != null && mContactsSelected.size() > 0) {
ArrayList<String> listUri = new ArrayList<String>(); ArrayList<String> listUri = new ArrayList<>();
for (ContactAddress ca : mContactsSelected) { for (ContactAddress ca : mContactsSelected) {
listUri.add(ca.getAddressAsDisplayableString()); listUri.add(ca.getAddressAsDisplayableString());
} }
@ -507,7 +507,7 @@ public class ChatRoomCreationFragment extends Fragment
Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull(); Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
ProxyConfig lpc = lc.getDefaultProxyConfig(); ProxyConfig lpc = lc.getDefaultProxyConfig();
boolean createEncryptedChatRoom = mSecurityToggle.isChecked(); boolean createEncryptedChatRoom = mSecurityToggle.isChecked();
if (lpc == null || lpc.getConferenceFactoryUri() == null || mCreateGroupChatRoom == false) { if (lpc == null || lpc.getConferenceFactoryUri() == null || !mCreateGroupChatRoom) {
if (createEncryptedChatRoom && lpc != null && lpc.getConferenceFactoryUri() != null) { if (createEncryptedChatRoom && lpc != null && lpc.getConferenceFactoryUri() != null) {
mChatRoom = mChatRoom =
lc.findOneToOneChatRoom(lpc.getIdentityAddress(), ca.getAddress(), true); lc.findOneToOneChatRoom(lpc.getIdentityAddress(), ca.getAddress(), true);

View file

@ -39,16 +39,16 @@ import org.linphone.views.ContactAvatar;
public class ChatRoomViewHolder extends RecyclerView.ViewHolder public class ChatRoomViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener, View.OnLongClickListener { implements View.OnClickListener, View.OnLongClickListener {
public TextView lastMessageView; public final TextView lastMessageView;
public TextView date; public final TextView date;
public TextView displayName; public final TextView displayName;
public TextView unreadMessages; public final TextView unreadMessages;
public CheckBox delete; public final CheckBox delete;
public RelativeLayout avatarLayout; public final RelativeLayout avatarLayout;
public ChatRoom room; public ChatRoom room;
private Context mContext; private final Context mContext;
private ClickListener mListener; private final ClickListener mListener;
public ChatRoomViewHolder(Context context, View itemView, ClickListener listener) { public ChatRoomViewHolder(Context context, View itemView, ClickListener listener) {
super(itemView); super(itemView);
@ -71,12 +71,12 @@ public class ChatRoomViewHolder extends RecyclerView.ViewHolder
ChatMessage lastMessage = this.room.getLastMessageInHistory(); ChatMessage lastMessage = this.room.getLastMessageInHistory();
if (lastMessage != null) { if (lastMessage != null) {
String messageContent = ""; StringBuilder messageContent = new StringBuilder();
for (Content c : lastMessage.getContents()) { for (Content c : lastMessage.getContents()) {
if (c.isFile() || c.isFileTransfer()) { if (c.isFile() || c.isFileTransfer()) {
messageContent += c.getName() + " "; messageContent.append(c.getName()).append(" ");
} else if (c.isText()) { } else if (c.isText()) {
messageContent = c.getStringBuffer() + " " + messageContent; messageContent.insert(0, c.getStringBuffer() + " ");
} }
} }
lastMessageView.setText(getSender(this.room) + messageContent); lastMessageView.setText(getSender(this.room) + messageContent);

View file

@ -34,10 +34,10 @@ import org.linphone.utils.SelectableAdapter;
import org.linphone.utils.SelectableHelper; import org.linphone.utils.SelectableHelper;
public class ChatRoomsAdapter extends SelectableAdapter<ChatRoomViewHolder> { public class ChatRoomsAdapter extends SelectableAdapter<ChatRoomViewHolder> {
private Context mContext; private final Context mContext;
public List<ChatRoom> mRooms; private List<ChatRoom> mRooms;
private int mItemResource; private final int mItemResource;
private ChatRoomViewHolder.ClickListener mClickListener; private final ChatRoomViewHolder.ClickListener mClickListener;
public ChatRoomsAdapter( public ChatRoomsAdapter(
Context context, Context context,

View file

@ -22,20 +22,18 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.RecyclerView;
public abstract class ChatScrollListener extends RecyclerView.OnScrollListener { abstract class ChatScrollListener extends RecyclerView.OnScrollListener {
// The minimum amount of items to have below your current scroll position // The minimum amount of items to have below your current scroll position
// before mLoading more. // before mLoading more.
private int mVisibleThreshold = 5; private final int mVisibleThreshold = 5;
// The current offset index of data you have loaded
private int mCurrentPage = 0;
// The total number of items in the dataset after the last load // The total number of items in the dataset after the last load
private int mPreviousTotalItemCount = 0; private int mPreviousTotalItemCount = 0;
// True if we are still waiting for the last set of data to load. // True if we are still waiting for the last set of data to load.
private boolean mLoading = true; private boolean mLoading = true;
// Sets the starting page index // Sets the starting page index
private int mStartingPageIndex = 0; private final int mStartingPageIndex = 0;
private LinearLayoutManager mLayoutManager; private final LinearLayoutManager mLayoutManager;
public ChatScrollListener(LinearLayoutManager layoutManager) { public ChatScrollListener(LinearLayoutManager layoutManager) {
mLayoutManager = layoutManager; mLayoutManager = layoutManager;
@ -46,7 +44,7 @@ public abstract class ChatScrollListener extends RecyclerView.OnScrollListener {
// but first we check if we are waiting for the previous load to finish. // but first we check if we are waiting for the previous load to finish.
@Override @Override
public void onScrolled(RecyclerView view, int dx, int dy) { public void onScrolled(RecyclerView view, int dx, int dy) {
int lastVisibleItemPosition = 0; int lastVisibleItemPosition;
int totalItemCount = mLayoutManager.getItemCount(); int totalItemCount = mLayoutManager.getItemCount();
lastVisibleItemPosition = mLayoutManager.findLastVisibleItemPosition(); lastVisibleItemPosition = mLayoutManager.findLastVisibleItemPosition();
@ -54,7 +52,6 @@ public abstract class ChatScrollListener extends RecyclerView.OnScrollListener {
// If the total item count is zero and the previous isn't, assume the // If the total item count is zero and the previous isn't, assume the
// list is invalidated and should be reset back to initial state // list is invalidated and should be reset back to initial state
if (totalItemCount < mPreviousTotalItemCount) { if (totalItemCount < mPreviousTotalItemCount) {
this.mCurrentPage = this.mStartingPageIndex;
this.mPreviousTotalItemCount = totalItemCount; this.mPreviousTotalItemCount = totalItemCount;
if (totalItemCount == 0) { if (totalItemCount == 0) {
this.mLoading = true; this.mLoading = true;
@ -73,12 +70,11 @@ public abstract class ChatScrollListener extends RecyclerView.OnScrollListener {
// If we do need to reload some more data, we execute onLoadMore to fetch the data. // If we do need to reload some more data, we execute onLoadMore to fetch the data.
// threshold should reflect how many total columns there are too // threshold should reflect how many total columns there are too
if (!mLoading && (lastVisibleItemPosition + mVisibleThreshold) > totalItemCount) { if (!mLoading && (lastVisibleItemPosition + mVisibleThreshold) > totalItemCount) {
mCurrentPage++; onLoadMore(totalItemCount);
onLoadMore(mCurrentPage, totalItemCount, view);
mLoading = true; mLoading = true;
} }
} }
// Defines the process for actually mLoading more data based on page // Defines the process for actually mLoading more data based on page
public abstract void onLoadMore(int page, int totalItemsCount, RecyclerView view); protected abstract void onLoadMore(int totalItemsCount);
} }

View file

@ -24,9 +24,9 @@ import android.widget.ImageView;
import android.widget.TextView; import android.widget.TextView;
import org.linphone.R; import org.linphone.R;
public class DeviceChildViewHolder { class DeviceChildViewHolder {
public TextView deviceName; public final TextView deviceName;
public ImageView securityLevel; public final ImageView securityLevel;
public DeviceChildViewHolder(View v) { public DeviceChildViewHolder(View v) {
deviceName = v.findViewById(R.id.name); deviceName = v.findViewById(R.id.name);

View file

@ -25,10 +25,10 @@ import android.widget.RelativeLayout;
import android.widget.TextView; import android.widget.TextView;
import org.linphone.R; import org.linphone.R;
public class DeviceGroupViewHolder { class DeviceGroupViewHolder {
public RelativeLayout avatarLayout; public final RelativeLayout avatarLayout;
public TextView participantName; public final TextView participantName;
public ImageView groupExpander; public final ImageView groupExpander;
public DeviceGroupViewHolder(View v) { public DeviceGroupViewHolder(View v) {
avatarLayout = v.findViewById(R.id.avatar_layout); avatarLayout = v.findViewById(R.id.avatar_layout);

View file

@ -36,8 +36,8 @@ import org.linphone.core.ParticipantDevice;
import org.linphone.utils.LinphoneUtils; import org.linphone.utils.LinphoneUtils;
import org.linphone.views.ContactAvatar; import org.linphone.views.ContactAvatar;
public class DevicesAdapter extends BaseExpandableListAdapter { class DevicesAdapter extends BaseExpandableListAdapter {
private Context mContext; private final Context mContext;
private List<Participant> mParticipants; private List<Participant> mParticipants;
private boolean mOnlyDisplayChildsAsGroups; private boolean mOnlyDisplayChildsAsGroups;

View file

@ -33,7 +33,7 @@ import org.linphone.core.ChatRoom;
import org.linphone.core.Participant; import org.linphone.core.Participant;
import org.linphone.views.ContactAvatar; import org.linphone.views.ContactAvatar;
public class GroupInfoAdapter extends RecyclerView.Adapter<GroupInfoViewHolder> { class GroupInfoAdapter extends RecyclerView.Adapter<GroupInfoViewHolder> {
private List<ContactAddress> mItems; private List<ContactAddress> mItems;
private View.OnClickListener mDeleteListener; private View.OnClickListener mDeleteListener;
private boolean mHideAdminFeatures; private boolean mHideAdminFeatures;
@ -136,11 +136,7 @@ public class GroupInfoAdapter extends RecyclerView.Adapter<GroupInfoViewHolder>
mChatRoom = room; mChatRoom = room;
} }
public int getCount() { private Object getItem(int i) {
return mItems.size();
}
public Object getItem(int i) {
return mItems.get(i); return mItems.get(i);
} }

View file

@ -62,7 +62,6 @@ public class GroupInfoFragment extends Fragment implements ChatRoomListener {
private RelativeLayout mAddParticipantsLayout; private RelativeLayout mAddParticipantsLayout;
private Address mGroupChatRoomAddress; private Address mGroupChatRoomAddress;
private EditText mSubjectField; private EditText mSubjectField;
private LayoutInflater mInflater;
private RecyclerView mParticipantsList; private RecyclerView mParticipantsList;
@ -84,7 +83,6 @@ public class GroupInfoFragment extends Fragment implements ChatRoomListener {
@Override @Override
public View onCreateView( public View onCreateView(
LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mInflater = inflater;
View view = inflater.inflate(R.layout.chat_infos, container, false); View view = inflater.inflate(R.layout.chat_infos, container, false);
if (getArguments() == null || getArguments().isEmpty()) { if (getArguments() == null || getArguments().isEmpty()) {

View file

@ -28,11 +28,11 @@ import androidx.recyclerview.widget.RecyclerView;
import org.linphone.R; import org.linphone.R;
public class GroupInfoViewHolder extends RecyclerView.ViewHolder { public class GroupInfoViewHolder extends RecyclerView.ViewHolder {
public TextView name; public final TextView name;
public RelativeLayout avatarLayout; public final RelativeLayout avatarLayout;
public ImageView delete; public final ImageView delete;
public LinearLayout isAdmin; public final LinearLayout isAdmin;
public LinearLayout isNotAdmin; public final LinearLayout isNotAdmin;
public GroupInfoViewHolder(View view) { public GroupInfoViewHolder(View view) {
super(view); super(view);

View file

@ -40,7 +40,7 @@ import org.linphone.notifications.NotifiableMessage;
import org.linphone.notifications.NotificationBroadcastReceiver; import org.linphone.notifications.NotificationBroadcastReceiver;
@TargetApi(28) @TargetApi(28)
public class ApiTwentyEightPlus { class ApiTwentyEightPlus {
public static Notification createMessageNotification( public static Notification createMessageNotification(
Context context, Notifiable notif, Bitmap contactIcon, PendingIntent intent) { Context context, Notifiable notif, Bitmap contactIcon, PendingIntent intent) {
String replyLabel = context.getResources().getString(R.string.notification_reply_label); String replyLabel = context.getResources().getString(R.string.notification_reply_label);

View file

@ -40,7 +40,7 @@ import org.linphone.notifications.NotifiableMessage;
import org.linphone.notifications.NotificationBroadcastReceiver; import org.linphone.notifications.NotificationBroadcastReceiver;
@TargetApi(24) @TargetApi(24)
public class ApiTwentyFourPlus { class ApiTwentyFourPlus {
public static Notification createRepliedNotification(Context context, String reply) { public static Notification createRepliedNotification(Context context, String reply) {
return new Notification.Builder(context) return new Notification.Builder(context)

View file

@ -28,7 +28,7 @@ import androidx.core.content.ContextCompat;
import org.linphone.R; import org.linphone.R;
@TargetApi(21) @TargetApi(21)
public class ApiTwentyOnePlus { class ApiTwentyOnePlus {
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public static Notification createMessageNotification( public static Notification createMessageNotification(
@ -47,61 +47,54 @@ public class ApiTwentyOnePlus {
.replace("%i", String.valueOf(msgCount)); .replace("%i", String.valueOf(msgCount));
} }
Notification notif = return new Notification.Builder(context)
new Notification.Builder(context) .setContentTitle(title)
.setContentTitle(title) .setContentText(msg)
.setContentText(msg) .setSmallIcon(R.drawable.topbar_chat_notification)
.setSmallIcon(R.drawable.topbar_chat_notification) .setAutoCancel(true)
.setAutoCancel(true) .setContentIntent(intent)
.setContentIntent(intent) .setDefaults(
.setDefaults( Notification.DEFAULT_SOUND
Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE
| Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS)
| Notification.DEFAULT_LIGHTS) .setLargeIcon(contactIcon)
.setLargeIcon(contactIcon) .setLights(
.setLights( ContextCompat.getColor(context, R.color.notification_color_led),
ContextCompat.getColor(context, R.color.notification_color_led), context.getResources().getInteger(R.integer.notification_ms_on),
context.getResources().getInteger(R.integer.notification_ms_on), context.getResources().getInteger(R.integer.notification_ms_off))
context.getResources().getInteger(R.integer.notification_ms_off)) .setCategory(Notification.CATEGORY_MESSAGE)
.setCategory(Notification.CATEGORY_MESSAGE) .setVisibility(Notification.VISIBILITY_PRIVATE)
.setVisibility(Notification.VISIBILITY_PRIVATE) .setPriority(Notification.PRIORITY_HIGH)
.setPriority(Notification.PRIORITY_HIGH) .setNumber(msgCount)
.setNumber(msgCount) .setWhen(System.currentTimeMillis())
.setWhen(System.currentTimeMillis()) .setShowWhen(true)
.setShowWhen(true) .build();
.build();
return notif;
} }
public static Notification createInCallNotification( public static Notification createInCallNotification(
Context context, Context context,
String title,
String msg, String msg,
int iconID, int iconID,
Bitmap contactIcon, Bitmap contactIcon,
String contactName, String contactName,
PendingIntent intent) { PendingIntent intent) {
Notification notif = return new Notification.Builder(context)
new Notification.Builder(context) .setContentTitle(contactName)
.setContentTitle(contactName) .setContentText(msg)
.setContentText(msg) .setSmallIcon(iconID)
.setSmallIcon(iconID) .setAutoCancel(false)
.setAutoCancel(false) .setContentIntent(intent)
.setContentIntent(intent) .setLargeIcon(contactIcon)
.setLargeIcon(contactIcon) .setCategory(Notification.CATEGORY_CALL)
.setCategory(Notification.CATEGORY_CALL) .setVisibility(Notification.VISIBILITY_PUBLIC)
.setVisibility(Notification.VISIBILITY_PUBLIC) .setPriority(Notification.PRIORITY_HIGH)
.setPriority(Notification.PRIORITY_HIGH) .setLights(
.setLights( ContextCompat.getColor(context, R.color.notification_color_led),
ContextCompat.getColor(context, R.color.notification_color_led), context.getResources().getInteger(R.integer.notification_ms_on),
context.getResources().getInteger(R.integer.notification_ms_on), context.getResources().getInteger(R.integer.notification_ms_off))
context.getResources().getInteger(R.integer.notification_ms_off)) .setShowWhen(true)
.setShowWhen(true) .build();
.build();
return notif;
} }
public static Notification createNotification( public static Notification createNotification(
@ -112,7 +105,6 @@ public class ApiTwentyOnePlus {
int level, int level,
Bitmap largeIcon, Bitmap largeIcon,
PendingIntent intent, PendingIntent intent,
boolean isOngoingEvent,
int priority) { int priority) {
Notification notif; Notification notif;
@ -160,49 +152,45 @@ public class ApiTwentyOnePlus {
public static Notification createMissedCallNotification( public static Notification createMissedCallNotification(
Context context, String title, String text, PendingIntent intent) { 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_EVENT)
.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 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_EVENT)
.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 createSimpleNotification( public static Notification createSimpleNotification(
Context context, String title, String text, PendingIntent intent) { 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 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();
} }
} }

View file

@ -34,16 +34,35 @@ import android.app.NotificationChannel;
import android.app.NotificationManager; import android.app.NotificationManager;
import android.app.PendingIntent; import android.app.PendingIntent;
import android.app.RemoteInput; import android.app.RemoteInput;
import android.bluetooth.BluetoothAdapter;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.os.Build;
import android.provider.Settings;
import org.linphone.R; import org.linphone.R;
import org.linphone.notifications.Notifiable; import org.linphone.notifications.Notifiable;
import org.linphone.notifications.NotifiableMessage; import org.linphone.notifications.NotifiableMessage;
import org.linphone.notifications.NotificationBroadcastReceiver; import org.linphone.notifications.NotificationBroadcastReceiver;
@TargetApi(26) @TargetApi(26)
public class ApiTwentySixPlus { class ApiTwentySixPlus {
public static String getDeviceName(Context context) {
String name =
Settings.Global.getString(
context.getContentResolver(), Settings.Global.DEVICE_NAME);
if (name == null) {
name = BluetoothAdapter.getDefaultAdapter().getName();
}
if (name == null) {
name = Settings.Secure.getString(context.getContentResolver(), "bluetooth_name");
}
if (name == null) {
name = Build.MANUFACTURER + " " + Build.MODEL;
}
return name;
}
public static Notification createRepliedNotification(Context context, String reply) { public static Notification createRepliedNotification(Context context, String reply) {
return new Notification.Builder( return new Notification.Builder(
context, context.getString(R.string.notification_channel_id)) context, context.getString(R.string.notification_channel_id))
@ -213,7 +232,6 @@ public class ApiTwentySixPlus {
int level, int level,
Bitmap largeIcon, Bitmap largeIcon,
PendingIntent intent, PendingIntent intent,
boolean isOngoingEvent,
int priority) { int priority) {
if (largeIcon != null) { if (largeIcon != null) {

View file

@ -23,7 +23,7 @@ import android.annotation.TargetApi;
import android.widget.TextView; import android.widget.TextView;
@TargetApi(23) @TargetApi(23)
public class ApiTwentyThreePlus { class ApiTwentyThreePlus {
public static void setTextAppearance(TextView textview, int style) { public static void setTextAppearance(TextView textview, int style) {
textview.setTextAppearance(style); textview.setTextAppearance(style);
} }

View file

@ -21,6 +21,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import android.app.FragmentTransaction; import android.app.FragmentTransaction;
import android.app.Notification; import android.app.Notification;
import android.app.PendingIntent; import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.graphics.Bitmap; import android.graphics.Bitmap;
@ -39,6 +40,21 @@ public class Compatibility {
public static final String INTENT_ANSWER_CALL_NOTIF_ACTION = "org.linphone.ANSWER_CALL_ACTION"; public static final String INTENT_ANSWER_CALL_NOTIF_ACTION = "org.linphone.ANSWER_CALL_ACTION";
public static final String INTENT_LOCAL_IDENTITY = "LOCAL_IDENTITY"; public static final String INTENT_LOCAL_IDENTITY = "LOCAL_IDENTITY";
public static String getDeviceName(Context context) {
if (Version.sdkAboveOrEqual(25)) {
return ApiTwentySixPlus.getDeviceName(context);
}
String name = BluetoothAdapter.getDefaultAdapter().getName();
if (name == null) {
name = Settings.Secure.getString(context.getContentResolver(), "bluetooth_name");
}
if (name == null) {
name = Build.MANUFACTURER + " " + Build.MODEL;
}
return name;
}
public static void createNotificationChannels(Context context) { public static void createNotificationChannels(Context context) {
if (Version.sdkAboveOrEqual(Version.API26_O_80)) { if (Version.sdkAboveOrEqual(Version.API26_O_80)) {
ApiTwentySixPlus.createServiceChannel(context); ApiTwentySixPlus.createServiceChannel(context);
@ -94,7 +110,6 @@ public class Compatibility {
Context context, Context context,
int callId, int callId,
boolean showAnswerAction, boolean showAnswerAction,
String title,
String msg, String msg,
int iconID, int iconID,
Bitmap contactIcon, Bitmap contactIcon,
@ -122,7 +137,7 @@ public class Compatibility {
intent); intent);
} }
return ApiTwentyOnePlus.createInCallNotification( return ApiTwentyOnePlus.createInCallNotification(
context, title, msg, iconID, contactIcon, contactName, intent); context, msg, iconID, contactIcon, contactName, intent);
} }
public static Notification createNotification( public static Notification createNotification(
@ -137,26 +152,10 @@ public class Compatibility {
int priority) { int priority) {
if (Version.sdkAboveOrEqual(Version.API26_O_80)) { if (Version.sdkAboveOrEqual(Version.API26_O_80)) {
return ApiTwentySixPlus.createNotification( return ApiTwentySixPlus.createNotification(
context, context, title, message, icon, iconLevel, largeIcon, intent, priority);
title,
message,
icon,
iconLevel,
largeIcon,
intent,
isOngoingEvent,
priority);
} }
return ApiTwentyOnePlus.createNotification( return ApiTwentyOnePlus.createNotification(
context, context, title, message, icon, iconLevel, largeIcon, intent, priority);
title,
message,
icon,
iconLevel,
largeIcon,
intent,
isOngoingEvent,
priority);
} }
public static boolean canDrawOverlays(Context context) { public static boolean canDrawOverlays(Context context) {

View file

@ -20,5 +20,5 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/ */
public interface CompatibilityScaleGestureListener { public interface CompatibilityScaleGestureListener {
public boolean onScale(CompatibilityScaleGestureDetector detector); boolean onScale(CompatibilityScaleGestureDetector detector);
} }

View file

@ -72,10 +72,6 @@ public class ContactAddress implements Serializable {
return mContact; return mContact;
} }
public SearchResult getResult() {
return mResult;
}
public void setResult(SearchResult result) { public void setResult(SearchResult result) {
this.mResult = result; this.mResult = result;
} }
@ -140,8 +136,8 @@ public class ContactAddress implements Serializable {
if (other == null) return false; if (other == null) return false;
if (other == this) return true; if (other == this) return true;
if (!(other instanceof ContactAddress)) return false; if (!(other instanceof ContactAddress)) return false;
if (((ContactAddress) other).getAddressAsDisplayableString() return ((ContactAddress) other)
== this.getAddressAsDisplayableString()) return true; .getAddressAsDisplayableString()
return false; .equals(getAddressAsDisplayableString());
} }
} }

View file

@ -62,20 +62,19 @@ public class ContactDetailsFragment extends Fragment implements OnClickListener
private ChatRoom mChatRoom; private ChatRoom mChatRoom;
private ChatRoomListenerStub mChatRoomCreationListener; private ChatRoomListenerStub mChatRoomCreationListener;
private OnClickListener mDialListener = private final OnClickListener mDialListener =
new OnClickListener() { new OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
if (LinphoneActivity.isInstanciated()) { if (LinphoneActivity.isInstanciated()) {
String tag = (String) v.getTag(); String tag = (String) v.getTag();
LinphoneActivity.instance() LinphoneActivity.instance()
.setAddresGoToDialerAndCall( .setAddresGoToDialerAndCall(tag, mContact.getFullName());
tag, mContact.getFullName(), mContact.getPhotoUri());
} }
} }
}; };
private OnClickListener mChatListener = private final OnClickListener mChatListener =
new OnClickListener() { new OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {

View file

@ -337,8 +337,6 @@ public class ContactEditorFragment extends Fragment {
public void onResume() { public void onResume() {
super.onResume(); super.onResume();
if (LinphoneActivity.isInstanciated()) {}
// Force hide keyboard // Force hide keyboard
getActivity() getActivity()
.getWindow() .getWindow()
@ -465,6 +463,7 @@ public class ContactEditorFragment extends Fragment {
} catch (Exception e) { } catch (Exception e) {
Log.e(e); Log.e(e);
} }
c.close();
return value; return value;
} }
@ -535,15 +534,6 @@ public class ContactEditorFragment extends Fragment {
private View displayNumberOrAddress( private View displayNumberOrAddress(
final LinearLayout controls, String numberOrAddress, boolean isSIP) { 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; String displayNumberOrAddress = numberOrAddress;
if (isSIP) { if (isSIP) {
if (mFirstSipAddressIndex == -1) { if (mFirstSipAddressIndex == -1) {
@ -554,21 +544,14 @@ public class ContactEditorFragment extends Fragment {
} }
if ((getResources().getBoolean(R.bool.hide_phone_numbers_in_editor) && !isSIP) if ((getResources().getBoolean(R.bool.hide_phone_numbers_in_editor) && !isSIP)
|| (getResources().getBoolean(R.bool.hide_sip_addresses_in_editor) && isSIP)) { || (getResources().getBoolean(R.bool.hide_sip_addresses_in_editor) && isSIP)) {
if (forceAddNumber) return null;
isSIP = !isSIP; // If number can't be displayed because we hide a sort of number,
// change that category
else return null;
} }
LinphoneNumberOrAddress tempNounoa; LinphoneNumberOrAddress tempNounoa;
if (forceAddNumber) { if (mIsNewContact || mNewSipOrNumberToAdd != null) {
tempNounoa = new LinphoneNumberOrAddress(null, isSIP); tempNounoa = new LinphoneNumberOrAddress(numberOrAddress, isSIP);
} else { } else {
if (mIsNewContact || mNewSipOrNumberToAdd != null) { tempNounoa = new LinphoneNumberOrAddress(null, isSIP, numberOrAddress);
tempNounoa = new LinphoneNumberOrAddress(numberOrAddress, isSIP);
} else {
tempNounoa = new LinphoneNumberOrAddress(null, isSIP, numberOrAddress);
}
} }
final LinphoneNumberOrAddress nounoa = tempNounoa; final LinphoneNumberOrAddress nounoa = tempNounoa;
mNumbersAndAddresses.add(nounoa); mNumbersAndAddresses.add(nounoa);
@ -594,9 +577,6 @@ public class ContactEditorFragment extends Fragment {
@Override @Override
public void afterTextChanged(Editable s) {} public void afterTextChanged(Editable s) {}
}); });
if (forceAddNumber) {
nounoa.setValue(noa.getText().toString());
}
ImageView delete = view.findViewById(R.id.delete_field); ImageView delete = view.findViewById(R.id.delete_field);
if ((getResources().getBoolean(R.bool.allow_only_one_phone_number) && !isSIP) if ((getResources().getBoolean(R.bool.allow_only_one_phone_number) && !isSIP)

View file

@ -1,26 +0,0 @@
/*
ContactPicked.java
Copyright (C) 2017 Belledonne Communications, Grenoble, France
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
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.
*/
package org.linphone.contacts;
import android.net.Uri;
public interface ContactPicked {
void setAddresGoToDialerAndCall(String number, String name, Uri photo);
}

View file

@ -0,0 +1,77 @@
package org.linphone.contacts;
/*
ContactViewHolder.java
Copyright (C) 2018 Belledonne Communications, Grenoble, France
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
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.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import org.linphone.R;
public class ContactViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener, View.OnLongClickListener {
public final CheckBox delete;
public final ImageView linphoneFriend;
public final TextView name;
public final LinearLayout separator;
public final TextView separatorText;
public final RelativeLayout avatarLayout;
public final TextView organization;
private final ClickListener mListener;
public ContactViewHolder(View view, ClickListener listener) {
super(view);
delete = view.findViewById(R.id.delete);
linphoneFriend = view.findViewById(R.id.friendLinphone);
name = view.findViewById(R.id.name);
separator = view.findViewById(R.id.separator);
separatorText = view.findViewById(R.id.separator_text);
avatarLayout = view.findViewById(R.id.avatar_layout);
organization = view.findViewById(R.id.contactOrganization);
// friendStatus = view.findViewById(R.id.friendStatus);
mListener = listener;
view.setOnClickListener(this);
view.setOnLongClickListener(this);
}
@Override
public void onClick(View view) {
if (mListener != null) {
mListener.onItemClicked(getAdapterPosition());
}
}
public boolean onLongClick(View v) {
if (mListener != null) {
return mListener.onItemLongClicked(getAdapterPosition());
}
return false;
}
public interface ClickListener {
void onItemClicked(int position);
boolean onItemLongClicked(int position);
}
}

View file

@ -1,7 +1,7 @@
package org.linphone.contacts; package org.linphone.contacts;
/* /*
ContactsListAdapter.java ContactsAdapter.java
Copyright (C) 2018 Belledonne Communications, Grenoble, France Copyright (C) 2018 Belledonne Communications, Grenoble, France
This program is free software; you can redistribute it and/or This program is free software; you can redistribute it and/or
@ -23,14 +23,8 @@ import android.content.Context;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SectionIndexer; import android.widget.SectionIndexer;
import android.widget.TextView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
@ -41,20 +35,20 @@ import org.linphone.utils.SelectableAdapter;
import org.linphone.utils.SelectableHelper; import org.linphone.utils.SelectableHelper;
import org.linphone.views.ContactAvatar; import org.linphone.views.ContactAvatar;
public class ContactsListAdapter extends SelectableAdapter<ContactsListAdapter.ViewHolder> public class ContactsAdapter extends SelectableAdapter<ContactViewHolder>
implements SectionIndexer { implements SectionIndexer {
private List<LinphoneContact> mContacts; private List<LinphoneContact> mContacts;
private String[] mSections; private String[] mSections;
private ArrayList<String> mSectionsList; private ArrayList<String> mSectionsList;
private Map<String, Integer> mMap = new LinkedHashMap<>(); private Map<String, Integer> mMap = new LinkedHashMap<>();
private ViewHolder.ClickListener mClickListener; private final ContactViewHolder.ClickListener mClickListener;
private Context mContext; private final Context mContext;
private boolean mIsSearchMode; private boolean mIsSearchMode;
ContactsListAdapter( ContactsAdapter(
Context context, Context context,
List<LinphoneContact> contactsList, List<LinphoneContact> contactsList,
ViewHolder.ClickListener clickListener, ContactViewHolder.ClickListener clickListener,
SelectableHelper helper) { SelectableHelper helper) {
super(helper); super(helper);
mContext = context; mContext = context;
@ -64,15 +58,15 @@ public class ContactsListAdapter extends SelectableAdapter<ContactsListAdapter.V
@NonNull @NonNull
@Override @Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { public ContactViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = View v =
LayoutInflater.from(parent.getContext()) LayoutInflater.from(parent.getContext())
.inflate(R.layout.contact_cell, parent, false); .inflate(R.layout.contact_cell, parent, false);
return new ViewHolder(v, mClickListener); return new ContactViewHolder(v, mClickListener);
} }
@Override @Override
public void onBindViewHolder(@NonNull ViewHolder holder, final int position) { public void onBindViewHolder(@NonNull ContactViewHolder holder, final int position) {
LinphoneContact contact = (LinphoneContact) getItem(position); LinphoneContact contact = (LinphoneContact) getItem(position);
holder.name.setText(contact.getFullName()); holder.name.setText(contact.getFullName());
@ -176,53 +170,4 @@ public class ContactsListAdapter extends SelectableAdapter<ContactsListAdapter.V
String letter = fullName.substring(0, 1).toUpperCase(Locale.getDefault()); String letter = fullName.substring(0, 1).toUpperCase(Locale.getDefault());
return mSectionsList.indexOf(letter); return mSectionsList.indexOf(letter);
} }
public static class ViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener, View.OnLongClickListener {
public CheckBox delete;
public ImageView linphoneFriend;
public TextView name;
public LinearLayout separator;
public TextView separatorText;
public RelativeLayout avatarLayout;
public TextView organization;
// public ImageView friendStatus;
private ClickListener mListener;
private ViewHolder(View view, ClickListener listener) {
super(view);
delete = view.findViewById(R.id.delete);
linphoneFriend = view.findViewById(R.id.friendLinphone);
name = view.findViewById(R.id.name);
separator = view.findViewById(R.id.separator);
separatorText = view.findViewById(R.id.separator_text);
avatarLayout = view.findViewById(R.id.avatar_layout);
organization = view.findViewById(R.id.contactOrganization);
// friendStatus = view.findViewById(R.id.friendStatus);
mListener = listener;
view.setOnClickListener(this);
view.setOnLongClickListener(this);
}
@Override
public void onClick(View view) {
if (mListener != null) {
mListener.onItemClicked(getAdapterPosition());
}
}
public boolean onLongClick(View v) {
if (mListener != null) {
return mListener.onItemLongClicked(getAdapterPosition());
}
return false;
}
public interface ClickListener {
void onItemClicked(int position);
boolean onItemLongClicked(int position);
}
}
} }

View file

@ -1,7 +1,7 @@
package org.linphone.contacts; package org.linphone.contacts;
/* /*
ContactsListFragment.java ContactsFragment.java
Copyright (C) 2017 Belledonne Communications, Grenoble, France Copyright (C) 2017 Belledonne Communications, Grenoble, France
This program is free software; you can redistribute it and/or This program is free software; you can redistribute it and/or
@ -42,10 +42,10 @@ import org.linphone.R;
import org.linphone.fragments.FragmentsAvailable; import org.linphone.fragments.FragmentsAvailable;
import org.linphone.utils.SelectableHelper; import org.linphone.utils.SelectableHelper;
public class ContactsListFragment extends Fragment public class ContactsFragment extends Fragment
implements OnItemClickListener, implements OnItemClickListener,
ContactsUpdatedListener, ContactsUpdatedListener,
ContactsListAdapter.ViewHolder.ClickListener, ContactViewHolder.ClickListener,
SelectableHelper.DeleteListener { SelectableHelper.DeleteListener {
private RecyclerView mContactsList; private RecyclerView mContactsList;
private TextView mNoSipContact, mNoContact; private TextView mNoSipContact, mNoContact;
@ -60,7 +60,7 @@ public class ContactsListFragment extends Fragment
private LinearLayoutManager mLayoutManager; private LinearLayoutManager mLayoutManager;
private Context mContext; private Context mContext;
private SelectableHelper mSelectionHelper; private SelectableHelper mSelectionHelper;
private ContactsListAdapter mContactAdapter; private ContactsAdapter mContactAdapter;
@Override @Override
public View onCreateView( public View onCreateView(
@ -183,7 +183,7 @@ public class ContactsListFragment extends Fragment
if (mContactsList != null if (mContactsList != null
&& mContactsList.getAdapter() != null && mContactsList.getAdapter() != null
&& mContactsList.getAdapter().getItemCount() > 0) { && mContactsList.getAdapter().getItemCount() > 0) {
ContactsListAdapter mAdapt = (ContactsListAdapter) mContactsList.getAdapter(); ContactsAdapter mAdapt = (ContactsAdapter) mContactsList.getAdapter();
LinphoneActivity.instance().displayContact((LinphoneContact) mAdapt.getItem(0), false); LinphoneActivity.instance().displayContact((LinphoneContact) mAdapt.getItem(0), false);
} else { } else {
LinphoneActivity.instance().displayEmptyFragment(); LinphoneActivity.instance().displayEmptyFragment();
@ -210,7 +210,7 @@ public class ContactsListFragment extends Fragment
isEditionEnabled = true; isEditionEnabled = true;
} }
mContactAdapter = new ContactsListAdapter(mContext, listContact, this, mSelectionHelper); mContactAdapter = new ContactsAdapter(mContext, listContact, this, mSelectionHelper);
// mContactsList.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE); // mContactsList.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
mSelectionHelper.setAdapter(mContactAdapter); mSelectionHelper.setAdapter(mContactAdapter);
@ -228,7 +228,7 @@ public class ContactsListFragment extends Fragment
mNoContact.setVisibility(View.GONE); mNoContact.setVisibility(View.GONE);
mContactsList.setVisibility(View.VISIBLE); mContactsList.setVisibility(View.VISIBLE);
boolean isEditionEnabled = false; boolean isEditionEnabled = false;
if (mSearchView.getQuery().toString() == "") { if (mSearchView.getQuery().toString().equals("")) {
if (mOnlyDisplayLinphoneContacts) { if (mOnlyDisplayLinphoneContacts) {
listContact = ContactsManager.getInstance().getSIPContacts(); listContact = ContactsManager.getInstance().getSIPContacts();
} else { } else {
@ -250,7 +250,7 @@ public class ContactsListFragment extends Fragment
isEditionEnabled = true; isEditionEnabled = true;
} }
mContactAdapter = new ContactsListAdapter(mContext, listContact, this, mSelectionHelper); mContactAdapter = new ContactsAdapter(mContext, listContact, this, mSelectionHelper);
mSelectionHelper.setAdapter(mContactAdapter); mSelectionHelper.setAdapter(mContactAdapter);
@ -366,7 +366,7 @@ public class ContactsListFragment extends Fragment
mContactsFetchInProgress.setVisibility(View.GONE); mContactsFetchInProgress.setVisibility(View.GONE);
} }
public void invalidate() { private void invalidate() {
if (mSearchView != null && mSearchView.getQuery().toString().length() > 0) { if (mSearchView != null && mSearchView.getQuery().toString().length() > 0) {
searchContacts(mSearchView.getQuery().toString()); searchContacts(mSearchView.getQuery().toString());
} else { } else {

View file

@ -78,7 +78,7 @@ public class ContactsManager extends ContentObserver implements FriendListListen
private List<LinphoneContact> mContacts, mSipContacts; private List<LinphoneContact> mContacts, mSipContacts;
private MagicSearch mMagicSearch; private MagicSearch mMagicSearch;
private Bitmap mDefaultAvatar; private final Bitmap mDefaultAvatar;
private boolean mContactsFetchedOnce = false; private boolean mContactsFetchedOnce = false;
private Context mContext; private Context mContext;
private AsyncContactsLoader mLoadContactTask; private AsyncContactsLoader mLoadContactTask;
@ -104,7 +104,7 @@ public class ContactsManager extends ContentObserver implements FriendListListen
sContactsUpdatedListeners.remove(listener); sContactsUpdatedListeners.remove(listener);
} }
public static final ContactsManager getInstance() { public static ContactsManager getInstance() {
if (sInstance == null) sInstance = new ContactsManager(); if (sInstance == null) sInstance = new ContactsManager();
return sInstance; return sInstance;
} }
@ -115,27 +115,28 @@ public class ContactsManager extends ContentObserver implements FriendListListen
String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.NUMBER}; String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor c = resolver.query(contactUri, projection, null, null, null); Cursor c = resolver.query(contactUri, projection, null, null, null);
if (c != null) { if (c != null) {
while (c.moveToNext()) { if (c.moveToNext()) {
int numberIndex = c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER); int numberIndex = c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String number = c.getString(numberIndex); String number = c.getString(numberIndex);
c.close(); c.close();
return number; return number;
} }
} }
c.close();
// SIP addresses // SIP addresses
projection = new String[] {ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS}; projection = new String[] {ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS};
c = resolver.query(contactUri, projection, null, null, null); c = resolver.query(contactUri, projection, null, null, null);
if (c != null) { if (c != null) {
while (c.moveToNext()) { if (c.moveToNext()) {
int numberIndex = int numberIndex =
c.getColumnIndex(ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS); c.getColumnIndex(ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS);
String address = c.getString(numberIndex); String address = c.getString(numberIndex);
c.close(); c.close();
return address; return address;
} }
c.close();
} }
c.close();
return null; return null;
} }
@ -182,7 +183,7 @@ public class ContactsManager extends ContentObserver implements FriendListListen
} }
} }
public void setContacts(List<LinphoneContact> c) { private void setContacts(List<LinphoneContact> c) {
synchronized (mContacts) { synchronized (mContacts) {
mContacts = c; mContacts = c;
} }
@ -259,10 +260,8 @@ public class ContactsManager extends ContentObserver implements FriendListListen
public boolean isLinphoneContactsPrefered() { public boolean isLinphoneContactsPrefered() {
ProxyConfig lpc = LinphoneManager.getLc().getDefaultProxyConfig(); ProxyConfig lpc = LinphoneManager.getLc().getDefaultProxyConfig();
if (lpc != null return lpc != null
&& lpc.getIdentityAddress().getDomain().equals(getString(R.string.default_domain))) && lpc.getIdentityAddress().getDomain().equals(getString(R.string.default_domain));
return true;
return false;
} }
public void initializeContactManager(Context context) { public void initializeContactManager(Context context) {
@ -296,8 +295,7 @@ public class ContactsManager extends ContentObserver implements FriendListListen
Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull(); Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
Friend lf = lc.findFriend(address); Friend lf = lc.findFriend(address);
if (lf != null) { if (lf != null) {
LinphoneContact contact = (LinphoneContact) lf.getUserData(); return (LinphoneContact) lf.getUserData();
return contact;
} }
return findContactFromPhoneNumber(address.getUsername()); return findContactFromPhoneNumber(address.getUsername());
} }
@ -321,13 +319,12 @@ public class ContactsManager extends ContentObserver implements FriendListListen
lc.findFriend( lc.findFriend(
addr); // Without this, the hashmap inside liblinphone won't find it... addr); // Without this, the hashmap inside liblinphone won't find it...
if (lf != null) { if (lf != null) {
LinphoneContact contact = (LinphoneContact) lf.getUserData(); return (LinphoneContact) lf.getUserData();
return contact;
} }
return null; return null;
} }
public synchronized boolean refreshSipContact(Friend lf) { private synchronized boolean refreshSipContact(Friend lf) {
LinphoneContact contact = (LinphoneContact) lf.getUserData(); LinphoneContact contact = (LinphoneContact) lf.getUserData();
if (contact != null && !getSIPContacts().contains(contact)) { if (contact != null && !getSIPContacts().contains(contact)) {
addSipContact(contact); addSipContact(contact);
@ -398,7 +395,7 @@ public class ContactsManager extends ContentObserver implements FriendListListen
mLoadContactTask.executeOnExecutor(THREAD_POOL_EXECUTOR); mLoadContactTask.executeOnExecutor(THREAD_POOL_EXECUTOR);
} }
public synchronized void setSipContacts(List<LinphoneContact> c) { private synchronized void setSipContacts(List<LinphoneContact> c) {
synchronized (mSipContacts) { synchronized (mSipContacts) {
mSipContacts = c; mSipContacts = c;
} }
@ -441,10 +438,10 @@ public class ContactsManager extends ContentObserver implements FriendListListen
} }
class AsyncContactsData { class AsyncContactsData {
List<LinphoneContact> contacts; final List<LinphoneContact> contacts;
List<LinphoneContact> sipContacts; final List<LinphoneContact> sipContacts;
public AsyncContactsData() { AsyncContactsData() {
contacts = new ArrayList<>(); contacts = new ArrayList<>();
sipContacts = new ArrayList<>(); sipContacts = new ArrayList<>();
} }
@ -560,6 +557,7 @@ public class ContactsManager extends ContentObserver implements FriendListListen
contact.setFirstNameAndLastName(data2, data3, false); contact.setFirstNameAndLastName(data2, data3, false);
} }
} }
c.close();
for (FriendList list : lc.getFriendsLists()) { for (FriendList list : lc.getFriendsLists()) {
for (Friend friend : list.getFriends()) { for (Friend friend : list.getFriends()) {

View file

@ -129,7 +129,7 @@ public class LinphoneContact implements Serializable, Comparable<LinphoneContact
} }
return -1; return -1;
} }
return ((Integer) noas1.size()).compareTo(noas2.size()); return Integer.compare(noas1.size(), noas2.size());
} }
return -1; return -1;
} }
@ -307,7 +307,7 @@ public class LinphoneContact implements Serializable, Comparable<LinphoneContact
return mPhotoUri; return mPhotoUri;
} }
public void setPhotoUri(Uri uri) { private void setPhotoUri(Uri uri) {
if (uri.equals(mPhotoUri)) return; if (uri.equals(mPhotoUri)) return;
mPhotoUri = uri; mPhotoUri = uri;
} }
@ -316,7 +316,7 @@ public class LinphoneContact implements Serializable, Comparable<LinphoneContact
return mThumbnailUri; return mThumbnailUri;
} }
public void setThumbnailUri(Uri uri) { private void setThumbnailUri(Uri uri) {
if (uri.equals(mThumbnailUri)) return; if (uri.equals(mThumbnailUri)) return;
mThumbnailUri = uri; mThumbnailUri = uri;
} }
@ -884,7 +884,7 @@ public class LinphoneContact implements Serializable, Comparable<LinphoneContact
return null; return null;
} }
public void getAndroidIds() { private void getAndroidIds() {
mAndroidRawId = findRawContactID(); mAndroidRawId = findRawContactID();
if (LinphoneManager.getInstance() if (LinphoneManager.getInstance()
.getContext() .getContext()
@ -1124,9 +1124,7 @@ public class LinphoneContact implements Serializable, Comparable<LinphoneContact
.build()); .build());
if (mChangesToCommit2.size() > 0) { if (mChangesToCommit2.size() > 0) {
for (ContentProviderOperation cpo : mChangesToCommit2) { batch.addAll(mChangesToCommit2);
batch.add(cpo);
}
} }
try { try {

View file

@ -24,9 +24,9 @@ import java.io.Serializable;
public class LinphoneNumberOrAddress implements Serializable, Comparable<LinphoneNumberOrAddress> { public class LinphoneNumberOrAddress implements Serializable, Comparable<LinphoneNumberOrAddress> {
private static final long serialVersionUID = -2301689469730072896L; private static final long serialVersionUID = -2301689469730072896L;
private boolean mIsSIPAddress; private final boolean mIsSIPAddress;
private String mValue, mOldValueForUpdatePurpose; private String mValue, mOldValueForUpdatePurpose;
private String mNormalizedPhone; private final String mNormalizedPhone;
public LinphoneNumberOrAddress(String v, boolean isSIP) { public LinphoneNumberOrAddress(String v, boolean isSIP) {
mValue = v; mValue = v;

View file

@ -0,0 +1,60 @@
package org.linphone.contacts;
/*
SearchContactViewHolder.java
Copyright (C) 2018 Belledonne Communications, Grenoble, France
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
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.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import org.linphone.R;
public class SearchContactViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener {
public final TextView name;
public final TextView address;
public final ImageView linphoneContact;
public final ImageView isSelect;
public final RelativeLayout avatarLayout;
private final ClickListener mListener;
public SearchContactViewHolder(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);
avatarLayout = view.findViewById(R.id.avatar_layout);
mListener = listener;
view.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if (mListener != null) {
mListener.onItemClicked(getAdapterPosition());
}
}
public interface ClickListener {
void onItemClicked(int position);
}
}

View file

@ -1,5 +1,7 @@
package org.linphone.contacts;
/* /*
SearchContactsListAdapter.java SearchContactsAdapter.java
Copyright (C) 2017 Belledonne Communications, Grenoble, France Copyright (C) 2017 Belledonne Communications, Grenoble, France
This program is free software; you can redistribute it and/or This program is free software; you can redistribute it and/or
@ -17,15 +19,10 @@ along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/ */
package org.linphone.contacts;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar; import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList; import java.util.ArrayList;
@ -41,23 +38,22 @@ import org.linphone.core.ProxyConfig;
import org.linphone.core.SearchResult; import org.linphone.core.SearchResult;
import org.linphone.views.ContactAvatar; import org.linphone.views.ContactAvatar;
public class SearchContactsListAdapter public class SearchContactsAdapter extends RecyclerView.Adapter<SearchContactViewHolder> {
extends RecyclerView.Adapter<SearchContactsListAdapter.ViewHolder> {
@SuppressWarnings("unused") @SuppressWarnings("unused")
private static final String TAG = SearchContactsListAdapter.class.getSimpleName(); private static final String TAG = SearchContactsAdapter.class.getSimpleName();
private List<ContactAddress> mContacts; private List<ContactAddress> mContacts;
private List<ContactAddress> mContactsSelected; private List<ContactAddress> mContactsSelected;
private ProgressBar mProgressBar; private final ProgressBar mProgressBar;
private boolean mOnlySipContact = false; private boolean mOnlySipContact = false;
private ViewHolder.ClickListener mListener; private SearchContactViewHolder.ClickListener mListener;
private boolean mHideSelectionMark; private final boolean mHideSelectionMark;
private String mPreviousSearch; private String mPreviousSearch;
public SearchContactsListAdapter( public SearchContactsAdapter(
List<ContactAddress> contactsList, List<ContactAddress> contactsList,
ProgressBar pB, ProgressBar pB,
ViewHolder.ClickListener clickListener, SearchContactViewHolder.ClickListener clickListener,
boolean hideSelectionMark) { boolean hideSelectionMark) {
mHideSelectionMark = hideSelectionMark; mHideSelectionMark = hideSelectionMark;
mListener = clickListener; mListener = clickListener;
@ -75,21 +71,21 @@ public class SearchContactsListAdapter
mOnlySipContact = enable; mOnlySipContact = enable;
} }
public void setListener(ViewHolder.ClickListener listener) { public void setListener(SearchContactViewHolder.ClickListener listener) {
mListener = listener; mListener = listener;
} }
@NonNull @NonNull
@Override @Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { public SearchContactViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = View v =
LayoutInflater.from(parent.getContext()) LayoutInflater.from(parent.getContext())
.inflate(R.layout.search_contact_cell, parent, false); .inflate(R.layout.search_contact_cell, parent, false);
return new ViewHolder(v, mListener); return new SearchContactViewHolder(v, mListener);
} }
@Override @Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) { public void onBindViewHolder(@NonNull SearchContactViewHolder holder, int position) {
ContactAddress contact = getItem(position); ContactAddress contact = getItem(position);
final String a = final String a =
(contact.getAddressAsDisplayableString().isEmpty()) (contact.getAddressAsDisplayableString().isEmpty())
@ -229,7 +225,7 @@ public class SearchContactsListAdapter
return list; return list;
} }
public void setContactsList(List<ContactAddress> contactsList) { private void setContactsList(List<ContactAddress> contactsList) {
if (contactsList == null) { if (contactsList == null) {
mContacts = getContactsList(); mContacts = getContactsList();
if (mProgressBar != null) mProgressBar.setVisibility(View.GONE); if (mProgressBar != null) mProgressBar.setVisibility(View.GONE);
@ -238,11 +234,7 @@ public class SearchContactsListAdapter
} }
} }
public int getCount() { private ContactAddress getItem(int position) {
return mContacts.size();
}
public ContactAddress getItem(int position) {
return mContacts.get(position); return mContacts.get(position);
} }
@ -337,36 +329,4 @@ public class SearchContactsListAdapter
resultContactsSearch.setAdapter(this); resultContactsSearch.setAdapter(this);
notifyDataSetChanged(); notifyDataSetChanged();
} }
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView name;
public TextView address;
public ImageView linphoneContact;
public ImageView isSelect;
public RelativeLayout avatarLayout;
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);
avatarLayout = view.findViewById(R.id.avatar_layout);
mListener = listener;
view.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if (mListener != null) {
mListener.onItemClicked(getAdapterPosition());
}
}
public interface ClickListener {
void onItemClicked(int position);
}
}
} }

View file

@ -181,9 +181,4 @@ public class AboutFragment extends Fragment implements OnClickListener {
} }
} }
} }
@Override
public void onDestroy() {
super.onDestroy();
}
} }

View file

@ -32,7 +32,6 @@ public class EmptyFragment extends Fragment {
public View onCreateView( public View onCreateView(
LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.empty_fragment, container, false); return inflater.inflate(R.layout.empty_fragment, container, false);
return view;
} }
} }

View file

@ -54,7 +54,7 @@ import org.linphone.mediastream.Log;
import org.linphone.settings.LinphonePreferences; import org.linphone.settings.LinphonePreferences;
public class StatusFragment extends Fragment { public class StatusFragment extends Fragment {
private Handler mRefreshHandler = new Handler(); private final Handler mRefreshHandler = new Handler();
private TextView mStatusText, mVoicemailCount; private TextView mStatusText, mVoicemailCount;
private ImageView mStatusLed, mCallQuality, mEncryption, mMenu, mVoicemail; private ImageView mStatusLed, mCallQuality, mEncryption, mMenu, mVoicemail;
private Runnable mCallQualityUpdater; private Runnable mCallQualityUpdater;
@ -100,10 +100,10 @@ public class StatusFragment extends Fragment {
if (lc.getDefaultProxyConfig() != null if (lc.getDefaultProxyConfig() != null
&& lc.getDefaultProxyConfig().equals(proxy)) { && lc.getDefaultProxyConfig().equals(proxy)) {
mStatusLed.setImageResource(getStatusIconResource(state, true)); mStatusLed.setImageResource(getStatusIconResource(state));
mStatusText.setText(getStatusIconText(state)); mStatusText.setText(getStatusIconText(state));
} else if (lc.getDefaultProxyConfig() == null) { } else if (lc.getDefaultProxyConfig() == null) {
mStatusLed.setImageResource(getStatusIconResource(state, true)); mStatusLed.setImageResource(getStatusIconResource(state));
mStatusText.setText(getStatusIconText(state)); mStatusText.setText(getStatusIconText(state));
} }
@ -116,6 +116,7 @@ public class StatusFragment extends Fragment {
} }
}); });
} catch (IllegalStateException ise) { } catch (IllegalStateException ise) {
Log.e(ise);
} }
} }
@ -128,7 +129,7 @@ public class StatusFragment extends Fragment {
if (content.getSize() == 0) return; if (content.getSize() == 0) return;
int unreadCount = -1; int unreadCount;
String data = content.getStringBuffer(); String data = content.getStringBuffer();
String[] voiceMail = data.split("voice-message: "); String[] voiceMail = data.split("voice-message: ");
final String[] intToParse = voiceMail[1].split("/", 0); final String[] intToParse = voiceMail[1].split("/", 0);
@ -211,16 +212,13 @@ public class StatusFragment extends Fragment {
mMenu.setEnabled(enabled); mMenu.setEnabled(enabled);
} }
private int getStatusIconResource(RegistrationState state, boolean isDefaultAccount) { private int getStatusIconResource(RegistrationState state) {
try { try {
Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull(); Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
boolean defaultAccountConnected = boolean defaultAccountConnected =
(isDefaultAccount (lc != null
&& lc != null && lc.getDefaultProxyConfig() != null
&& lc.getDefaultProxyConfig() != null && lc.getDefaultProxyConfig().getState() == RegistrationState.Ok);
&& lc.getDefaultProxyConfig().getState()
== RegistrationState.Ok)
|| !isDefaultAccount;
if (state == RegistrationState.Ok && defaultAccountConnected) { if (state == RegistrationState.Ok && defaultAccountConnected) {
return R.drawable.led_connected; return R.drawable.led_connected;
} else if (state == RegistrationState.Progress) { } else if (state == RegistrationState.Progress) {
@ -270,7 +268,7 @@ public class StatusFragment extends Fragment {
mRefreshHandler.postDelayed( mRefreshHandler.postDelayed(
mCallQualityUpdater = mCallQualityUpdater =
new Runnable() { new Runnable() {
Call mCurrentCall = LinphoneManager.getLc().getCurrentCall(); final Call mCurrentCall = LinphoneManager.getLc().getCurrentCall();
public void run() { public void run() {
if (mCurrentCall == null) { if (mCurrentCall == null) {
@ -288,7 +286,7 @@ public class StatusFragment extends Fragment {
1000); 1000);
} }
void updateQualityOfSignalIcon(float quality) { private void updateQualityOfSignalIcon(float quality) {
int iQuality = (int) quality; int iQuality = (int) quality;
if (iQuality == mDisplayedQuality) return; if (iQuality == mDisplayedQuality) return;
@ -327,7 +325,7 @@ public class StatusFragment extends Fragment {
if (mIsInCall && (call != null || lc.getConferenceSize() > 1 || lc.getCallsNb() > 0)) { if (mIsInCall && (call != null || lc.getConferenceSize() > 1 || lc.getCallsNb() > 0)) {
if (call != null) { if (call != null) {
startCallQuality(); startCallQuality();
refreshStatusItems(call, call.getCurrentParams().videoEnabled()); refreshStatusItems(call);
} }
mMenu.setVisibility(View.INVISIBLE); mMenu.setVisibility(View.INVISIBLE);
mCallQuality.setVisibility(View.VISIBLE); mCallQuality.setVisibility(View.VISIBLE);
@ -338,7 +336,7 @@ public class StatusFragment extends Fragment {
mStatusText.setText(getString(R.string.no_account)); mStatusText.setText(getString(R.string.no_account));
} else { } else {
mStatusLed.setImageResource( mStatusLed.setImageResource(
getStatusIconResource(lc.getDefaultProxyConfig().getState(), true)); getStatusIconResource(lc.getDefaultProxyConfig().getState()));
mStatusText.setText(getStatusIconText(lc.getDefaultProxyConfig().getState())); mStatusText.setText(getStatusIconText(lc.getDefaultProxyConfig().getState()));
} }
} }
@ -363,17 +361,11 @@ public class StatusFragment extends Fragment {
} }
} }
public void refreshStatusItems(final Call call, boolean isVideoEnabled) { public void refreshStatusItems(final Call call) {
if (call != null) { if (call != null) {
mVoicemailCount.setVisibility(View.GONE); mVoicemailCount.setVisibility(View.GONE);
MediaEncryption mediaEncryption = call.getCurrentParams().getMediaEncryption(); MediaEncryption mediaEncryption = call.getCurrentParams().getMediaEncryption();
if (isVideoEnabled) {
// background.setVisibility(View.GONE);
} else {
// background.setVisibility(View.VISIBLE);
}
mEncryption.setVisibility(View.VISIBLE); mEncryption.setVisibility(View.VISIBLE);
if (mediaEncryption == MediaEncryption.SRTP if (mediaEncryption == MediaEncryption.SRTP
|| (mediaEncryption == MediaEncryption.ZRTP || (mediaEncryption == MediaEncryption.ZRTP

View file

@ -41,9 +41,9 @@ import org.linphone.utils.SelectableHelper;
import org.linphone.views.ContactAvatar; import org.linphone.views.ContactAvatar;
public class HistoryAdapter extends SelectableAdapter<HistoryViewHolder> { public class HistoryAdapter extends SelectableAdapter<HistoryViewHolder> {
private List<CallLog> mLogs; private final List<CallLog> mLogs;
private Context mContext; private final Context mContext;
private HistoryViewHolder.ClickListener mClickListener; private final HistoryViewHolder.ClickListener mClickListener;
public HistoryAdapter( public HistoryAdapter(
Context aContext, Context aContext,
@ -56,10 +56,6 @@ public class HistoryAdapter extends SelectableAdapter<HistoryViewHolder> {
mClickListener = listener; mClickListener = listener;
} }
public int getCount() {
return mLogs.size();
}
public Object getItem(int position) { public Object getItem(int position) {
return mLogs.get(position); return mLogs.get(position);
} }

View file

@ -20,7 +20,6 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/ */
import android.app.Fragment; import android.app.Fragment;
import android.net.Uri;
import android.os.Bundle; import android.os.Bundle;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
@ -217,11 +216,7 @@ public class HistoryDetailFragment extends Fragment implements OnClickListener {
getFragmentManager().popBackStackImmediate(); getFragmentManager().popBackStackImmediate();
} }
if (id == R.id.call) { if (id == R.id.call) {
LinphoneActivity.instance() LinphoneActivity.instance().setAddresGoToDialerAndCall(mSipUri, mDisplayName);
.setAddresGoToDialerAndCall(
mSipUri,
mDisplayName,
mPictureUri == null ? null : Uri.parse(mPictureUri));
} else if (id == R.id.chat) { } else if (id == R.id.chat) {
Core lc = LinphoneManager.getLc(); Core lc = LinphoneManager.getLc();
Address participant = Factory.instance().createAddress(mSipUri); Address participant = Factory.instance().createAddress(mSipUri);

View file

@ -101,7 +101,7 @@ public class HistoryFragment extends Fragment
return view; return view;
} }
public void refresh() { private void refresh() {
mLogs = Arrays.asList(LinphoneManager.getLc().getCallLogs()); mLogs = Arrays.asList(LinphoneManager.getLc().getCallLogs());
} }
@ -122,7 +122,7 @@ public class HistoryFragment extends Fragment
private void removeNotMissedCallsFromLogs() { private void removeNotMissedCallsFromLogs() {
if (mOnlyDisplayMissedCalls) { if (mOnlyDisplayMissedCalls) {
List<CallLog> missedCalls = new ArrayList<CallLog>(); List<CallLog> missedCalls = new ArrayList<>();
for (CallLog log : mLogs) { for (CallLog log : mLogs) {
if (log.getStatus() == Call.Status.Missed) { if (log.getStatus() == Call.Status.Missed) {
missedCalls.add(log); missedCalls.add(log);
@ -248,7 +248,7 @@ public class HistoryFragment extends Fragment
} }
LinphoneActivity.instance() LinphoneActivity.instance()
.setAddresGoToDialerAndCall( .setAddresGoToDialerAndCall(
address.asStringUriOnly(), address.getDisplayName(), null); address.asStringUriOnly(), address.getDisplayName());
} }
} }
} }

View file

@ -30,16 +30,15 @@ import org.linphone.R;
public class HistoryViewHolder extends RecyclerView.ViewHolder public class HistoryViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener, View.OnLongClickListener { implements View.OnClickListener, View.OnLongClickListener {
public TextView contact; public final TextView contact;
public ImageView detail; public final ImageView detail;
public CheckBox select; public final CheckBox select;
public ImageView callDirection; public final ImageView callDirection;
public RelativeLayout avatarLayout; public final RelativeLayout avatarLayout;
public RelativeLayout CallContact; public final LinearLayout separator;
public LinearLayout separator; public final TextView separatorText;
public TextView separatorText;
private ClickListener mListener; private final ClickListener mListener;
public HistoryViewHolder(View view, ClickListener listener) { public HistoryViewHolder(View view, ClickListener listener) {
super(view); super(view);
@ -48,7 +47,6 @@ public class HistoryViewHolder extends RecyclerView.ViewHolder
select = view.findViewById(R.id.delete); select = view.findViewById(R.id.delete);
callDirection = view.findViewById(R.id.icon); callDirection = view.findViewById(R.id.icon);
avatarLayout = view.findViewById(R.id.avatar_layout); avatarLayout = view.findViewById(R.id.avatar_layout);
CallContact = view.findViewById(R.id.history_click);
separator = view.findViewById(R.id.separator); separator = view.findViewById(R.id.separator);
separatorText = view.findViewById(R.id.separator_text); separatorText = view.findViewById(R.id.separator_text);
mListener = listener; mListener = listener;

View file

@ -23,7 +23,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
public class Notifiable { public class Notifiable {
private int mNotificationId; private final int mNotificationId;
private List<NotifiableMessage> mMessages; private List<NotifiableMessage> mMessages;
private boolean mIsGroup; private boolean mIsGroup;
private String mGroupTitle; private String mGroupTitle;

View file

@ -23,12 +23,12 @@ import android.graphics.Bitmap;
import android.net.Uri; import android.net.Uri;
public class NotifiableMessage { public class NotifiableMessage {
private String mMessage; private final String mMessage;
private String mSender; private final String mSender;
private long mTime; private final long mTime;
private Bitmap mSenderBitmap; private Bitmap mSenderBitmap;
private Uri mFilePath; private final Uri mFilePath;
private String mFileMime; private final String mFileMime;
public NotifiableMessage( public NotifiableMessage(
String message, String sender, long time, Uri filePath, String fileMime) { String message, String sender, long time, Uri filePath, String fileMime) {

View file

@ -45,7 +45,7 @@ public class NotificationBroadcastReceiver extends BroadcastReceiver {
final int notifId = intent.getIntExtra(Compatibility.INTENT_NOTIF_ID, 0); final int notifId = intent.getIntExtra(Compatibility.INTENT_NOTIF_ID, 0);
final String localyIdentity = intent.getStringExtra(Compatibility.INTENT_LOCAL_IDENTITY); final String localyIdentity = intent.getStringExtra(Compatibility.INTENT_LOCAL_IDENTITY);
if (intent.getAction() == Compatibility.INTENT_REPLY_NOTIF_ACTION) { if (intent.getAction().equals(Compatibility.INTENT_REPLY_NOTIF_ACTION)) {
final String reply = getMessageText(intent).toString(); final String reply = getMessageText(intent).toString();
if (reply == null) { if (reply == null) {
Log.e("Couldn't get reply text"); Log.e("Couldn't get reply text");
@ -113,8 +113,8 @@ public class NotificationBroadcastReceiver extends BroadcastReceiver {
} }
} }
}); });
} else if (intent.getAction() == Compatibility.INTENT_ANSWER_CALL_NOTIF_ACTION } else if (intent.getAction().equals(Compatibility.INTENT_ANSWER_CALL_NOTIF_ACTION)
|| intent.getAction() == Compatibility.INTENT_HANGUP_CALL_NOTIF_ACTION) { || intent.getAction().equals(Compatibility.INTENT_HANGUP_CALL_NOTIF_ACTION)) {
String remoteAddr = String remoteAddr =
LinphoneService.instance() LinphoneService.instance()
.getNotificationManager() .getNotificationManager()
@ -131,7 +131,7 @@ public class NotificationBroadcastReceiver extends BroadcastReceiver {
return; return;
} }
if (intent.getAction() == Compatibility.INTENT_ANSWER_CALL_NOTIF_ACTION) { if (intent.getAction().equals(Compatibility.INTENT_ANSWER_CALL_NOTIF_ACTION)) {
call.accept(); call.accept();
} else { } else {
call.terminate(); call.terminate();

View file

@ -39,6 +39,7 @@ import org.linphone.contacts.ContactsManager;
import org.linphone.contacts.LinphoneContact; import org.linphone.contacts.LinphoneContact;
import org.linphone.core.Address; import org.linphone.core.Address;
import org.linphone.core.Call; import org.linphone.core.Call;
import org.linphone.mediastream.Log;
import org.linphone.mediastream.Version; import org.linphone.mediastream.Version;
import org.linphone.settings.LinphonePreferences; import org.linphone.settings.LinphonePreferences;
import org.linphone.utils.ImageUtils; import org.linphone.utils.ImageUtils;
@ -49,11 +50,12 @@ public class NotificationsManager {
private static final int MISSED_CALLS_NOTIF_ID = 2; private static final int MISSED_CALLS_NOTIF_ID = 2;
private static final int IN_APP_NOTIF_ID = 3; private static final int IN_APP_NOTIF_ID = 3;
private Context mContext; private final Context mContext;
private NotificationManager mNM; private final NotificationManager mNM;
private HashMap<String, Notifiable> mChatNotifMap, mCallNotifMap; private final HashMap<String, Notifiable> mChatNotifMap;
private final HashMap<String, Notifiable> mCallNotifMap;
private int mLastNotificationId; private int mLastNotificationId;
private Notification mServiceNotification; private final Notification mServiceNotification;
public NotificationsManager(Context context) { public NotificationsManager(Context context) {
mContext = context; mContext = context;
@ -80,6 +82,7 @@ public class NotificationsManager {
try { try {
bm = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher); bm = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher);
} catch (Exception e) { } catch (Exception e) {
Log.e(e);
} }
PendingIntent pendingIntent = PendingIntent pendingIntent =
@ -126,7 +129,7 @@ public class NotificationsManager {
} }
} }
public boolean isServiceNotificationDisplayed() { private boolean isServiceNotificationDisplayed() {
return LinphonePreferences.instance().getServiceNotificationVisibility(); return LinphonePreferences.instance().getServiceNotificationVisibility();
} }
@ -327,7 +330,6 @@ public class NotificationsManager {
mContext, mContext,
notif.getNotificationId(), notif.getNotificationId(),
showAnswerAction, showAnswerAction,
mContext.getString(R.string.service_name),
mContext.getString(notificationTextId), mContext.getString(notificationTextId),
iconId, iconId,
bm, bm,

View file

@ -47,7 +47,7 @@ public class InAppPurchaseActivity extends Activity
private List<Purchasable> mPurchasedItems; private List<Purchasable> mPurchasedItems;
private Fragment mFragment; private Fragment mFragment;
private Handler mHandler = new Handler(); private final Handler mHandler = new Handler();
public static InAppPurchaseActivity instance() { public static InAppPurchaseActivity instance() {
return sInstance; return sInstance;
@ -78,7 +78,7 @@ public class InAppPurchaseActivity extends Activity
transaction.commitAllowingStateLoss(); transaction.commitAllowingStateLoss();
} }
public void displayInappList() { private void displayInappList() {
mFragment = new InAppPurchaseListFragment(); mFragment = new InAppPurchaseListFragment();
changeFragment(mFragment); changeFragment(mFragment);
} }
@ -138,9 +138,7 @@ public class InAppPurchaseActivity extends Activity
// purchasableItemsLayout.removeAllViews(); // purchasableItemsLayout.removeAllViews();
mInProgress.setVisibility(View.GONE); mInProgress.setVisibility(View.GONE);
mPurchasedItems = new ArrayList<>(); mPurchasedItems = new ArrayList<>();
for (Purchasable item : items) { mPurchasedItems.addAll(items);
mPurchasedItems.add(item);
}
displayInappList(); displayInappList();
} }
@ -170,7 +168,7 @@ public class InAppPurchaseActivity extends Activity
xmlRpcHelper.updateAccountExpireAsync( xmlRpcHelper.updateAccountExpireAsync(
new XmlRpcListenerBase() { new XmlRpcListenerBase() {
@Override @Override
public void onAccountExpireUpdated(String result) { public void onAccountExpireUpdated() {
// TODO // TODO
} }
}, },
@ -199,7 +197,7 @@ public class InAppPurchaseActivity extends Activity
} }
@Override @Override
public void onRecoverAccountSuccessful(boolean success) {} public void onRecoverAccountSuccessful() {}
@Override @Override
public void onError(final String error) { public void onError(final String error) {

View file

@ -42,7 +42,7 @@ import org.linphone.settings.LinphonePreferences;
import org.linphone.xmlrpc.XmlRpcHelper; import org.linphone.xmlrpc.XmlRpcHelper;
import org.linphone.xmlrpc.XmlRpcListenerBase; import org.linphone.xmlrpc.XmlRpcListenerBase;
public class InAppPurchaseHelper { class InAppPurchaseHelper {
public static final int API_VERSION = 3; public static final int API_VERSION = 3;
public static final int ACTIVITY_RESULT_CODE_PURCHASE_ITEM = 11089; public static final int ACTIVITY_RESULT_CODE_PURCHASE_ITEM = 11089;
@ -90,12 +90,12 @@ public class InAppPurchaseHelper {
public static final String CLIENT_ERROR_BILLING_SERVICE_UNAVAILABLE = public static final String CLIENT_ERROR_BILLING_SERVICE_UNAVAILABLE =
"BILLING_SERVICE_UNAVAILABLE"; "BILLING_SERVICE_UNAVAILABLE";
private Context mContext; private final Context mContext;
private InAppPurchaseListener mListener; private final InAppPurchaseListener mListener;
private IInAppBillingService mService; private IInAppBillingService mService;
private ServiceConnection mServiceConn; private final ServiceConnection mServiceConn;
private Handler mHandler = new Handler(); private final Handler mHandler = new Handler();
private String mGmailAccount; private final String mGmailAccount;
public InAppPurchaseHelper(Activity context, InAppPurchaseListener listener) { public InAppPurchaseHelper(Activity context, InAppPurchaseListener listener) {
mContext = context; mContext = context;
@ -320,8 +320,7 @@ public class InAppPurchaseHelper {
for (Account account : accounts) { for (Account account : accounts) {
if (isEmailCorrect(account.name)) { if (isEmailCorrect(account.name)) {
String possibleEmail = account.name; return account.name;
return possibleEmail;
} }
} }
@ -333,7 +332,7 @@ public class InAppPurchaseHelper {
return emailPattern.matcher(email).matches(); return emailPattern.matcher(email).matches();
} }
private Purchasable verifySignature(String payload, String signature) { private Purchasable verifySignature() {
// TODO FIXME rework to be async // TODO FIXME rework to be async
/*XmlRpcHelper helper = new XmlRpcHelper(); /*XmlRpcHelper helper = new XmlRpcHelper();
if (helper.verifySignature(payload, signature)) { if (helper.verifySignature(payload, signature)) {

View file

@ -20,7 +20,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import java.util.ArrayList; import java.util.ArrayList;
public interface InAppPurchaseListener { interface InAppPurchaseListener {
/** Callback called when the in-app purchase listener is connected and available for queries */ /** Callback called when the in-app purchase listener is connected and available for queries */
void onServiceAvailableForQueries(); void onServiceAvailableForQueries();
@ -45,12 +45,8 @@ public interface InAppPurchaseListener {
*/ */
void onPurchasedItemConfirmationQueryFinished(boolean success); void onPurchasedItemConfirmationQueryFinished(boolean success);
/** /** Callback called when the account has been recovered (or not) */
* Callback called when the account has been recovered (or not) void onRecoverAccountSuccessful();
*
* @param success true if the recover has been successful, false otherwise
*/
void onRecoverAccountSuccessful(boolean success);
/** /**
* Callback called when the account has been activated (or not) * Callback called when the account has been activated (or not)

View file

@ -47,7 +47,7 @@ public class InAppPurchaseListenerBase implements InAppPurchaseListener {
} }
@Override @Override
public void onRecoverAccountSuccessful(boolean success) { public void onRecoverAccountSuccessful() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }

View file

@ -25,7 +25,10 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/ */
public class Purchasable { public class Purchasable {
private String mId, mTitle, mDescription, mPrice; private final String mId;
private String mTitle;
private String mDescription;
private String mPrice;
private long mExpire; private long mExpire;
private String mPurchasePayload, mPurchasePayloadSignature; private String mPurchasePayload, mPurchasePayloadSignature;
private String mUserData; private String mUserData;
@ -65,15 +68,6 @@ public class Purchasable {
return this; return this;
} }
public long getExpire() {
return mExpire;
}
public Purchasable setExpire(long expire) {
this.mExpire = expire;
return this;
}
public String getExpireDate() { public String getExpireDate() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.getDefault()); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.getDefault());
Date date = new Date(mExpire); Date date = new Date(mExpire);

View file

@ -32,6 +32,7 @@ import java.util.List;
import org.linphone.LinphoneManager; import org.linphone.LinphoneManager;
import org.linphone.LinphoneService; import org.linphone.LinphoneService;
import org.linphone.call.CallActivity; import org.linphone.call.CallActivity;
import org.linphone.mediastream.Log;
public class BluetoothManager extends BroadcastReceiver { public class BluetoothManager extends BroadcastReceiver {
private static BluetoothManager sInstance; private static BluetoothManager sInstance;
@ -181,6 +182,7 @@ public class BluetoothManager extends BroadcastReceiver {
try { try {
Thread.sleep(200); Thread.sleep(200);
} catch (InterruptedException e) { } catch (InterruptedException e) {
Log.e(e);
} }
if (mAudioManager != null) { if (mAudioManager != null) {
@ -257,6 +259,7 @@ public class BluetoothManager extends BroadcastReceiver {
try { try {
Thread.sleep(200); Thread.sleep(200);
} catch (InterruptedException e) { } catch (InterruptedException e) {
Log.e(e);
} }
mAudioManager.stopBluetoothSco(); mAudioManager.stopBluetoothSco();
@ -266,7 +269,7 @@ public class BluetoothManager extends BroadcastReceiver {
} }
} }
public void stopBluetooth() { private void stopBluetooth() {
android.util.Log.w("BluetoothManager", "[Bluetooth] Stopping..."); android.util.Log.w("BluetoothManager", "[Bluetooth] Stopping...");
mIsBluetoothConnected = false; mIsBluetoothConnected = false;
@ -295,6 +298,7 @@ public class BluetoothManager extends BroadcastReceiver {
mContext.unregisterReceiver(this); mContext.unregisterReceiver(this);
android.util.Log.d("BluetoothManager", "[Bluetooth] Receiver stopped"); android.util.Log.d("BluetoothManager", "[Bluetooth] Receiver stopped");
} catch (Exception e) { } catch (Exception e) {
Log.e(e);
} }
} catch (Exception e) { } catch (Exception e) {
android.util.Log.e("BluetoothManager", e.getMessage()); android.util.Log.e("BluetoothManager", e.getMessage());

View file

@ -39,9 +39,7 @@ import org.linphone.utils.LinphoneUtils;
public class KeepAliveReceiver extends BroadcastReceiver { public class KeepAliveReceiver extends BroadcastReceiver {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
if (!LinphoneService.isReady()) { if (LinphoneService.isReady()) {
return;
} else {
boolean isDebugEnabled = LinphonePreferences.instance().isDebugEnabled(); boolean isDebugEnabled = LinphonePreferences.instance().isDebugEnabled();
LinphoneUtils.initLoggingService(isDebugEnabled, context.getString(R.string.app_name)); LinphoneUtils.initLoggingService(isDebugEnabled, context.getString(R.string.app_name));
Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull(); Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();

View file

@ -35,7 +35,7 @@ public class NetworkManager extends BroadcastReceiver {
Boolean lNoConnectivity = Boolean lNoConnectivity =
intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
if (LinphoneManager.isInstanciated()) { if (LinphoneManager.isInstanciated()) {
LinphoneManager.getInstance().connectivityChanged(cm, lNoConnectivity); LinphoneManager.getInstance().connectivityChanged();
} }
} }
} }

View file

@ -33,15 +33,16 @@ import org.linphone.core.Player;
import org.linphone.core.PlayerListener; import org.linphone.core.PlayerListener;
import org.linphone.mediastream.Log; import org.linphone.mediastream.Log;
public class Recording implements PlayerListener, Comparable<Recording> { class Recording implements PlayerListener, Comparable<Recording> {
public static final Pattern RECORD_PATTERN = public static final Pattern RECORD_PATTERN =
Pattern.compile(".*/(.*)_(\\d{2}-\\d{2}-\\d{4}-\\d{2}-\\d{2}-\\d{2})\\..*"); Pattern.compile(".*/(.*)_(\\d{2}-\\d{2}-\\d{4}-\\d{2}-\\d{2}-\\d{2})\\..*");
private String mRecordPath, mName; private final String mRecordPath;
private String mName;
private Date mRecordDate; private Date mRecordDate;
private Player mPlayer; private final Player mPlayer;
private RecordingListener mListener; private RecordingListener mListener;
private Handler mHandler; private final Handler mHandler;
private Runnable mUpdateCurrentPositionTimer; private Runnable mUpdateCurrentPositionTimer;
@SuppressLint("SimpleDateFormat") @SuppressLint("SimpleDateFormat")

View file

@ -19,7 +19,7 @@ along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/ */
public interface RecordingListener { interface RecordingListener {
void currentPositionChanged(int currentPosition); void currentPositionChanged(int currentPosition);
void endOfRecordReached(); void endOfRecordReached();

View file

@ -30,14 +30,17 @@ import org.linphone.R;
public class RecordingViewHolder extends RecyclerView.ViewHolder public class RecordingViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener, View.OnLongClickListener { implements View.OnClickListener, View.OnLongClickListener {
public ImageView playButton; public final ImageView playButton;
public TextView name, date, currentPosition, duration; public final TextView name;
public SeekBar progressionBar; public final TextView date;
public CheckBox select; public final TextView currentPosition;
public LinearLayout separator; public final TextView duration;
public TextView separatorText; public final SeekBar progressionBar;
public final CheckBox select;
public final LinearLayout separator;
public final TextView separatorText;
private RecordingViewHolder.ClickListener mListener; private final RecordingViewHolder.ClickListener mListener;
public RecordingViewHolder(View view, RecordingViewHolder.ClickListener listener) { public RecordingViewHolder(View view, RecordingViewHolder.ClickListener listener) {
super(view); super(view);

View file

@ -30,15 +30,16 @@ import java.text.SimpleDateFormat;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.linphone.R; import org.linphone.R;
import org.linphone.utils.SelectableAdapter; import org.linphone.utils.SelectableAdapter;
import org.linphone.utils.SelectableHelper; import org.linphone.utils.SelectableHelper;
public class RecordingsAdapter extends SelectableAdapter<RecordingViewHolder> { public class RecordingsAdapter extends SelectableAdapter<RecordingViewHolder> {
private List<Recording> mRecordings; private final List<Recording> mRecordings;
private Context mContext; private final Context mContext;
private RecordingViewHolder.ClickListener mClickListener; private final RecordingViewHolder.ClickListener mClickListener;
public RecordingsAdapter( public RecordingsAdapter(
Context context, Context context,
@ -119,6 +120,7 @@ public class RecordingsAdapter extends SelectableAdapter<RecordingViewHolder> {
int position = record.getCurrentPosition(); int position = record.getCurrentPosition();
viewHolder.currentPosition.setText( viewHolder.currentPosition.setText(
String.format( String.format(
Locale.getDefault(),
"%02d:%02d", "%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(position), TimeUnit.MILLISECONDS.toMinutes(position),
TimeUnit.MILLISECONDS.toSeconds(position) TimeUnit.MILLISECONDS.toSeconds(position)
@ -128,6 +130,7 @@ public class RecordingsAdapter extends SelectableAdapter<RecordingViewHolder> {
int duration = record.getDuration(); int duration = record.getDuration();
viewHolder.duration.setText( viewHolder.duration.setText(
String.format( String.format(
Locale.getDefault(),
"%02d:%02d", "%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(duration), TimeUnit.MILLISECONDS.toMinutes(duration),
TimeUnit.MILLISECONDS.toSeconds(duration) TimeUnit.MILLISECONDS.toSeconds(duration)
@ -154,6 +157,7 @@ public class RecordingsAdapter extends SelectableAdapter<RecordingViewHolder> {
int currentPosition = record.getCurrentPosition(); int currentPosition = record.getCurrentPosition();
viewHolder.currentPosition.setText( viewHolder.currentPosition.setText(
String.format( String.format(
Locale.getDefault(),
"%02d:%02d", "%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(currentPosition), TimeUnit.MILLISECONDS.toMinutes(currentPosition),
TimeUnit.MILLISECONDS.toSeconds(currentPosition) TimeUnit.MILLISECONDS.toSeconds(currentPosition)
@ -176,6 +180,7 @@ public class RecordingsAdapter extends SelectableAdapter<RecordingViewHolder> {
public void currentPositionChanged(int currentPosition) { public void currentPositionChanged(int currentPosition) {
viewHolder.currentPosition.setText( viewHolder.currentPosition.setText(
String.format( String.format(
Locale.getDefault(),
"%02d:%02d", "%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(currentPosition), TimeUnit.MILLISECONDS.toMinutes(currentPosition),
TimeUnit.MILLISECONDS.toSeconds(currentPosition) TimeUnit.MILLISECONDS.toSeconds(currentPosition)

View file

@ -104,7 +104,7 @@ public class RecordingsFragment extends Fragment
} }
} }
public void removeDeletedRecordings() { private void removeDeletedRecordings() {
String recordingsDirectory = FileUtils.getRecordingsDirectory(mContext); String recordingsDirectory = FileUtils.getRecordingsDirectory(mContext);
File directory = new File(recordingsDirectory); File directory = new File(recordingsDirectory);
@ -127,7 +127,7 @@ public class RecordingsFragment extends Fragment
} }
} }
public void searchForRecordings() { private void searchForRecordings() {
String recordingsDirectory = FileUtils.getRecordingsDirectory(mContext); String recordingsDirectory = FileUtils.getRecordingsDirectory(mContext);
File directory = new File(recordingsDirectory); File directory = new File(recordingsDirectory);

View file

@ -48,7 +48,7 @@ import org.linphone.utils.LinphoneUtils;
public class AccountPreferencesFragment extends PreferencesListFragment public class AccountPreferencesFragment extends PreferencesListFragment
implements AccountCreatorListener { implements AccountCreatorListener {
private int mN; private int mN;
private OnPreferenceClickListener linkAccountListener = private final OnPreferenceClickListener linkAccountListener =
new OnPreferenceClickListener() { new OnPreferenceClickListener() {
@Override @Override
public boolean onPreferenceClick(Preference preference) { public boolean onPreferenceClick(Preference preference) {
@ -62,8 +62,8 @@ public class AccountPreferencesFragment extends PreferencesListFragment
} }
}; };
private boolean mIsNewAccount = false; private boolean mIsNewAccount = false;
private LinphonePreferences mPrefs; private final LinphonePreferences mPrefs;
private OnPreferenceChangeListener mAvpfRRIntervalChangedListener = private final OnPreferenceChangeListener mAvpfRRIntervalChangedListener =
new OnPreferenceChangeListener() { new OnPreferenceChangeListener() {
@Override @Override
public boolean onPreferenceChange(Preference preference, Object newValue) { public boolean onPreferenceChange(Preference preference, Object newValue) {
@ -74,6 +74,7 @@ public class AccountPreferencesFragment extends PreferencesListFragment
return false; return false;
} }
} catch (NumberFormatException nfe) { } catch (NumberFormatException nfe) {
Log.e(nfe);
} }
if (mIsNewAccount) { if (mIsNewAccount) {
// TODO // TODO
@ -84,7 +85,7 @@ public class AccountPreferencesFragment extends PreferencesListFragment
return true; return true;
} }
}; };
private OnPreferenceChangeListener mEscapeChangedListener = private final OnPreferenceChangeListener mEscapeChangedListener =
new OnPreferenceChangeListener() { new OnPreferenceChangeListener() {
@Override @Override
public boolean onPreferenceChange(Preference preference, Object newValue) { public boolean onPreferenceChange(Preference preference, Object newValue) {
@ -97,7 +98,7 @@ public class AccountPreferencesFragment extends PreferencesListFragment
return true; return true;
} }
}; };
private OnPreferenceChangeListener mPushNotificationListener = private final OnPreferenceChangeListener mPushNotificationListener =
new OnPreferenceChangeListener() { new OnPreferenceChangeListener() {
@Override @Override
public boolean onPreferenceChange(Preference preference, Object newValue) { public boolean onPreferenceChange(Preference preference, Object newValue) {
@ -110,7 +111,7 @@ public class AccountPreferencesFragment extends PreferencesListFragment
return true; return true;
} }
}; };
private OnPreferenceChangeListener mIceChangedListener = private final OnPreferenceChangeListener mIceChangedListener =
new OnPreferenceChangeListener() { new OnPreferenceChangeListener() {
@Override @Override
public boolean onPreferenceChange(Preference preference, Object newValue) { public boolean onPreferenceChange(Preference preference, Object newValue) {
@ -123,7 +124,7 @@ public class AccountPreferencesFragment extends PreferencesListFragment
return true; return true;
} }
}; };
private OnPreferenceChangeListener mStunTurnChangedListener = private final OnPreferenceChangeListener mStunTurnChangedListener =
new OnPreferenceChangeListener() { new OnPreferenceChangeListener() {
@Override @Override
public boolean onPreferenceChange(Preference preference, Object newValue) { public boolean onPreferenceChange(Preference preference, Object newValue) {
@ -137,7 +138,7 @@ public class AccountPreferencesFragment extends PreferencesListFragment
} }
}; };
private EditTextPreference mProxyPreference; private EditTextPreference mProxyPreference;
private OnPreferenceChangeListener mTransportChangedListener = private final OnPreferenceChangeListener mTransportChangedListener =
new OnPreferenceChangeListener() { new OnPreferenceChangeListener() {
@Override @Override
public boolean onPreferenceChange(Preference preference, Object newValue) { public boolean onPreferenceChange(Preference preference, Object newValue) {
@ -160,7 +161,7 @@ public class AccountPreferencesFragment extends PreferencesListFragment
}; };
private ListPreference mTransportPreference; private ListPreference mTransportPreference;
private AccountBuilder mBuilder; private AccountBuilder mBuilder;
private OnPreferenceChangeListener mUsernameChangedListener = private final OnPreferenceChangeListener mUsernameChangedListener =
new OnPreferenceChangeListener() { new OnPreferenceChangeListener() {
@Override @Override
public boolean onPreferenceChange(Preference preference, Object newValue) { public boolean onPreferenceChange(Preference preference, Object newValue) {
@ -174,7 +175,7 @@ public class AccountPreferencesFragment extends PreferencesListFragment
return true; return true;
} }
}; };
private OnPreferenceChangeListener mUseridChangedListener = private final OnPreferenceChangeListener mUseridChangedListener =
new OnPreferenceChangeListener() { new OnPreferenceChangeListener() {
@Override @Override
public boolean onPreferenceChange(Preference preference, Object newValue) { public boolean onPreferenceChange(Preference preference, Object newValue) {
@ -187,7 +188,7 @@ public class AccountPreferencesFragment extends PreferencesListFragment
return true; return true;
} }
}; };
private OnPreferenceChangeListener mPasswordChangedListener = private final OnPreferenceChangeListener mPasswordChangedListener =
new OnPreferenceChangeListener() { new OnPreferenceChangeListener() {
@Override @Override
public boolean onPreferenceChange(Preference preference, Object newValue) { public boolean onPreferenceChange(Preference preference, Object newValue) {
@ -200,7 +201,7 @@ public class AccountPreferencesFragment extends PreferencesListFragment
return true; return true;
} }
}; };
private OnPreferenceChangeListener mDomainChangedListener = private final OnPreferenceChangeListener mDomainChangedListener =
new OnPreferenceChangeListener() { new OnPreferenceChangeListener() {
@Override @Override
public boolean onPreferenceChange(Preference preference, Object newValue) { public boolean onPreferenceChange(Preference preference, Object newValue) {
@ -214,7 +215,7 @@ public class AccountPreferencesFragment extends PreferencesListFragment
return true; return true;
} }
}; };
private OnPreferenceChangeListener mDisplayNameChangedListener = private final OnPreferenceChangeListener mDisplayNameChangedListener =
new OnPreferenceChangeListener() { new OnPreferenceChangeListener() {
@Override @Override
public boolean onPreferenceChange(Preference preference, Object newValue) { public boolean onPreferenceChange(Preference preference, Object newValue) {
@ -227,7 +228,7 @@ public class AccountPreferencesFragment extends PreferencesListFragment
return true; return true;
} }
}; };
private OnPreferenceChangeListener mProxyChangedListener = private final OnPreferenceChangeListener mProxyChangedListener =
new OnPreferenceChangeListener() { new OnPreferenceChangeListener() {
@Override @Override
public boolean onPreferenceChange(Preference preference, Object newValue) { public boolean onPreferenceChange(Preference preference, Object newValue) {
@ -247,7 +248,7 @@ public class AccountPreferencesFragment extends PreferencesListFragment
return true; return true;
} }
}; };
private OnPreferenceChangeListener mOutboundProxyChangedListener = private final OnPreferenceChangeListener mOutboundProxyChangedListener =
new OnPreferenceChangeListener() { new OnPreferenceChangeListener() {
@Override @Override
public boolean onPreferenceChange(Preference preference, Object newValue) { public boolean onPreferenceChange(Preference preference, Object newValue) {
@ -259,7 +260,7 @@ public class AccountPreferencesFragment extends PreferencesListFragment
return true; return true;
} }
}; };
private OnPreferenceChangeListener mExpiresChangedListener = private final OnPreferenceChangeListener mExpiresChangedListener =
new OnPreferenceChangeListener() { new OnPreferenceChangeListener() {
@Override @Override
public boolean onPreferenceChange(Preference preference, Object newValue) { public boolean onPreferenceChange(Preference preference, Object newValue) {
@ -272,7 +273,7 @@ public class AccountPreferencesFragment extends PreferencesListFragment
return true; return true;
} }
}; };
private OnPreferenceChangeListener mPrefixChangedListener = private final OnPreferenceChangeListener mPrefixChangedListener =
new OnPreferenceChangeListener() { new OnPreferenceChangeListener() {
@Override @Override
public boolean onPreferenceChange(Preference preference, Object newValue) { public boolean onPreferenceChange(Preference preference, Object newValue) {
@ -286,7 +287,7 @@ public class AccountPreferencesFragment extends PreferencesListFragment
return true; return true;
} }
}; };
private OnPreferenceChangeListener mAvpfChangedListener = private final OnPreferenceChangeListener mAvpfChangedListener =
new OnPreferenceChangeListener() { new OnPreferenceChangeListener() {
@Override @Override
public boolean onPreferenceChange(Preference preference, Object newValue) { public boolean onPreferenceChange(Preference preference, Object newValue) {
@ -297,7 +298,7 @@ public class AccountPreferencesFragment extends PreferencesListFragment
return true; return true;
} }
}; };
private OnPreferenceChangeListener mDisableChangedListener = private final OnPreferenceChangeListener mDisableChangedListener =
new OnPreferenceChangeListener() { new OnPreferenceChangeListener() {
@Override @Override
public boolean onPreferenceChange(Preference preference, Object newValue) { public boolean onPreferenceChange(Preference preference, Object newValue) {
@ -317,7 +318,7 @@ public class AccountPreferencesFragment extends PreferencesListFragment
mPrefs = LinphonePreferences.instance(); mPrefs = LinphonePreferences.instance();
} }
public static boolean isEditTextEmpty(String s) { private static boolean isEditTextEmpty(String s) {
return s.equals(""); // really empty. return s.equals(""); // really empty.
} }
@ -340,7 +341,7 @@ public class AccountPreferencesFragment extends PreferencesListFragment
mIsNewAccount = true; mIsNewAccount = true;
mBuilder = new AccountBuilder(LinphoneManager.getLc()); mBuilder = new AccountBuilder(LinphoneManager.getLc());
} }
initAccountPreferencesFields(screen); initAccountPreferencesFields();
// Force hide keyboard // Force hide keyboard
getActivity() getActivity()
@ -348,7 +349,7 @@ public class AccountPreferencesFragment extends PreferencesListFragment
.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
} }
private void initAccountPreferencesFields(PreferenceScreen parent) { private void initAccountPreferencesFields() {
boolean isDefaultAccount = mPrefs.getDefaultAccountIndex() == mN; boolean isDefaultAccount = mPrefs.getDefaultAccountIndex() == mN;
NatPolicy natPolicy = null; NatPolicy natPolicy = null;
if (LinphoneManager.getLcIfManagerNotDestroyedOrNull() != null if (LinphoneManager.getLcIfManagerNotDestroyedOrNull() != null
@ -531,8 +532,8 @@ public class AccountPreferencesFragment extends PreferencesListFragment
} }
private void initializeTransportPreference(ListPreference pref) { private void initializeTransportPreference(ListPreference pref) {
List<CharSequence> entries = new ArrayList<CharSequence>(); List<CharSequence> entries = new ArrayList<>();
List<CharSequence> values = new ArrayList<CharSequence>(); List<CharSequence> values = new ArrayList<>();
entries.add(getString(R.string.pref_transport_udp)); entries.add(getString(R.string.pref_transport_udp));
values.add(getString(R.string.pref_transport_udp_key)); values.add(getString(R.string.pref_transport_udp_key));
entries.add(getString(R.string.pref_transport_tcp)); entries.add(getString(R.string.pref_transport_tcp));

View file

@ -61,7 +61,7 @@ public class LinphonePreferences {
private LinphonePreferences() {} private LinphonePreferences() {}
public static final synchronized LinphonePreferences instance() { public static synchronized LinphonePreferences instance() {
if (sInstance == null) { if (sInstance == null) {
sInstance = new LinphonePreferences(); sInstance = new LinphonePreferences();
} }
@ -147,8 +147,7 @@ public class LinphonePreferences {
ProxyConfig prxCfg = getProxyConfig(n); ProxyConfig prxCfg = getProxyConfig(n);
if (prxCfg == null) return null; if (prxCfg == null) return null;
Address addr = prxCfg.getIdentityAddress(); Address addr = prxCfg.getIdentityAddress();
AuthInfo authInfo = getLc().findAuthInfo(null, addr.getUsername(), addr.getDomain()); return getLc().findAuthInfo(null, addr.getUsername(), addr.getDomain());
return authInfo;
} }
/** /**
@ -207,7 +206,7 @@ public class LinphonePreferences {
} }
} }
public TransportType getAccountTransport(int n) { private TransportType getAccountTransport(int n) {
TransportType transport = null; TransportType transport = null;
ProxyConfig proxyConfig = getProxyConfig(n); ProxyConfig proxyConfig = getProxyConfig(n);
@ -303,16 +302,12 @@ public class LinphonePreferences {
return authInfo == null ? null : authInfo.getUserid(); return authInfo == null ? null : authInfo.getUserid();
} }
public String getAccountRealm(int n) { private String getAccountRealm(int n) {
AuthInfo authInfo = getAuthInfo(n); AuthInfo authInfo = getAuthInfo(n);
return authInfo == null ? null : authInfo.getRealm(); return authInfo == null ? null : authInfo.getRealm();
} }
public void setAccountPassword(int n, String password) { public void setAccountPassword(int n, String password) {
setAccountPassword(n, password, null);
}
private void setAccountPassword(int n, String password, String ha1) {
if (getLc() == null) return; if (getLc() == null) return;
String user = getAccountUsername(n); String user = getAccountUsername(n);
String domain = getAccountDomain(n); String domain = getAccountDomain(n);
@ -327,7 +322,7 @@ public class LinphonePreferences {
.removeAuthInfo(LinphoneManager.getLc().getAuthInfoList()[n]); .removeAuthInfo(LinphoneManager.getLc().getAuthInfoList()[n]);
} }
AuthInfo authInfo = AuthInfo authInfo =
Factory.instance().createAuthInfo(user, userid, password, ha1, realm, domain); Factory.instance().createAuthInfo(user, userid, password, null, realm, domain);
LinphoneManager.getLc().addAuthInfo(authInfo); LinphoneManager.getLc().addAuthInfo(authInfo);
} }
} }
@ -422,8 +417,7 @@ public class LinphonePreferences {
} }
public String getAccountProxy(int n) { public String getAccountProxy(int n) {
String proxy = getProxyConfig(n).getServerAddr(); return getProxyConfig(n).getServerAddr();
return proxy;
} }
public void setAccountOutboundProxyEnabled(int n, boolean enabled) { public void setAccountOutboundProxyEnabled(int n, boolean enabled) {
@ -442,13 +436,6 @@ public class LinphonePreferences {
return getProxyConfig(n).getRoute() != null; 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) { public String getExpires(int n) {
return String.valueOf(getProxyConfig(n).getExpires()); return String.valueOf(getProxyConfig(n).getExpires());
} }
@ -460,6 +447,7 @@ public class LinphonePreferences {
prxCfg.setExpires(Integer.parseInt(expire)); prxCfg.setExpires(Integer.parseInt(expire));
prxCfg.done(); prxCfg.done();
} catch (NumberFormatException nfe) { } catch (NumberFormatException nfe) {
Log.e(nfe);
} }
} }
@ -496,6 +484,7 @@ public class LinphonePreferences {
prxCfg.setAvpfRrInterval(Integer.parseInt(interval)); prxCfg.setAvpfRrInterval(Integer.parseInt(interval));
prxCfg.done(); prxCfg.done();
} catch (NumberFormatException nfe) { } catch (NumberFormatException nfe) {
Log.e(nfe);
} }
} }
@ -798,7 +787,7 @@ public class LinphonePreferences {
useRandomPort(enabled, true); useRandomPort(enabled, true);
} }
public void useRandomPort(boolean enabled, boolean apply) { private void useRandomPort(boolean enabled, boolean apply) {
getConfig().setBool("app", "random_port", enabled); getConfig().setBool("app", "random_port", enabled);
if (apply) { if (apply) {
if (enabled) { if (enabled) {
@ -850,7 +839,6 @@ public class LinphonePreferences {
NatPolicy nat = getOrCreateNatPolicy(); NatPolicy nat = getOrCreateNatPolicy();
nat.setStunServer(stun); nat.setStunServer(stun);
if (stun != null && !stun.isEmpty()) {}
getLc().setNatPolicy(nat); getLc().setNatPolicy(nat);
} }
@ -1017,7 +1005,7 @@ public class LinphonePreferences {
} }
} }
public String getPushNotificationRegistrationID() { private String getPushNotificationRegistrationID() {
return getConfig().getString("app", "push_notification_regid", null); return getConfig().getString("app", "push_notification_regid", null);
} }
@ -1185,7 +1173,7 @@ public class LinphonePreferences {
public boolean isProvisioningLoginViewEnabled() { public boolean isProvisioningLoginViewEnabled() {
return (getConfig() != null) ? getConfig().getBool("app", "show_login_view", false) : false; return (getConfig() != null) && getConfig().getBool("app", "show_login_view", false);
} }
// End of tunnel settings // End of tunnel settings
@ -1230,11 +1218,7 @@ public class LinphonePreferences {
getConfig().getString("in-app-purchase", "purchase_item_signature", null); getConfig().getString("in-app-purchase", "purchase_item_signature", null);
String username = getConfig().getString("in-app-purchase", "purchase_item_username", null); String username = getConfig().getString("in-app-purchase", "purchase_item_username", null);
Purchasable item = return new Purchasable(id).setPayloadAndSignature(payload, signature).setUserData(username);
new Purchasable(id)
.setPayloadAndSignature(payload, signature)
.setUserData(username);
return item;
} }
public void setInAppPurchasedItem(Purchasable item) { public void setInAppPurchasedItem(Purchasable item) {
@ -1249,7 +1233,7 @@ public class LinphonePreferences {
} }
public ArrayList<String> getInAppPurchasables() { public ArrayList<String> getInAppPurchasables() {
ArrayList<String> purchasables = new ArrayList<String>(); ArrayList<String> purchasables = new ArrayList<>();
String list = getConfig().getString("in-app-purchase", "purchasable_items_ids", null); String list = getConfig().getString("in-app-purchase", "purchasable_items_ids", null);
if (list != null) { if (list != null) {
for (String purchasable : list.split(";")) { for (String purchasable : list.split(";")) {
@ -1344,7 +1328,7 @@ public class LinphonePreferences {
return firstTimeAskingForPermission(permission, true); return firstTimeAskingForPermission(permission, true);
} }
public boolean firstTimeAskingForPermission(String permission, boolean toggle) { private boolean firstTimeAskingForPermission(String permission, boolean toggle) {
boolean firstTime = getConfig().getBool("app", permission, true); boolean firstTime = getConfig().getBool("app", permission, true);
if (toggle) { if (toggle) {
permissionHasBeenAsked(permission); permissionHasBeenAsked(permission);
@ -1352,7 +1336,7 @@ public class LinphonePreferences {
return firstTime; return firstTime;
} }
public void permissionHasBeenAsked(String permission) { private void permissionHasBeenAsked(String permission) {
getConfig().setBool("app", permission, false); getConfig().setBool("app", permission, false);
} }
@ -1421,7 +1405,7 @@ public class LinphonePreferences {
} }
public static class AccountBuilder { public static class AccountBuilder {
private Core lc; private final Core lc;
private String tempUsername; private String tempUsername;
private String tempDisplayName; private String tempDisplayName;
private String tempUserId; private String tempUserId;
@ -1434,10 +1418,10 @@ public class LinphonePreferences {
private String tempExpire; private String tempExpire;
private TransportType tempTransport; private TransportType tempTransport;
private int tempAvpfRRInterval = 0; private int tempAvpfRRInterval = 0;
private boolean tempQualityReportingEnabled = false; private final boolean tempQualityReportingEnabled = false;
private int tempQualityReportingInterval = 0; private final int tempQualityReportingInterval = 0;
private boolean tempEnabled = true; private boolean tempEnabled = true;
private boolean tempNoDefault = false; private final boolean tempNoDefault = false;
public AccountBuilder(Core lc) { public AccountBuilder(Core lc) {
this.lc = lc; this.lc = lc;

View file

@ -51,7 +51,7 @@ public class PreferencesListFragment extends ListFragment {
private PreferenceManager mPreferenceManager; private PreferenceManager mPreferenceManager;
private ListView mPreferencesList; private ListView mPreferencesList;
private Handler mHandler = private final Handler mHandler =
new Handler() { new Handler() {
@Override @Override
public void handleMessage(Message msg) { public void handleMessage(Message msg) {
@ -64,7 +64,7 @@ public class PreferencesListFragment extends ListFragment {
}; };
private int mXmlResID; private int mXmlResID;
public PreferencesListFragment(int xmlId) { PreferencesListFragment(int xmlId) {
mXmlResID = xmlId; mXmlResID = xmlId;
} }
@ -188,9 +188,7 @@ public class PreferencesListFragment extends ListFragment {
Constructor<PreferenceManager> c = Constructor<PreferenceManager> c =
PreferenceManager.class.getDeclaredConstructor(Activity.class, int.class); PreferenceManager.class.getDeclaredConstructor(Activity.class, int.class);
c.setAccessible(true); c.setAccessible(true);
PreferenceManager preferenceManager = return c.newInstance(this.getActivity(), FIRST_REQUEST_CODE);
c.newInstance(this.getActivity(), FIRST_REQUEST_CODE);
return preferenceManager;
} catch (Exception e) { } catch (Exception e) {
Log.e("[PreferencesListFragment] onCreatePreferenceManager " + e); Log.e("[PreferencesListFragment] onCreatePreferenceManager " + e);
return null; return null;
@ -202,7 +200,7 @@ public class PreferencesListFragment extends ListFragment {
* *
* @return The {@link PreferenceManager}. * @return The {@link PreferenceManager}.
*/ */
public PreferenceManager getPreferenceManager() { PreferenceManager getPreferenceManager() {
return mPreferenceManager; return mPreferenceManager;
} }
@ -211,7 +209,7 @@ public class PreferencesListFragment extends ListFragment {
* *
* @return The {@link PreferenceScreen} that is the root of the preference hierarchy. * @return The {@link PreferenceScreen} that is the root of the preference hierarchy.
*/ */
public PreferenceScreen getPreferenceScreen() { PreferenceScreen getPreferenceScreen() {
try { try {
Method m = PreferenceManager.class.getDeclaredMethod("getPreferenceScreen"); Method m = PreferenceManager.class.getDeclaredMethod("getPreferenceScreen");
m.setAccessible(true); m.setAccessible(true);
@ -228,7 +226,7 @@ public class PreferencesListFragment extends ListFragment {
* *
* @param preferenceScreen The root {@link PreferenceScreen} of the preference hierarchy. * @param preferenceScreen The root {@link PreferenceScreen} of the preference hierarchy.
*/ */
public void setPreferenceScreen(PreferenceScreen preferenceScreen) { private void setPreferenceScreen(PreferenceScreen preferenceScreen) {
try { try {
Method m = Method m =
PreferenceManager.class.getDeclaredMethod( PreferenceManager.class.getDeclaredMethod(
@ -249,7 +247,7 @@ public class PreferencesListFragment extends ListFragment {
* *
* @param preferencesResId The XML resource ID to inflate. * @param preferencesResId The XML resource ID to inflate.
*/ */
public void addPreferencesFromResource(int preferencesResId) { private void addPreferencesFromResource(int preferencesResId) {
try { try {
Method m = Method m =
PreferenceManager.class.getDeclaredMethod( PreferenceManager.class.getDeclaredMethod(
@ -278,7 +276,7 @@ public class PreferencesListFragment extends ListFragment {
* @return The {@link Preference} with the key, or null. * @return The {@link Preference} with the key, or null.
* @see PreferenceGroup#findPreference(CharSequence) * @see PreferenceGroup#findPreference(CharSequence)
*/ */
public Preference findPreference(CharSequence key) { Preference findPreference(CharSequence key) {
if (mPreferenceManager == null) { if (mPreferenceManager == null) {
Log.e("[PreferencesListFragment] PreferenceManager is null !"); Log.e("[PreferencesListFragment] PreferenceManager is null !");
return null; return null;

View file

@ -28,6 +28,7 @@ import android.content.SharedPreferences;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.media.AudioManager; import android.media.AudioManager;
import android.net.Uri; import android.net.Uri;
import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler; import android.os.Handler;
import android.preference.CheckBoxPreference; import android.preference.CheckBoxPreference;
@ -48,7 +49,6 @@ import org.linphone.LinphoneService;
import org.linphone.R; import org.linphone.R;
import org.linphone.core.Address; import org.linphone.core.Address;
import org.linphone.core.Core; import org.linphone.core.Core;
import org.linphone.core.CoreException;
import org.linphone.core.CoreListenerStub; import org.linphone.core.CoreListenerStub;
import org.linphone.core.EcCalibratorStatus; import org.linphone.core.EcCalibratorStatus;
import org.linphone.core.Factory; import org.linphone.core.Factory;
@ -69,10 +69,10 @@ import org.linphone.views.LedPreference;
public class SettingsFragment extends PreferencesListFragment { public class SettingsFragment extends PreferencesListFragment {
private LinphonePreferences mPrefs; private LinphonePreferences mPrefs;
private Handler mHandler = new Handler(); private final Handler mHandler = new Handler();
private CoreListenerStub mListener; private CoreListenerStub mListener;
private PreferenceScreen mCurrentPreferenceScreen; private PreferenceScreen mCurrentPreferenceScreen;
private Preference.OnPreferenceClickListener mPrefClickListener = private final Preference.OnPreferenceClickListener mPrefClickListener =
new Preference.OnPreferenceClickListener() { new Preference.OnPreferenceClickListener() {
@Override @Override
public boolean onPreferenceClick(Preference preference) { public boolean onPreferenceClick(Preference preference) {
@ -445,8 +445,8 @@ public class SettingsFragment extends PreferencesListFragment {
} }
private void initMediaEncryptionPreference(ListPreference pref) { private void initMediaEncryptionPreference(ListPreference pref) {
List<CharSequence> entries = new ArrayList<CharSequence>(); List<CharSequence> entries = new ArrayList<>();
List<CharSequence> values = new ArrayList<CharSequence>(); List<CharSequence> values = new ArrayList<>();
entries.add(getString(R.string.pref_none)); entries.add(getString(R.string.pref_none));
values.add(getString(R.string.pref_media_encryption_key_none)); values.add(getString(R.string.pref_media_encryption_key_none));
@ -493,8 +493,8 @@ public class SettingsFragment extends PreferencesListFragment {
} }
private void initializePreferredVideoSizePreferences(ListPreference pref) { private void initializePreferredVideoSizePreferences(ListPreference pref) {
List<CharSequence> entries = new ArrayList<CharSequence>(); List<CharSequence> entries = new ArrayList<>();
List<CharSequence> values = new ArrayList<CharSequence>(); List<CharSequence> values = new ArrayList<>();
for (VideoDefinition vd : Factory.instance().getSupportedVideoDefinitions()) { for (VideoDefinition vd : Factory.instance().getSupportedVideoDefinitions()) {
entries.add(vd.getName()); entries.add(vd.getName());
values.add(vd.getName()); values.add(vd.getName());
@ -508,8 +508,8 @@ public class SettingsFragment extends PreferencesListFragment {
} }
private void initializePreferredVideoFpsPreferences(ListPreference pref) { private void initializePreferredVideoFpsPreferences(ListPreference pref) {
List<CharSequence> entries = new ArrayList<CharSequence>(); List<CharSequence> entries = new ArrayList<>();
List<CharSequence> values = new ArrayList<CharSequence>(); List<CharSequence> values = new ArrayList<>();
entries.add(getString(R.string.pref_none)); entries.add(getString(R.string.pref_none));
values.add("0"); values.add("0");
for (int i = 5; i <= 30; i += 5) { for (int i = 5; i <= 30; i += 5) {
@ -582,13 +582,7 @@ public class SettingsFragment extends PreferencesListFragment {
codec.setTitle(pt.getMimeType()); codec.setTitle(pt.getMimeType());
/* Special case */ /* Special case */
if (pt.getMimeType().equals("mpeg4-generic")) { if (pt.getMimeType().equals("mpeg4-generic")) {
if (android.os.Build.VERSION.SDK_INT < 16) { codec.setTitle("AAC-ELD");
/* Make sure AAC is disabled */
pt.enable(false);
continue;
} else {
codec.setTitle("AAC-ELD");
}
} }
codec.setSummary(pt.getClockRate() + " Hz"); codec.setSummary(pt.getClockRate() + " Hz");
@ -733,34 +727,22 @@ public class SettingsFragment extends PreferencesListFragment {
public void startEchoTester() { public void startEchoTester() {
Preference preference = findPreference(getString(R.string.pref_echo_tester_key)); Preference preference = findPreference(getString(R.string.pref_echo_tester_key));
try { if (LinphoneManager.getInstance().startEchoTester() > 0) {
if (LinphoneManager.getInstance().startEchoTester() > 0) { preference.setSummary("Is running");
preference.setSummary("Is running");
}
} catch (CoreException e) {
e.printStackTrace();
} }
} }
public void stopEchoTester() { private void stopEchoTester() {
Preference preference = findPreference(getString(R.string.pref_echo_tester_key)); Preference preference = findPreference(getString(R.string.pref_echo_tester_key));
try { if (LinphoneManager.getInstance().stopEchoTester() > 0) {
if (LinphoneManager.getInstance().stopEchoTester() > 0) { preference.setSummary("Is stopped");
preference.setSummary("Is stopped");
}
} catch (CoreException e) {
e.printStackTrace();
} }
} }
public void startEchoCancellerCalibration() { public void startEchoCancellerCalibration() {
try { if (LinphoneManager.getInstance().getEchoTesterStatus()) stopEchoTester();
if (LinphoneManager.getInstance().getEchoTesterStatus()) stopEchoTester(); LinphoneManager.getLc().addListener(mListener);
LinphoneManager.getLc().addListener(mListener); LinphoneManager.getInstance().startEcCalibration();
LinphoneManager.getInstance().startEcCalibration();
} catch (CoreException e) {
Log.e(e);
}
} }
public void echoCalibrationFail() { public void echoCalibrationFail() {
@ -891,20 +873,7 @@ public class SettingsFragment extends PreferencesListFragment {
mCodecDownloader.downloadCodec(); mCodecDownloader.downloadCodec();
} }
}); });
builder.setNegativeButton( builder.setNegativeButton("No", null).show();
"No",
new DialogInterface.OnClickListener() {
@Override
public void onClick(
DialogInterface dialog, int which) {
if (which
== DialogInterface
.BUTTON_NEGATIVE) {
// Disable H264
}
}
})
.show();
} }
} }
pt.enable(enable); pt.enable(enable);
@ -915,7 +884,7 @@ public class SettingsFragment extends PreferencesListFragment {
codecs.addPreference(codec); codecs.addPreference(codec);
} }
// Adding OpenH264 button on device < 5.1 // Adding OpenH264 button on device < 5.1
if (mCodecDownloader.isOpenH264DownloadEnabled() && !h264IsHere) { if (OpenH264DownloadHelper.isOpenH264DownloadEnabled() && !h264IsHere) {
final CheckBoxPreference codec = new CheckBoxPreference(getActivity()); final CheckBoxPreference codec = new CheckBoxPreference(getActivity());
codec.setTitle("OpenH264"); codec.setTitle("OpenH264");
codec.setSummary(mCodecDownloader.getLicenseMessage()); codec.setSummary(mCodecDownloader.getLicenseMessage());
@ -925,7 +894,7 @@ public class SettingsFragment extends PreferencesListFragment {
@Override @Override
public boolean onPreferenceChange(Preference preference, Object newValue) { public boolean onPreferenceChange(Preference preference, Object newValue) {
boolean enable = (Boolean) newValue; boolean enable = (Boolean) newValue;
if (mCodecDownloader.isOpenH264DownloadEnabled()) { if (OpenH264DownloadHelper.isOpenH264DownloadEnabled()) {
if (enable if (enable
&& Version.getCpuAbis().contains("armeabi-v7a") && Version.getCpuAbis().contains("armeabi-v7a")
&& !Version.getCpuAbis().contains("x86") && !Version.getCpuAbis().contains("x86")
@ -1401,19 +1370,23 @@ public class SettingsFragment extends PreferencesListFragment {
@Override @Override
public boolean onPreferenceClick(Preference preference) { public boolean onPreferenceClick(Preference preference) {
synchronized (SettingsFragment.this) { synchronized (SettingsFragment.this) {
Context context = SettingsFragment.this.getActivity(); if (Build.VERSION.SDK_INT >= Version.API26_O_80) {
Intent i = new Intent(); Context context = SettingsFragment.this.getActivity();
i.setAction(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS); Intent i = new Intent();
i.putExtra( i.setAction(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
Settings.EXTRA_APP_PACKAGE, context.getPackageName()); i.putExtra(
i.putExtra( Settings.EXTRA_APP_PACKAGE,
Settings.EXTRA_CHANNEL_ID, context.getPackageName());
context.getString(R.string.notification_channel_id)); i.putExtra(
i.addCategory(Intent.CATEGORY_DEFAULT); Settings.EXTRA_CHANNEL_ID,
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.getString(
i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); R.string.notification_channel_id));
i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); i.addCategory(Intent.CATEGORY_DEFAULT);
context.startActivity(i); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
context.startActivity(i);
}
return true; return true;
} }
} }
@ -1631,6 +1604,7 @@ public class SettingsFragment extends PreferencesListFragment {
try { try {
port = Integer.parseInt(newValue.toString()); port = Integer.parseInt(newValue.toString());
} catch (NumberFormatException nfe) { } catch (NumberFormatException nfe) {
Log.e(nfe);
} }
mPrefs.setSipPort(port); mPrefs.setSipPort(port);

View file

@ -22,11 +22,10 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import android.accounts.AbstractAccountAuthenticator; import android.accounts.AbstractAccountAuthenticator;
import android.accounts.Account; import android.accounts.Account;
import android.accounts.AccountAuthenticatorResponse; import android.accounts.AccountAuthenticatorResponse;
import android.accounts.NetworkErrorException;
import android.content.Context; import android.content.Context;
import android.os.Bundle; import android.os.Bundle;
public class Authenticator extends AbstractAccountAuthenticator { class Authenticator extends AbstractAccountAuthenticator {
public Authenticator(Context context) { public Authenticator(Context context) {
super(context); super(context);
@ -39,21 +38,19 @@ public class Authenticator extends AbstractAccountAuthenticator {
@Override @Override
public Bundle addAccount( public Bundle addAccount(
AccountAuthenticatorResponse r, String s, String s2, String[] strings, Bundle bundle) AccountAuthenticatorResponse r, String s, String s2, String[] strings, Bundle bundle) {
throws NetworkErrorException {
return null; return null;
} }
@Override @Override
public Bundle confirmCredentials(AccountAuthenticatorResponse r, Account account, Bundle bundle) public Bundle confirmCredentials(
throws NetworkErrorException { AccountAuthenticatorResponse r, Account account, Bundle bundle) {
return null; return null;
} }
@Override @Override
public Bundle getAuthToken( public Bundle getAuthToken(
AccountAuthenticatorResponse r, Account account, String s, Bundle bundle) AccountAuthenticatorResponse r, Account account, String s, Bundle bundle) {
throws NetworkErrorException {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@ -64,14 +61,12 @@ public class Authenticator extends AbstractAccountAuthenticator {
@Override @Override
public Bundle updateCredentials( public Bundle updateCredentials(
AccountAuthenticatorResponse r, Account account, String s, Bundle bundle) AccountAuthenticatorResponse r, Account account, String s, Bundle bundle) {
throws NetworkErrorException {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@Override @Override
public Bundle hasFeatures(AccountAuthenticatorResponse r, Account account, String[] strings) public Bundle hasFeatures(AccountAuthenticatorResponse r, Account account, String[] strings) {
throws NetworkErrorException {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
} }

View file

@ -26,7 +26,7 @@ import android.content.Context;
import android.content.SyncResult; import android.content.SyncResult;
import android.os.Bundle; import android.os.Bundle;
public class SyncAdapter extends AbstractThreadedSyncAdapter { class SyncAdapter extends AbstractThreadedSyncAdapter {
public SyncAdapter(Context context, boolean autoInitialize) { public SyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize); super(context, autoInitialize);

View file

@ -127,15 +127,12 @@ public class FileUtils {
private static boolean copyToFile(InputStream inputStream, File destFile) { private static boolean copyToFile(InputStream inputStream, File destFile) {
if (inputStream == null || destFile == null) return false; if (inputStream == null || destFile == null) return false;
try { try {
OutputStream out = new FileOutputStream(destFile); try (OutputStream out = new FileOutputStream(destFile)) {
try {
byte[] buffer = new byte[4096]; byte[] buffer = new byte[4096];
int bytesRead; int bytesRead;
while ((bytesRead = inputStream.read(buffer)) >= 0) { while ((bytesRead = inputStream.read(buffer)) >= 0) {
out.write(buffer, 0, bytesRead); out.write(buffer, 0, bytesRead);
} }
} finally {
out.close();
} }
return true; return true;
} catch (IOException e) { } catch (IOException e) {
@ -143,7 +140,7 @@ public class FileUtils {
} }
} }
public static File createFile(Context context, String fileName) throws IOException { private static File createFile(Context context, String fileName) {
if (TextUtils.isEmpty(fileName)) fileName = getStartDate(); if (TextUtils.isEmpty(fileName)) fileName = getStartDate();
if (!fileName.contains(".")) { if (!fileName.contains(".")) {
@ -162,10 +159,9 @@ public class FileUtils {
FriendList[] friendList = LinphoneManager.getLc().getFriendsLists(); FriendList[] friendList = LinphoneManager.getLc().getFriendsLists();
for (FriendList list : friendList) { for (FriendList list : friendList) {
for (Friend friend : list.getFriends()) { for (Friend friend : list.getFriends()) {
if (friend.getRefKey().toString().equals(contactId)) { if (friend.getRefKey().equals(contactId)) {
String contactVcard = friend.getVcard().asVcard4String(); String contactVcard = friend.getVcard().asVcard4String();
Uri path = createCvsFromString(contactVcard); return createCvsFromString(contactVcard);
return path;
} }
} }
} }

View file

@ -34,7 +34,6 @@ import android.util.TypedValue;
import android.widget.ImageView; import android.widget.ImageView;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
import org.linphone.R; import org.linphone.R;
import org.linphone.contacts.ContactsManager; import org.linphone.contacts.ContactsManager;
@ -49,14 +48,13 @@ public class ImageUtils {
url = new URL(uri.toString()); url = new URL(uri.toString());
is = url.openStream(); is = url.openStream();
return BitmapFactory.decodeStream(is); return BitmapFactory.decodeStream(is);
} catch (MalformedURLException e) {
Log.e(e, e.getMessage());
} catch (IOException e) { } catch (IOException e) {
Log.e(e, e.getMessage()); Log.e(e, e.getMessage());
} finally { } finally {
try { try {
is.close(); is.close();
} catch (IOException x) { } catch (IOException x) {
Log.e(x);
} }
} }
return null; return null;
@ -83,6 +81,7 @@ public class ImageUtils {
MediaStore.Images.Media.getBitmap( MediaStore.Images.Media.getBitmap(
c.getContentResolver(), thumbnailUri); c.getContentResolver(), thumbnailUri);
} catch (IOException ie) { } catch (IOException ie) {
Log.e(ie);
} }
} }
} }
@ -118,7 +117,7 @@ public class ImageUtils {
return bm; return bm;
} }
public static Bitmap getRoundBitmap(Bitmap bitmap) { private static Bitmap getRoundBitmap(Bitmap bitmap) {
Bitmap output = Bitmap output =
Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output); Canvas canvas = new Canvas(output);

View file

@ -37,7 +37,6 @@ public class LinphoneGenericActivity extends Activity {
if (!LinphoneService.isReady() || !LinphoneManager.isInstanciated()) { if (!LinphoneService.isReady() || !LinphoneManager.isInstanciated()) {
finish(); finish();
startActivity(getIntent().setClass(this, LinphoneLauncherActivity.class)); startActivity(getIntent().setClass(this, LinphoneLauncherActivity.class));
return;
} }
} }
} }

View file

@ -21,15 +21,12 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import android.app.Activity; import android.app.Activity;
import android.app.AlertDialog; import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.net.ConnectivityManager; import android.net.ConnectivityManager;
import android.net.NetworkInfo; import android.net.NetworkInfo;
import android.os.Build;
import android.os.Handler; import android.os.Handler;
import android.os.Looper; import android.os.Looper;
import android.provider.Settings;
import android.telephony.TelephonyManager; import android.telephony.TelephonyManager;
import android.text.Html; import android.text.Html;
import android.text.Spanned; import android.text.Spanned;
@ -65,26 +62,10 @@ import org.linphone.settings.LinphonePreferences;
/** Helpers. */ /** Helpers. */
public final class LinphoneUtils { public final class LinphoneUtils {
private static Context sContext = null; private static Context sContext = null;
private static Handler sHandler = new Handler(Looper.getMainLooper()); private static final Handler sHandler = new Handler(Looper.getMainLooper());
private LinphoneUtils() {} private LinphoneUtils() {}
public static String getDeviceName(Context context) {
String name =
Settings.Global.getString(
context.getContentResolver(), Settings.Global.DEVICE_NAME);
if (name == null) {
name = BluetoothAdapter.getDefaultAdapter().getName();
}
if (name == null) {
name = Settings.Secure.getString(context.getContentResolver(), "bluetooth_name");
}
if (name == null) {
name = Build.MANUFACTURER + " " + Build.MODEL;
}
return name;
}
public static void initLoggingService(boolean isDebugEnabled, String appName) { public static void initLoggingService(boolean isDebugEnabled, String appName) {
if (!LinphonePreferences.instance().useJavaLogger()) { if (!LinphonePreferences.instance().useJavaLogger()) {
Factory.instance().enableLogCollection(LogCollectionState.Enabled); Factory.instance().enableLogCollection(LogCollectionState.Enabled);
@ -135,7 +116,7 @@ public final class LinphoneUtils {
// private static final String strictSipAddressRegExp = // private static final String strictSipAddressRegExp =
// "^sip:(\\+)?[a-z0-9]+([_\\.-][a-z0-9]+)*@([a-z0-9]+([\\.-][a-z0-9]+)*)+\\.[a-z]{2,}$"; // "^sip:(\\+)?[a-z0-9]+([_\\.-][a-z0-9]+)*@([a-z0-9]+([\\.-][a-z0-9]+)*)+\\.[a-z]{2,}$";
public static boolean isSipAddress(String numberOrAddress) { private static boolean isSipAddress(String numberOrAddress) {
Factory.instance().createAddress(numberOrAddress); Factory.instance().createAddress(numberOrAddress);
return true; return true;
} }
@ -211,11 +192,11 @@ public final class LinphoneUtils {
} }
} }
static boolean isToday(Calendar cal) { private static boolean isToday(Calendar cal) {
return isSameDay(cal, Calendar.getInstance()); return isSameDay(cal, Calendar.getInstance());
} }
static boolean isSameDay(Calendar cal1, Calendar cal2) { private static boolean isSameDay(Calendar cal1, Calendar cal2) {
if (cal1 == null || cal2 == null) { if (cal1 == null || cal2 == null) {
return false; return false;
} }
@ -237,7 +218,7 @@ public final class LinphoneUtils {
return true; return true;
} }
public static final List<Call> getCallsInState(Core lc, Collection<State> states) { public static List<Call> getCallsInState(Core lc, Collection<State> states) {
List<Call> foundCalls = new ArrayList<>(); List<Call> foundCalls = new ArrayList<>();
for (Call call : lc.getCalls()) { for (Call call : lc.getCalls()) {
if (states.contains(call.getState())) { if (states.contains(call.getState())) {
@ -247,7 +228,7 @@ public final class LinphoneUtils {
return foundCalls; return foundCalls;
} }
public static boolean isCallRunning(Call call) { private static boolean isCallRunning(Call call) {
if (call == null) { if (call == null) {
return false; return false;
} }

View file

@ -26,7 +26,7 @@ import java.io.File;
import org.linphone.mediastream.Log; import org.linphone.mediastream.Log;
public class MediaScanner implements MediaScannerConnection.MediaScannerConnectionClient { public class MediaScanner implements MediaScannerConnection.MediaScannerConnectionClient {
private MediaScannerConnection mMediaConnection; private final MediaScannerConnection mMediaConnection;
private boolean mIsConnected; private boolean mIsConnected;
private File mFileWaitingForScan; private File mFileWaitingForScan;
private MediaScannerListener mListener; private MediaScannerListener mListener;
@ -52,7 +52,7 @@ public class MediaScanner implements MediaScannerConnection.MediaScannerConnecti
scanFile(file, FileUtils.getMimeFromFile(file.getAbsolutePath()), listener); scanFile(file, FileUtils.getMimeFromFile(file.getAbsolutePath()), listener);
} }
public void scanFile(File file, String mime, MediaScannerListener listener) { private void scanFile(File file, String mime, MediaScannerListener listener) {
mListener = listener; mListener = listener;
if (!mIsConnected) { if (!mIsConnected) {

View file

@ -26,11 +26,11 @@ import java.util.List;
public abstract class SelectableAdapter<VH extends RecyclerView.ViewHolder> public abstract class SelectableAdapter<VH extends RecyclerView.ViewHolder>
extends RecyclerView.Adapter<VH> { extends RecyclerView.Adapter<VH> {
private SparseBooleanArray mSelectedItems; private final SparseBooleanArray mSelectedItems;
private boolean mIsEditionEnabled = false; private boolean mIsEditionEnabled = false;
private SelectableHelper mListHelper; private final SelectableHelper mListHelper;
public SelectableAdapter(SelectableHelper helper) { protected SelectableAdapter(SelectableHelper helper) {
mSelectedItems = new SparseBooleanArray(); mSelectedItems = new SparseBooleanArray();
mListHelper = helper; mListHelper = helper;
} }
@ -52,7 +52,7 @@ public abstract class SelectableAdapter<VH extends RecyclerView.ViewHolder>
* @param position Position of the item to check * @param position Position of the item to check
* @return true if the item is selected, false otherwise * @return true if the item is selected, false otherwise
*/ */
public boolean isSelected(int position) { protected boolean isSelected(int position) {
return getSelectedItems().contains(position); return getSelectedItems().contains(position);
} }

View file

@ -30,15 +30,16 @@ import org.linphone.LinphoneActivity;
import org.linphone.R; import org.linphone.R;
public class SelectableHelper { public class SelectableHelper {
private ImageView mEditButton, private final ImageView mEditButton;
mSelectAllButton, private final ImageView mSelectAllButton;
mDeselectAllButton, private final ImageView mDeselectAllButton;
mDeleteSelectionButton, private final ImageView mDeleteSelectionButton;
mCancelButton; private final ImageView mCancelButton;
private LinearLayout mEditTopBar, mTopBar; private final LinearLayout mEditTopBar;
private final LinearLayout mTopBar;
private SelectableAdapter<RecyclerView.ViewHolder> mAdapter; private SelectableAdapter<RecyclerView.ViewHolder> mAdapter;
private DeleteListener mDeleteListener; private final DeleteListener mDeleteListener;
private Context mContext; private final Context mContext;
private int mDialogDeleteMessageResourceId; private int mDialogDeleteMessageResourceId;
public SelectableHelper(View view, DeleteListener listener) { public SelectableHelper(View view, DeleteListener listener) {
@ -159,7 +160,7 @@ public class SelectableHelper {
} }
} }
public void quitEditionMode() { private void quitEditionMode() {
mAdapter.enableEdition(false); mAdapter.enableEdition(false);
mTopBar.setVisibility(View.VISIBLE); mTopBar.setVisibility(View.VISIBLE);
mEditTopBar.setVisibility(View.GONE); mEditTopBar.setVisibility(View.GONE);

View file

@ -33,7 +33,7 @@ import org.linphone.fragments.DialerFragment;
public class AddressText extends EditText implements AddressType { public class AddressText extends EditText implements AddressType {
private String mDisplayedName; private String mDisplayedName;
private Paint mTestPaint; private final Paint mTestPaint;
private DialerFragment mDialer; private DialerFragment mDialer;
public AddressText(Context context, AttributeSet attrs) { public AddressText(Context context, AttributeSet attrs) {

View file

@ -31,7 +31,6 @@ import android.provider.MediaStore;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.RelativeLayout; import android.widget.RelativeLayout;
import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
import org.linphone.mediastream.Log; import org.linphone.mediastream.Log;
@ -42,8 +41,8 @@ public class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> {
public String path; public String path;
private final WeakReference<ImageView> mImageViewReference; private final WeakReference<ImageView> mImageViewReference;
private Context mContext; private final Context mContext;
private Bitmap mDefaultBitmap; private final Bitmap mDefaultBitmap;
public BitmapWorkerTask(Context context, ImageView imageView, Bitmap defaultBitmap) { public BitmapWorkerTask(Context context, ImageView imageView, Bitmap defaultBitmap) {
mContext = context; mContext = context;
@ -85,8 +84,6 @@ public class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> {
bm = bm =
MediaStore.Images.Media.getBitmap( MediaStore.Images.Media.getBitmap(
mContext.getContentResolver(), Uri.parse(path)); mContext.getContentResolver(), Uri.parse(path));
} catch (FileNotFoundException e) {
Log.e(e);
} catch (IOException e) { } catch (IOException e) {
Log.e(e); Log.e(e);
} }

View file

@ -33,8 +33,10 @@ import org.linphone.mediastream.Log;
import org.linphone.utils.ImageUtils; import org.linphone.utils.ImageUtils;
class ContactAvatarHolder { class ContactAvatarHolder {
public ImageView contactPicture, avatarMask, securityLevel; public final ImageView contactPicture;
public TextView generatedAvatar; public final ImageView avatarMask;
public final ImageView securityLevel;
public final TextView generatedAvatar;
public ContactAvatarHolder(View v) { public ContactAvatarHolder(View v) {
contactPicture = v.findViewById(R.id.contact_picture); contactPicture = v.findViewById(R.id.contact_picture);
@ -54,11 +56,11 @@ public class ContactAvatar {
private static String generateAvatar(String displayName) { private static String generateAvatar(String displayName) {
String[] names = displayName.split(" "); String[] names = displayName.split(" ");
String generatedAvatarText = ""; StringBuilder generatedAvatarText = new StringBuilder();
for (String name : names) { for (String name : names) {
generatedAvatarText += name.charAt(0); generatedAvatarText.append(name.charAt(0));
} }
return generatedAvatarText.toUpperCase(); return generatedAvatarText.toString().toUpperCase();
} }
private static void setSecurityLevel(ChatRoomSecurityLevel level, View v) { private static void setSecurityLevel(ChatRoomSecurityLevel level, View v) {

View file

@ -29,8 +29,8 @@ import org.linphone.R;
import org.linphone.contacts.ContactAddress; import org.linphone.contacts.ContactAddress;
public class ContactSelectView extends View { public class ContactSelectView extends View {
private TextView mContactName; private final TextView mContactName;
private ImageView mDeleteContact; private final ImageView mDeleteContact;
public ContactSelectView(Context context) { public ContactSelectView(Context context) {
super(context); super(context);

Some files were not shown because too many files have changed in this diff Show more