diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 82d28839b..93c982f89 100755 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -1,112 +1,114 @@ - - - - - - - - + + + + + + + + android:required="false" /> - - - + + + + android:required="false" /> - - + + - + - + - - + + - - - - - - + + + + + + - + - - + + + android:xlargeScreens="true" /> + android:largeHeap="true" + android:roundIcon="@mipmap/ic_launcher_round"> - + - + - - + + - + - - + + - + - + - - + + - - + + - - + + + - - - - - - + + + + + + + @@ -118,7 +120,7 @@ android:launchMode="singleTask" android:theme="@style/NoTitle"> - + - + - + - + - + + - - + + + android:label="@string/service_name" /> - + + android:resource="@xml/syncadapter" /> + android:resource="@xml/contacts" /> - + + android:resource="@xml/authenticator" /> - + - + android:enabled="false"> - + - + - + - + - + - + @@ -266,18 +268,20 @@ android:name=".receivers.AccountEnableReceiver" android:permission="android.permission.USE_SIP"> - + - + - + - + @@ -288,10 +292,10 @@ android:grantUriPermissions="true"> + android:resource="@xml/provider_paths" /> - + sideMenuItems; private boolean callTransfer = false; private boolean isOnBackground = false; + private int mAlwaysChangingPhoneAngle = -1; - public String mAddressWaitingToBeCalled; - - static public final boolean isInstanciated() { + public static final boolean isInstanciated() { return instance != null; } public static final LinphoneActivity instance() { - if (instance != null) - return instance; + if (instance != null) return instance; throw new RuntimeException("LinphoneActivity not instantiated yet"); } @Override protected void onCreate(Bundle savedInstanceState) { - //This must be done before calling super.onCreate(). + // This must be done before calling super.onCreate(). super.onCreate(savedInstanceState); if (getResources().getBoolean(R.bool.orientation_portrait_only)) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } - boolean useFirstLoginActivity = getResources().getBoolean(R.bool.display_account_assistant_at_first_start); + boolean useFirstLoginActivity = + getResources().getBoolean(R.bool.display_account_assistant_at_first_start); if (LinphonePreferences.instance().isProvisioningLoginViewEnabled()) { Intent wizard = new Intent(); wizard.setClass(this, RemoteProvisioningLoginActivity.class); @@ -188,8 +191,10 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick startActivity(wizard); finish(); return; - } else if (savedInstanceState == null && (useFirstLoginActivity && LinphoneManager.getLcIfManagerNotDestroyedOrNull() != null - && LinphonePreferences.instance().isFirstLaunch())) { + } else if (savedInstanceState == null + && (useFirstLoginActivity + && LinphoneManager.getLcIfManagerNotDestroyedOrNull() != null + && LinphonePreferences.instance().isFirstLaunch())) { if (LinphonePreferences.instance().getAccountCount() > 0) { LinphonePreferences.instance().firstLaunchSuccessful(); } else { @@ -200,7 +205,10 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick } if (getResources().getBoolean(R.bool.use_linphone_tag)) { - if (getPackageManager().checkPermission(Manifest.permission.WRITE_SYNC_SETTINGS, getPackageName()) != PackageManager.PERMISSION_GRANTED) { + if (getPackageManager() + .checkPermission( + Manifest.permission.WRITE_SYNC_SETTINGS, getPackageName()) + != PackageManager.PERMISSION_GRANTED) { checkSyncPermission(); } else { if (LinphoneService.isReady()) @@ -223,56 +231,77 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick if (savedInstanceState == null) { changeCurrentFragment(FragmentsAvailable.DIALER, getIntent().getExtras()); } else { - currentFragment = (FragmentsAvailable) savedInstanceState.getSerializable("currentFragment"); + currentFragment = + (FragmentsAvailable) savedInstanceState.getSerializable("currentFragment"); } - mListener = new CoreListenerStub() { - @Override - public void onMessageReceived(Core lc, ChatRoom cr, ChatMessage message) { - displayMissedChats(LinphoneManager.getInstance().getUnreadMessageCount()); - } - - @Override - public void onRegistrationStateChanged(Core lc, ProxyConfig proxy, RegistrationState state, String smessage) { - AuthInfo authInfo = lc.findAuthInfo(proxy.getRealm(), proxy.getIdentityAddress().getUsername(), proxy.getDomain()); - - refreshAccounts(); - - if (getResources().getBoolean(R.bool.use_phone_number_validation) - && authInfo != null && authInfo.getDomain().equals(getString(R.string.default_domain))) { - if (state.equals(RegistrationState.Ok)) { - LinphoneManager.getInstance().isAccountWithAlias(); + mListener = + new CoreListenerStub() { + @Override + public void onMessageReceived(Core lc, ChatRoom cr, ChatMessage message) { + displayMissedChats(LinphoneManager.getInstance().getUnreadMessageCount()); } - } - if (state.equals(RegistrationState.Failed) && newProxyConfig) { - newProxyConfig = false; - if (proxy.getError() == Reason.Forbidden) { - //displayCustomToast(getString(R.string.error_bad_credentials), Toast.LENGTH_LONG); - } - if (proxy.getError() == Reason.Unauthorized) { - displayCustomToast(getString(R.string.error_unauthorized), Toast.LENGTH_LONG); - } - if (proxy.getError() == Reason.IOError) { - displayCustomToast(getString(R.string.error_io_error), Toast.LENGTH_LONG); - } - } - } + @Override + public void onRegistrationStateChanged( + Core lc, ProxyConfig proxy, RegistrationState state, String smessage) { + AuthInfo authInfo = + lc.findAuthInfo( + proxy.getRealm(), + proxy.getIdentityAddress().getUsername(), + proxy.getDomain()); - @Override - public void onCallStateChanged(Core lc, Call call, Call.State state, String message) { - if (state == State.IncomingReceived) { - startActivity(new Intent(LinphoneActivity.instance(), CallIncomingActivity.class)); - } else if (state == State.OutgoingInit || state == State.OutgoingProgress) { - startActivity(new Intent(LinphoneActivity.instance(), CallOutgoingActivity.class)); - } else if (state == State.End || state == State.Error || state == State.Released) { - resetClassicMenuLayoutAndGoBackToCallIfStillRunning(); - } + refreshAccounts(); - int missedCalls = LinphoneManager.getLc().getMissedCallsCount(); - displayMissedCalls(missedCalls); - } - }; + if (getResources().getBoolean(R.bool.use_phone_number_validation) + && authInfo != null + && authInfo.getDomain() + .equals(getString(R.string.default_domain))) { + if (state.equals(RegistrationState.Ok)) { + LinphoneManager.getInstance().isAccountWithAlias(); + } + } + + if (state.equals(RegistrationState.Failed) && newProxyConfig) { + newProxyConfig = false; + if (proxy.getError() == Reason.Forbidden) { + // displayCustomToast(getString(R.string.error_bad_credentials), + // Toast.LENGTH_LONG); + } + if (proxy.getError() == Reason.Unauthorized) { + displayCustomToast( + getString(R.string.error_unauthorized), Toast.LENGTH_LONG); + } + if (proxy.getError() == Reason.IOError) { + displayCustomToast( + getString(R.string.error_io_error), Toast.LENGTH_LONG); + } + } + } + + @Override + public void onCallStateChanged( + Core lc, Call call, Call.State state, String message) { + if (state == State.IncomingReceived) { + startActivity( + new Intent( + LinphoneActivity.instance(), + CallIncomingActivity.class)); + } else if (state == State.OutgoingInit || state == State.OutgoingProgress) { + startActivity( + new Intent( + LinphoneActivity.instance(), + CallOutgoingActivity.class)); + } else if (state == State.End + || state == State.Error + || state == State.Released) { + resetClassicMenuLayoutAndGoBackToCallIfStillRunning(); + } + + int missedCalls = LinphoneManager.getLc().getMissedCallsCount(); + displayMissedCalls(missedCalls); + } + }; Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull(); if (lc != null) { @@ -362,7 +391,8 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick } private void changeCurrentFragment(FragmentsAvailable newFragmentType, Bundle extras) { - if (newFragmentType == currentFragment && newFragmentType != FragmentsAvailable.CHAT + if (newFragmentType == currentFragment + && newFragmentType != FragmentsAvailable.CHAT && newFragmentType != FragmentsAvailable.GROUP_CHAT) { return; } @@ -486,7 +516,8 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick currentFragment = newFragmentType; } - private void changeFragmentForTablets(Fragment newFragment, FragmentsAvailable newFragmentType) { + private void changeFragmentForTablets( + Fragment newFragment, FragmentsAvailable newFragmentType) { if (getResources().getBoolean(R.bool.show_statusbar_only_on_dialer)) { if (newFragmentType == FragmentsAvailable.DIALER) { showStatusBar(); @@ -506,7 +537,8 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick transaction.commitAllowingStateLoss(); getFragmentManager().executePendingTransactions(); } else { - if (newFragmentType.shouldAddItselfToTheRightOf(currentFragment) || newFragmentType.shouldAddItselfToTheRightOf(leftFragment)) { + if (newFragmentType.shouldAddItselfToTheRightOf(currentFragment) + || newFragmentType.shouldAddItselfToTheRightOf(leftFragment)) { ll.setVisibility(View.VISIBLE); if (newFragmentType == FragmentsAvailable.CONTACT_EDITOR) { @@ -515,7 +547,8 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick transaction.replace(R.id.fragmentContainer2, newFragment); leftFragment = currentFragment; - if (newFragmentType == FragmentsAvailable.GROUP_CHAT && leftFragment != FragmentsAvailable.CHAT_LIST) { + if (newFragmentType == FragmentsAvailable.GROUP_CHAT + && leftFragment != FragmentsAvailable.CHAT_LIST) { leftFragment = FragmentsAvailable.CHAT_LIST; transaction.replace(R.id.fragmentContainer, new ChatRoomsFragment()); } @@ -550,7 +583,8 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick || newFragmentType == FragmentsAvailable.CHAT_LIST || newFragmentType == FragmentsAvailable.HISTORY_LIST) { try { - getFragmentManager().popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); + getFragmentManager() + .popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); } catch (java.lang.IllegalStateException e) { } @@ -568,8 +602,10 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick c = ContactsManager.getInstance().findContactFromAddress(lAddress); } - String displayName = c != null ? c.getFullName() : LinphoneUtils.getAddressDisplayName(sipUri); - String pictureUri = c != null && c.getPhotoUri() != null ? c.getPhotoUri().toString() : null; + String displayName = + c != null ? c.getFullName() : LinphoneUtils.getAddressDisplayName(sipUri); + String pictureUri = + c != null && c.getPhotoUri() != null ? c.getPhotoUri().toString() : null; String status; if (log.getDir() == Call.Dir.Outgoing) { @@ -586,9 +622,12 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick String callDate = String.valueOf(log.getStartDate()); Fragment fragment2 = getFragmentManager().findFragmentById(R.id.fragmentContainer2); - if (fragment2 != null && fragment2.isVisible() && currentFragment == FragmentsAvailable.HISTORY_DETAIL) { + if (fragment2 != null + && fragment2.isVisible() + && currentFragment == FragmentsAvailable.HISTORY_DETAIL) { HistoryDetailFragment historyDetailFragment = (HistoryDetailFragment) fragment2; - historyDetailFragment.changeDisplayedHistory(sipUri, displayName, pictureUri, status, callTime, callDate); + historyDetailFragment.changeDisplayedHistory( + sipUri, displayName, pictureUri, status, callTime, callDate); } else { Bundle extras = new Bundle(); extras.putString("SipUri", sipUri); @@ -618,7 +657,9 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick public void displayContact(LinphoneContact contact, boolean chatOnly) { Fragment fragment2 = getFragmentManager().findFragmentById(R.id.fragmentContainer2); - if (fragment2 != null && fragment2.isVisible() && currentFragment == FragmentsAvailable.CONTACT_DETAIL) { + if (fragment2 != null + && fragment2.isVisible() + && currentFragment == FragmentsAvailable.CONTACT_DETAIL) { ContactDetailsFragment contactFragment = (ContactDetailsFragment) fragment2; contactFragment.changeDisplayedContact(contact); } else { @@ -662,19 +703,23 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick startActivity(new Intent(LinphoneActivity.this, AssistantActivity.class)); } - public void displayInapp() { startActivity(new Intent(LinphoneActivity.this, InAppPurchaseActivity.class)); } - private void displayChat(String sipUri, String message, String fileUri, String pictureUri, String thumbnailUri, String displayName, Address lAddress) { + private void displayChat( + String sipUri, + String message, + String fileUri, + String pictureUri, + String thumbnailUri, + String displayName, + Address lAddress) { Bundle extras = new Bundle(); extras.putString("SipUri", sipUri); - if (message != null) - extras.putString("messageDraft", message); - if (fileUri != null) - extras.putString("fileSharedUri", fileUri); + if (message != null) extras.putString("messageDraft", message); + if (fileUri != null) extras.putString("fileSharedUri", fileUri); if (sipUri != null && lAddress.getDisplayName() != null) { extras.putString("DisplayName", displayName); extras.putString("PictureUri", pictureUri); @@ -688,8 +733,14 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick } } - public void goToChatCreator(String address, ArrayList selectedContacts, String subject, boolean isGoBack, Bundle shareInfos, - boolean createGroupChat, boolean isChatRoomEncrypted) { + public void goToChatCreator( + String address, + ArrayList selectedContacts, + String subject, + boolean isGoBack, + Bundle shareInfos, + boolean createGroupChat, + boolean isChatRoomEncrypted) { if (currentFragment == FragmentsAvailable.INFO_GROUP_CHAT && isGoBack) { getFragmentManager().popBackStackImmediate(); getFragmentManager().popBackStackImmediate(); @@ -724,7 +775,10 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick if (isTablet()) { Fragment fragment2 = getFragmentManager().findFragmentById(R.id.fragmentContainer2); - if (fragment2 != null && fragment2.isVisible() && currentFragment == FragmentsAvailable.GROUP_CHAT && !emptyFragment) { + if (fragment2 != null + && fragment2.isVisible() + && currentFragment == FragmentsAvailable.GROUP_CHAT + && !emptyFragment) { ChatMessagesFragment chatFragment = (ChatMessagesFragment) fragment2; chatFragment.changeDisplayedChat(sipUri); } else { @@ -738,8 +792,14 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick displayMissedChats(LinphoneManager.getInstance().getUnreadMessageCount()); } - public void goToChatGroupInfos(String address, ArrayList contacts, String subject, - boolean isEditionEnabled, boolean isGoBack, Bundle shareInfos, boolean enableEncryption) { + public void goToChatGroupInfos( + String address, + ArrayList contacts, + String subject, + boolean isEditionEnabled, + boolean isGoBack, + Bundle shareInfos, + boolean enableEncryption) { if (currentFragment == FragmentsAvailable.CREATE_CHAT && isGoBack) { getFragmentManager().popBackStackImmediate(); getFragmentManager().popBackStackImmediate(); @@ -791,7 +851,8 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick if (sipUri != null) { lAddress = LinphoneManager.getLc().interpretUrl(sipUri); if (lAddress == null) return; - LinphoneContact contact = ContactsManager.getInstance().findContactFromAddress(lAddress); + LinphoneContact contact = + ContactsManager.getInstance().findContactFromAddress(lAddress); displayName = contact != null ? contact.getFullName() : null; if (contact != null && contact.getPhotoUri() != null) { @@ -800,19 +861,25 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick } } - if (currentFragment == FragmentsAvailable.CHAT_LIST || currentFragment == FragmentsAvailable.GROUP_CHAT) { + if (currentFragment == FragmentsAvailable.CHAT_LIST + || currentFragment == FragmentsAvailable.GROUP_CHAT) { Fragment fragment2 = getFragmentManager().findFragmentById(R.id.fragmentContainer2); - if (fragment2 != null && fragment2.isVisible() && currentFragment == FragmentsAvailable.GROUP_CHAT && !emptyFragment) { + if (fragment2 != null + && fragment2.isVisible() + && currentFragment == FragmentsAvailable.GROUP_CHAT + && !emptyFragment) { ChatMessagesFragment chatFragment = (ChatMessagesFragment) fragment2; chatFragment.changeDisplayedChat(sipUri); } else { - displayChat(sipUri, message, fileUri, pictureUri, thumbnailUri, displayName, lAddress); + displayChat( + sipUri, message, fileUri, pictureUri, thumbnailUri, displayName, lAddress); } } else { if (isTablet()) { changeCurrentFragment(FragmentsAvailable.CHAT_LIST, null); } else { - displayChat(sipUri, message, fileUri, pictureUri, thumbnailUri, displayName, lAddress); + displayChat( + sipUri, message, fileUri, pictureUri, thumbnailUri, displayName, lAddress); } } @@ -878,7 +945,8 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick public void selectMenu(FragmentsAvailable menuToSelect) { currentFragment = menuToSelect; resetSelection(); - boolean hideBottomBar = getResources().getBoolean(R.bool.hide_bottom_bar_on_second_level_views); + boolean hideBottomBar = + getResources().getBoolean(R.bool.hide_bottom_bar_on_second_level_views); switch (menuToSelect) { case HISTORY_LIST: @@ -929,7 +997,10 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick public void updateDialerFragment() { // Hack to maintain soft input flags - getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); + getWindow() + .setSoftInputMode( + WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN + | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); } public void goToDialerFragment() { @@ -980,8 +1051,10 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick missedChats.clearAnimation(); missedChats.setVisibility(View.GONE); } - if (currentFragment == FragmentsAvailable.CHAT_LIST && fragment != null && fragment instanceof ChatRoomsFragment) { - ((ChatRoomsFragment)fragment).invalidate(); + if (currentFragment == FragmentsAvailable.CHAT_LIST + && fragment != null + && fragment instanceof ChatRoomsFragment) { + ((ChatRoomsFragment) fragment).invalidate(); } } @@ -1000,16 +1073,19 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick } public void displayChatRoomError() { - final Dialog dialog = LinphoneActivity.instance().displayDialog(getString(R.string.chat_room_creation_failed)); + final Dialog dialog = + LinphoneActivity.instance() + .displayDialog(getString(R.string.chat_room_creation_failed)); dialog.findViewById(R.id.dialog_delete_button).setVisibility(View.GONE); Button cancel = dialog.findViewById(R.id.dialog_cancel_button); cancel.setText(getString(R.string.ok)); - cancel.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - dialog.dismiss(); - } - }); + cancel.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View view) { + dialog.dismiss(); + } + }); dialog.show(); } @@ -1020,7 +1096,10 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick Drawable d = new ColorDrawable(ContextCompat.getColor(this, R.color.colorC)); d.setAlpha(200); dialog.setContentView(R.layout.dialog); - dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT); + dialog.getWindow() + .setLayout( + WindowManager.LayoutParams.MATCH_PARENT, + WindowManager.LayoutParams.MATCH_PARENT); dialog.getWindow().setBackgroundDrawable(d); TextView customText = dialog.findViewById(R.id.dialog_message); @@ -1030,11 +1109,11 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick @Override public void setAddresGoToDialerAndCall(String number, String name, Uri photo) { -// Bundle extras = new Bundle(); -// extras.putString("SipUri", number); -// extras.putString("DisplayName", name); -// extras.putString("Photo", photo == null ? null : photo.toString()); -// changeCurrentFragment(FragmentsAvailable.DIALER, extras); + // Bundle extras = new Bundle(); + // extras.putString("SipUri", number); + // extras.putString("DisplayName", name); + // extras.putString("Photo", photo == null ? null : photo.toString()); + // changeCurrentFragment(FragmentsAvailable.DIALER, extras); AddressType address = new AddressText(this, null); address.setText(number); @@ -1048,9 +1127,7 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick startActivityForResult(intent, CALL_ACTIVITY); } - /** - * Register a sensor to track phoneOrientation changes - */ + /** Register a sensor to track phoneOrientation changes */ private synchronized void startOrientationSensor() { if (mOrientationHelper == null) { mOrientationHelper = new LocalOrientationEventListener(this); @@ -1058,45 +1135,6 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick mOrientationHelper.enable(); } - private int mAlwaysChangingPhoneAngle = -1; - - private class LocalOrientationEventListener extends OrientationEventListener { - public LocalOrientationEventListener(Context context) { - super(context); - } - - @Override - public void onOrientationChanged(final int o) { - if (o == OrientationEventListener.ORIENTATION_UNKNOWN) { - return; - } - - int degrees = 270; - if (o < 45 || o > 315) - degrees = 0; - else if (o < 135) - degrees = 90; - else if (o < 225) - degrees = 180; - - if (mAlwaysChangingPhoneAngle == degrees) { - return; - } - mAlwaysChangingPhoneAngle = degrees; - - Log.d("Phone orientation changed to ", degrees); - int rotation = (360 - degrees) % 360; - Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull(); - if (lc != null) { - lc.setDeviceRotation(rotation); - Call currentCall = lc.getCurrentCall(); - if (currentCall != null && currentCall.cameraEnabled() && currentCall.getCurrentParams().videoEnabled()) { - lc.updateCall(currentCall, null); - } - } - } - } - public Boolean isCallTransfer() { return callTransfer; } @@ -1177,7 +1215,8 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick if (data.getExtras().getBoolean("Exit", false)) { quit(); } else { - pendingFragmentTransaction = (FragmentsAvailable) data.getExtras().getSerializable("FragmentToDisplay"); + pendingFragmentTransaction = + (FragmentsAvailable) data.getExtras().getSerializable("FragmentToDisplay"); } } else if (resultCode == Activity.RESULT_FIRST_USER && requestCode == CALL_ACTIVITY) { getIntent().putExtra("PreviousActivity", CALL_ACTIVITY); @@ -1209,10 +1248,15 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick } public boolean checkAndRequestOverlayPermission() { - Log.i("[Permission] Draw overlays permission is " + (Compatibility.canDrawOverlays(this) ? "granted" : "denied")); + Log.i( + "[Permission] Draw overlays permission is " + + (Compatibility.canDrawOverlays(this) ? "granted" : "denied")); if (!Compatibility.canDrawOverlays(this)) { Log.i("[Permission] Asking for overlay"); - Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())); + Intent intent = + new Intent( + Settings.ACTION_MANAGE_OVERLAY_PERMISSION, + Uri.parse("package:" + getPackageName())); startActivityForResult(intent, PERMISSIONS_REQUEST_OVERLAY); return false; } @@ -1232,27 +1276,42 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick } public void checkAndRequestRecordAudioPermissionForEchoCanceller() { - checkAndRequestPermission(Manifest.permission.RECORD_AUDIO, PERMISSIONS_RECORD_AUDIO_ECHO_CANCELLER); + checkAndRequestPermission( + Manifest.permission.RECORD_AUDIO, PERMISSIONS_RECORD_AUDIO_ECHO_CANCELLER); } public void checkAndRequestRecordAudioPermissionsForEchoTester() { - checkAndRequestPermission(Manifest.permission.RECORD_AUDIO, PERMISSIONS_RECORD_AUDIO_ECHO_TESTER); + checkAndRequestPermission( + Manifest.permission.RECORD_AUDIO, PERMISSIONS_RECORD_AUDIO_ECHO_TESTER); } public void checkAndRequestReadExternalStoragePermissionForDeviceRingtone() { - checkAndRequestPermission(Manifest.permission.READ_EXTERNAL_STORAGE, PERMISSIONS_READ_EXTERNAL_STORAGE_DEVICE_RINGTONE); + checkAndRequestPermission( + Manifest.permission.READ_EXTERNAL_STORAGE, + PERMISSIONS_READ_EXTERNAL_STORAGE_DEVICE_RINGTONE); } public void checkAndRequestPermissionsToSendImage() { ArrayList permissionsList = new ArrayList<>(); - int readExternalStorage = getPackageManager().checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE, getPackageName()); - Log.i("[Permission] Read external storage permission is " + (readExternalStorage == PackageManager.PERMISSION_GRANTED ? "granted" : "denied")); - int camera = getPackageManager().checkPermission(Manifest.permission.CAMERA, getPackageName()); - Log.i("[Permission] Camera permission is " + (camera == PackageManager.PERMISSION_GRANTED ? "granted" : "denied")); + int readExternalStorage = + getPackageManager() + .checkPermission( + Manifest.permission.READ_EXTERNAL_STORAGE, getPackageName()); + Log.i( + "[Permission] Read external storage permission is " + + (readExternalStorage == PackageManager.PERMISSION_GRANTED + ? "granted" + : "denied")); + int camera = + getPackageManager().checkPermission(Manifest.permission.CAMERA, getPackageName()); + Log.i( + "[Permission] Camera permission is " + + (camera == PackageManager.PERMISSION_GRANTED ? "granted" : "denied")); if (readExternalStorage != PackageManager.PERMISSION_GRANTED) { - ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE); + ActivityCompat.shouldShowRequestPermissionRationale( + this, Manifest.permission.READ_EXTERNAL_STORAGE); Log.i("[Permission] Asking for read external storage"); permissionsList.add(Manifest.permission.READ_EXTERNAL_STORAGE); } @@ -1269,30 +1328,43 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick } private void checkSyncPermission() { - checkAndRequestPermission(Manifest.permission.WRITE_SYNC_SETTINGS, PERMISSIONS_REQUEST_SYNC); + checkAndRequestPermission( + Manifest.permission.WRITE_SYNC_SETTINGS, PERMISSIONS_REQUEST_SYNC); } public void checkAndRequestPermission(String permission, int result) { int permissionGranted = getPackageManager().checkPermission(permission, getPackageName()); - Log.i("[Permission] " + permission + " is " + (permissionGranted == PackageManager.PERMISSION_GRANTED ? "granted" : "denied")); + Log.i( + "[Permission] " + + permission + + " is " + + (permissionGranted == PackageManager.PERMISSION_GRANTED + ? "granted" + : "denied")); if (permissionGranted != PackageManager.PERMISSION_GRANTED) { ActivityCompat.shouldShowRequestPermissionRationale(this, permission); Log.i("[Permission] Asking for " + permission); - ActivityCompat.requestPermissions(this, new String[]{permission}, result); + ActivityCompat.requestPermissions(this, new String[] {permission}, result); } } @Override - public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { - if (permissions.length <= 0) - return; + public void onRequestPermissionsResult( + int requestCode, String[] permissions, int[] grantResults) { + if (permissions.length <= 0) return; int readContactsI = -1; for (int i = 0; i < permissions.length; i++) { - Log.i("[Permission] " + permissions[i] + " is " + (grantResults[i] == PackageManager.PERMISSION_GRANTED ? "granted" : "denied")); - if (permissions[i].compareTo(Manifest.permission.READ_CONTACTS) == 0 || - permissions[i].compareTo(Manifest.permission.WRITE_CONTACTS) == 0) + Log.i( + "[Permission] " + + permissions[i] + + " is " + + (grantResults[i] == PackageManager.PERMISSION_GRANTED + ? "granted" + : "denied")); + if (permissions[i].compareTo(Manifest.permission.READ_CONTACTS) == 0 + || permissions[i].compareTo(Manifest.permission.WRITE_CONTACTS) == 0) readContactsI = i; } @@ -1314,8 +1386,7 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick } break; case PERMISSIONS_READ_EXTERNAL_STORAGE_DEVICE_RINGTONE: - if (permissions[0].compareTo(Manifest.permission.READ_EXTERNAL_STORAGE) != 0) - break; + if (permissions[0].compareTo(Manifest.permission.READ_EXTERNAL_STORAGE) != 0) break; boolean enableRingtone = (grantResults[0] == PackageManager.PERMISSION_GRANTED); LinphonePreferences.instance().enableDeviceRingtone(enableRingtone); LinphoneManager.getInstance().enableDeviceRingtone(enableRingtone); @@ -1325,7 +1396,8 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick ((SettingsFragment) fragment).startEchoTester(); break; } - if (readContactsI >= 0 && grantResults[readContactsI] == PackageManager.PERMISSION_GRANTED) { + if (readContactsI >= 0 + && grantResults[readContactsI] == PackageManager.PERMISSION_GRANTED) { ContactsManager.getInstance().enableContactsAccess(); if (!ContactsManager.getInstance().contactsFetchedOnce()) { ContactsManager.getInstance().initializeContactManager(this); @@ -1337,35 +1409,59 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick protected void onStart() { super.onStart(); ArrayList permissionsList = new ArrayList<>(); - permissionsList.add(Manifest.permission.SYSTEM_ALERT_WINDOW); // This one is to allow floating notifications - permissionsList.add("android.permission.FOREGROUND_SERVICE"); // Manifest.permission.FOREGROUND_SERVICE, required starting Android 9 to be able to start a foreground service + permissionsList.add( + Manifest.permission + .SYSTEM_ALERT_WINDOW); // This one is to allow floating notifications + permissionsList.add( + "android.permission.FOREGROUND_SERVICE"); // Manifest.permission.FOREGROUND_SERVICE, + // required starting Android 9 to be able + // to start a foreground service - int contacts = getPackageManager().checkPermission(Manifest.permission.READ_CONTACTS, getPackageName()); - Log.i("[Permission] Contacts permission is " + (contacts == PackageManager.PERMISSION_GRANTED ? "granted" : "denied")); + int contacts = + getPackageManager() + .checkPermission(Manifest.permission.READ_CONTACTS, getPackageName()); + Log.i( + "[Permission] Contacts permission is " + + (contacts == PackageManager.PERMISSION_GRANTED ? "granted" : "denied")); - int readPhone = getPackageManager().checkPermission(Manifest.permission.READ_PHONE_STATE, getPackageName()); - Log.i("[Permission] Read phone state permission is " + (readPhone == PackageManager.PERMISSION_GRANTED ? "granted" : "denied")); + int readPhone = + getPackageManager() + .checkPermission(Manifest.permission.READ_PHONE_STATE, getPackageName()); + Log.i( + "[Permission] Read phone state permission is " + + (readPhone == PackageManager.PERMISSION_GRANTED ? "granted" : "denied")); - int ringtone = getPackageManager().checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE, getPackageName()); - Log.i("[Permission] Read external storage for ring tone permission is " + (ringtone == PackageManager.PERMISSION_GRANTED ? "granted" : "denied")); + int ringtone = + getPackageManager() + .checkPermission( + Manifest.permission.READ_EXTERNAL_STORAGE, getPackageName()); + Log.i( + "[Permission] Read external storage for ring tone permission is " + + (ringtone == PackageManager.PERMISSION_GRANTED ? "granted" : "denied")); if (ringtone != PackageManager.PERMISSION_GRANTED) { - if (LinphonePreferences.instance().firstTimeAskingForPermission(Manifest.permission.READ_EXTERNAL_STORAGE) - || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) { + if (LinphonePreferences.instance() + .firstTimeAskingForPermission(Manifest.permission.READ_EXTERNAL_STORAGE) + || ActivityCompat.shouldShowRequestPermissionRationale( + this, Manifest.permission.READ_EXTERNAL_STORAGE)) { Log.i("[Permission] Asking for read external storage for ring tone"); permissionsList.add(Manifest.permission.READ_EXTERNAL_STORAGE); } } if (readPhone != PackageManager.PERMISSION_GRANTED) { - if (LinphonePreferences.instance().firstTimeAskingForPermission(Manifest.permission.READ_PHONE_STATE) - || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_STATE)) { + if (LinphonePreferences.instance() + .firstTimeAskingForPermission(Manifest.permission.READ_PHONE_STATE) + || ActivityCompat.shouldShowRequestPermissionRationale( + this, Manifest.permission.READ_PHONE_STATE)) { Log.i("[Permission] Asking for read phone state"); permissionsList.add(Manifest.permission.READ_PHONE_STATE); } } if (contacts != PackageManager.PERMISSION_GRANTED) { - if (LinphonePreferences.instance().firstTimeAskingForPermission(Manifest.permission.READ_CONTACTS) - || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_CONTACTS)) { + if (LinphonePreferences.instance() + .firstTimeAskingForPermission(Manifest.permission.READ_CONTACTS) + || ActivityCompat.shouldShowRequestPermissionRationale( + this, Manifest.permission.READ_CONTACTS)) { Log.i("[Permission] Asking for contacts"); permissionsList.add(Manifest.permission.READ_CONTACTS); } @@ -1379,7 +1475,8 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick if (permissionsList.size() > 0) { String[] permissions = new String[permissionsList.size()]; permissions = permissionsList.toArray(permissions); - ActivityCompat.requestPermissions(this, permissions, PERMISSIONS_READ_EXTERNAL_STORAGE_DEVICE_RINGTONE); + ActivityCompat.requestPermissions( + this, permissions, PERMISSIONS_READ_EXTERNAL_STORAGE_DEVICE_RINGTONE); } } @@ -1435,7 +1532,9 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick if (onCallStateChanged == State.IncomingReceived) { startActivity(new Intent(this, CallIncomingActivity.class)); - } else if (onCallStateChanged == State.OutgoingInit || onCallStateChanged == State.OutgoingProgress || onCallStateChanged == State.OutgoingRinging) { + } else if (onCallStateChanged == State.OutgoingInit + || onCallStateChanged == State.OutgoingProgress + || onCallStateChanged == State.OutgoingRinging) { startActivity(new Intent(this, CallOutgoingActivity.class)); } else { startIncallActivity(); @@ -1449,7 +1548,8 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick displayChat(null, intent.getStringExtra("msgShared"), null); intent.putExtra("msgShared", ""); } - if (intent.getStringExtra("fileShared") != null && intent.getStringExtra("fileShared") != "") { + if (intent.getStringExtra("fileShared") != null + && intent.getStringExtra("fileShared") != "") { displayChat(null, null, intent.getStringExtra("fileShared")); intent.putExtra("fileShared", ""); } @@ -1533,7 +1633,8 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick DialerFragment dialerFragment = DialerFragment.instance(); if (dialerFragment != null) { if (extras != null && extras.containsKey("SipUriOrNumber")) { - if (getResources().getBoolean(R.bool.automatically_start_intercepted_outgoing_gsm_call)) { + if (getResources() + .getBoolean(R.bool.automatically_start_intercepted_outgoing_gsm_call)) { dialerFragment.newOutgoingCall(extras.getString("SipUriOrNumber")); } else { dialerFragment.displayTextInAddressBar(extras.getString("SipUriOrNumber")); @@ -1574,9 +1675,12 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick case CONTACTS_LIST: case HISTORY_LIST: case CHAT_LIST: - boolean isBackgroundModeActive = LinphonePreferences.instance().isBackgroundModeEnabled(); + boolean isBackgroundModeActive = + LinphonePreferences.instance().isBackgroundModeEnabled(); if (!isBackgroundModeActive) { - stopService(new Intent(Intent.ACTION_MAIN).setClass(this, LinphoneService.class)); + stopService( + new Intent(Intent.ACTION_MAIN) + .setClass(this, LinphoneService.class)); finish(); } else if (LinphoneUtils.onKeyBackGoHome(this, keyCode, event)) { return true; @@ -1598,7 +1702,7 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick return super.onKeyDown(keyCode, event); } - //SIDE MENU + // SIDE MENU public void openOrCloseSideMenu(boolean open) { if (open) { sideMenu.openDrawer(sideMenuContent); @@ -1611,66 +1715,102 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick sideMenu = findViewById(R.id.side_menu); sideMenuItems = new ArrayList<>(); if (!getResources().getBoolean(R.bool.hide_assistant_from_side_menu)) { - sideMenuItems.add(new MenuItem(getResources().getString(R.string.menu_assistant), R.drawable.menu_assistant)); + sideMenuItems.add( + new MenuItem( + getResources().getString(R.string.menu_assistant), + R.drawable.menu_assistant)); } if (!getResources().getBoolean(R.bool.hide_settings_from_side_menu)) { - sideMenuItems.add(new MenuItem(getResources().getString(R.string.menu_settings), R.drawable.menu_options)); + sideMenuItems.add( + new MenuItem( + getResources().getString(R.string.menu_settings), + R.drawable.menu_options)); } if (getResources().getBoolean(R.bool.enable_in_app_purchase)) { - sideMenuItems.add(new MenuItem(getResources().getString(R.string.inapp), R.drawable.menu_options)); + sideMenuItems.add( + new MenuItem( + getResources().getString(R.string.inapp), R.drawable.menu_options)); } - sideMenuItems.add(new MenuItem(getResources().getString(R.string.menu_recordings), R.drawable.menu_recordings)); - sideMenuItems.add(new MenuItem(getResources().getString(R.string.menu_about), R.drawable.menu_about)); + sideMenuItems.add( + new MenuItem( + getResources().getString(R.string.menu_recordings), + R.drawable.menu_recordings)); + sideMenuItems.add( + new MenuItem(getResources().getString(R.string.menu_about), R.drawable.menu_about)); sideMenuContent = findViewById(R.id.side_menu_content); sideMenuItemList = findViewById(R.id.item_list); menu = findViewById(R.id.side_menu_button); - sideMenuItemList.setAdapter(new MenuAdapter(this, R.layout.side_menu_item_cell, sideMenuItems)); - sideMenuItemList.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView adapterView, View view, int i, long l) { - if (sideMenuItemList.getAdapter().getItem(i).toString().equals(getString(R.string.menu_settings))) { - LinphoneActivity.instance().displaySettings(); - } - if (sideMenuItemList.getAdapter().getItem(i).toString().equals(getString(R.string.menu_about))) { - LinphoneActivity.instance().displayAbout(); - } - if (sideMenuItemList.getAdapter().getItem(i).toString().equals(getString(R.string.menu_assistant))) { - LinphoneActivity.instance().displayAssistant(); - } - if (getResources().getBoolean(R.bool.enable_in_app_purchase)) { - if (sideMenuItemList.getAdapter().getItem(i).toString().equals(getString(R.string.inapp))) { - LinphoneActivity.instance().displayInapp(); + sideMenuItemList.setAdapter( + new MenuAdapter(this, R.layout.side_menu_item_cell, sideMenuItems)); + sideMenuItemList.setOnItemClickListener( + new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView adapterView, View view, int i, long l) { + if (sideMenuItemList + .getAdapter() + .getItem(i) + .toString() + .equals(getString(R.string.menu_settings))) { + LinphoneActivity.instance().displaySettings(); + } + if (sideMenuItemList + .getAdapter() + .getItem(i) + .toString() + .equals(getString(R.string.menu_about))) { + LinphoneActivity.instance().displayAbout(); + } + if (sideMenuItemList + .getAdapter() + .getItem(i) + .toString() + .equals(getString(R.string.menu_assistant))) { + LinphoneActivity.instance().displayAssistant(); + } + if (getResources().getBoolean(R.bool.enable_in_app_purchase)) { + if (sideMenuItemList + .getAdapter() + .getItem(i) + .toString() + .equals(getString(R.string.inapp))) { + LinphoneActivity.instance().displayInapp(); + } + } + if (sideMenuItemList + .getAdapter() + .getItem(i) + .toString() + .equals(getString(R.string.menu_recordings))) { + LinphoneActivity.instance().displayRecordings(); + } + openOrCloseSideMenu(false); } - } - if (sideMenuItemList.getAdapter().getItem(i).toString().equals(getString(R.string.menu_recordings))) { - LinphoneActivity.instance().displayRecordings(); - } - openOrCloseSideMenu(false); - } - }); + }); initAccounts(); - menu.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View view) { + menu.setOnClickListener( + new OnClickListener() { + @Override + public void onClick(View view) { - if (sideMenu.isDrawerVisible(Gravity.LEFT)) { - sideMenu.closeDrawer(sideMenuContent); - } else { - sideMenu.openDrawer(sideMenuContent); - } - } - }); + if (sideMenu.isDrawerVisible(Gravity.LEFT)) { + sideMenu.closeDrawer(sideMenuContent); + } else { + sideMenu.openDrawer(sideMenuContent); + } + } + }); quitLayout = findViewById(R.id.side_menu_quit); - quitLayout.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View view) { - LinphoneActivity.instance().quit(); - } - }); + quitLayout.setOnClickListener( + new OnClickListener() { + @Override + public void onClick(View view) { + LinphoneActivity.instance().quit(); + } + }); } private int getStatusIconResource(RegistrationState state) { @@ -1697,7 +1837,6 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick TextView address = defaultAccount.findViewById(R.id.main_account_address); TextView displayName = defaultAccount.findViewById(R.id.main_account_display_name); - ProxyConfig proxy = LinphoneManager.getLc().getDefaultProxyConfig(); if (proxy == null) { displayName.setText(getString(R.string.no_account)); @@ -1713,31 +1852,37 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick status.setImageResource(getStatusIconResource(proxy.getState())); status.setVisibility(View.VISIBLE); - defaultAccount.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View view) { - LinphoneActivity.instance().displayAccountSettings(LinphonePreferences.instance().getDefaultAccountIndex()); - openOrCloseSideMenu(false); - } - }); + defaultAccount.setOnClickListener( + new OnClickListener() { + @Override + public void onClick(View view) { + LinphoneActivity.instance() + .displayAccountSettings( + LinphonePreferences.instance() + .getDefaultAccountIndex()); + openOrCloseSideMenu(false); + } + }); } } public void refreshAccounts() { - if (LinphoneManager.getLc().getProxyConfigList() != null && - LinphoneManager.getLc().getProxyConfigList().length > 1) { + if (LinphoneManager.getLc().getProxyConfigList() != null + && LinphoneManager.getLc().getProxyConfigList().length > 1) { accountsList.setVisibility(View.VISIBLE); accountsList.setAdapter(new AccountsListAdapter()); - accountsList.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView adapterView, View view, int i, long l) { - if (view != null && view.getTag() != null) { - int position = Integer.parseInt(view.getTag().toString()); - LinphoneActivity.instance().displayAccountSettings(position); - } - openOrCloseSideMenu(false); - } - }); + accountsList.setOnItemClickListener( + new AdapterView.OnItemClickListener() { + @Override + public void onItemClick( + AdapterView adapterView, View view, int i, long l) { + if (view != null && view.getTag() != null) { + int position = Integer.parseInt(view.getTag().toString()); + LinphoneActivity.instance().displayAccountSettings(position); + } + openOrCloseSideMenu(false); + } + }); } else { accountsList.setVisibility(View.GONE); } @@ -1749,6 +1894,150 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick defaultAccount = findViewById(R.id.default_account); } + // Inapp Purchase + private void isTrialAccount() { + if (LinphoneManager.getLc().getDefaultProxyConfig() != null + && LinphonePreferences.instance().getInappPopupTime() != null) { + XmlRpcHelper helper = new XmlRpcHelper(); + helper.isTrialAccountAsync( + new XmlRpcListenerBase() { + @Override + public void onTrialAccountFetched(boolean isTrial) { + isTrialAccount = isTrial; + getExpirationAccount(); + } + + @Override + public void onError(String error) {} + }, + LinphonePreferences.instance() + .getAccountUsername( + LinphonePreferences.instance().getDefaultAccountIndex()), + LinphonePreferences.instance() + .getAccountHa1( + LinphonePreferences.instance().getDefaultAccountIndex())); + } + } + + private void getExpirationAccount() { + if (LinphoneManager.getLc().getDefaultProxyConfig() != null + && LinphonePreferences.instance().getInappPopupTime() != null) { + XmlRpcHelper helper = new XmlRpcHelper(); + helper.getAccountExpireAsync( + new XmlRpcListenerBase() { + @Override + public void onAccountExpireFetched(String result) { + if (result != null) { + long timestamp = Long.parseLong(result); + + Calendar calresult = Calendar.getInstance(); + calresult.setTimeInMillis(timestamp); + + int diff = getDiffDays(calresult, Calendar.getInstance()); + if (diff != -1 + && diff + <= getResources() + .getInteger( + R.integer + .days_notification_shown)) { + displayInappNotification(timestampToHumanDate(calresult)); + } + } + } + + @Override + public void onError(String error) {} + }, + LinphonePreferences.instance() + .getAccountUsername( + LinphonePreferences.instance().getDefaultAccountIndex()), + LinphonePreferences.instance() + .getAccountHa1( + LinphonePreferences.instance().getDefaultAccountIndex())); + } + } + + public void displayInappNotification(String date) { + Timestamp now = new Timestamp(new Date().getTime()); + if (LinphonePreferences.instance().getInappPopupTime() != null + && Long.parseLong(LinphonePreferences.instance().getInappPopupTime()) + > now.getTime()) { + return; + } else { + long newDate = + now.getTime() + + getResources().getInteger(R.integer.time_between_inapp_notification); + LinphonePreferences.instance().setInappPopupTime(String.valueOf(newDate)); + } + if (isTrialAccount) { + LinphoneService.instance() + .getNotificationManager() + .displayInappNotification( + String.format( + getString(R.string.inapp_notification_trial_expire), date)); + } else { + LinphoneService.instance() + .getNotificationManager() + .displayInappNotification( + String.format( + getString(R.string.inapp_notification_account_expire), date)); + } + } + + private String timestampToHumanDate(Calendar cal) { + SimpleDateFormat dateFormat; + dateFormat = + new SimpleDateFormat(getResources().getString(R.string.inapp_popup_date_format)); + return dateFormat.format(cal.getTime()); + } + + private int getDiffDays(Calendar cal1, Calendar cal2) { + if (cal1 == null || cal2 == null) { + return -1; + } + if (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) + && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)) { + return cal1.get(Calendar.DAY_OF_YEAR) - cal2.get(Calendar.DAY_OF_YEAR); + } + return -1; + } + + private class LocalOrientationEventListener extends OrientationEventListener { + public LocalOrientationEventListener(Context context) { + super(context); + } + + @Override + public void onOrientationChanged(final int o) { + if (o == OrientationEventListener.ORIENTATION_UNKNOWN) { + return; + } + + int degrees = 270; + if (o < 45 || o > 315) degrees = 0; + else if (o < 135) degrees = 90; + else if (o < 225) degrees = 180; + + if (mAlwaysChangingPhoneAngle == degrees) { + return; + } + mAlwaysChangingPhoneAngle = degrees; + + Log.d("Phone orientation changed to ", degrees); + int rotation = (360 - degrees) % 360; + Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull(); + if (lc != null) { + lc.setDeviceRotation(rotation); + Call currentCall = lc.getCurrentCall(); + if (currentCall != null + && currentCall.cameraEnabled() + && currentCall.getCurrentParams().videoEnabled()) { + lc.updateCall(currentCall, null); + } + } + } + } + class AccountsListAdapter extends BaseAdapter { List proxy_list; @@ -1815,82 +2104,6 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick } } - //Inapp Purchase - private void isTrialAccount() { - if (LinphoneManager.getLc().getDefaultProxyConfig() != null && LinphonePreferences.instance().getInappPopupTime() != null) { - XmlRpcHelper helper = new XmlRpcHelper(); - helper.isTrialAccountAsync(new XmlRpcListenerBase() { - @Override - public void onTrialAccountFetched(boolean isTrial) { - isTrialAccount = isTrial; - getExpirationAccount(); - } - - @Override - public void onError(String error) { - } - }, LinphonePreferences.instance().getAccountUsername(LinphonePreferences.instance().getDefaultAccountIndex()), LinphonePreferences.instance().getAccountHa1(LinphonePreferences.instance().getDefaultAccountIndex())); - } - } - - private void getExpirationAccount() { - if (LinphoneManager.getLc().getDefaultProxyConfig() != null && LinphonePreferences.instance().getInappPopupTime() != null) { - XmlRpcHelper helper = new XmlRpcHelper(); - helper.getAccountExpireAsync(new XmlRpcListenerBase() { - @Override - public void onAccountExpireFetched(String result) { - if (result != null) { - long timestamp = Long.parseLong(result); - - Calendar calresult = Calendar.getInstance(); - calresult.setTimeInMillis(timestamp); - - int diff = getDiffDays(calresult, Calendar.getInstance()); - if (diff != -1 && diff <= getResources().getInteger(R.integer.days_notification_shown)) { - displayInappNotification(timestampToHumanDate(calresult)); - } - } - } - - @Override - public void onError(String error) { - } - }, LinphonePreferences.instance().getAccountUsername(LinphonePreferences.instance().getDefaultAccountIndex()), LinphonePreferences.instance().getAccountHa1(LinphonePreferences.instance().getDefaultAccountIndex())); - } - } - - public void displayInappNotification(String date) { - Timestamp now = new Timestamp(new Date().getTime()); - if (LinphonePreferences.instance().getInappPopupTime() != null && Long.parseLong(LinphonePreferences.instance().getInappPopupTime()) > now.getTime()) { - return; - } else { - long newDate = now.getTime() + getResources().getInteger(R.integer.time_between_inapp_notification); - LinphonePreferences.instance().setInappPopupTime(String.valueOf(newDate)); - } - if (isTrialAccount) { - LinphoneService.instance().getNotificationManager().displayInappNotification(String.format(getString(R.string.inapp_notification_trial_expire), date)); - } else { - LinphoneService.instance().getNotificationManager().displayInappNotification(String.format(getString(R.string.inapp_notification_account_expire), date)); - } - - } - - private String timestampToHumanDate(Calendar cal) { - SimpleDateFormat dateFormat; - dateFormat = new SimpleDateFormat(getResources().getString(R.string.inapp_popup_date_format)); - return dateFormat.format(cal.getTime()); - } - - private int getDiffDays(Calendar cal1, Calendar cal2) { - if (cal1 == null || cal2 == null) { - return -1; - } - if (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)) { - return cal1.get(Calendar.DAY_OF_YEAR) - cal2.get(Calendar.DAY_OF_YEAR); - } - return -1; - } - private class MenuItem { public String name; public int icon; @@ -1909,7 +2122,8 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick private List mItems; private int mResource; - public MenuAdapter(@NonNull Context context, int resource, @NonNull List objects) { + public MenuAdapter( + @NonNull Context context, int resource, @NonNull List objects) { super(context, resource, objects); mResource = resource; mItems = objects; @@ -1929,7 +2143,8 @@ public class LinphoneActivity extends LinphoneGenericActivity implements OnClick @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { - LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); + LayoutInflater inflater = + (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); View rowView = inflater.inflate(mResource, parent, false); diff --git a/app/src/main/java/org/linphone/LinphoneLauncherActivity.java b/app/src/main/java/org/linphone/LinphoneLauncherActivity.java index db9478439..13b2017a6 100644 --- a/app/src/main/java/org/linphone/LinphoneLauncherActivity.java +++ b/app/src/main/java/org/linphone/LinphoneLauncherActivity.java @@ -19,6 +19,8 @@ along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ +import static android.content.Intent.ACTION_MAIN; + import android.app.Activity; import android.content.Intent; import android.content.pm.ActivityInfo; @@ -26,19 +28,13 @@ import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.util.Log; - -import org.linphone.settings.LinphonePreferences; import org.linphone.assistant.RemoteProvisioningActivity; import org.linphone.call.CallActivity; import org.linphone.contacts.ContactsManager; +import org.linphone.settings.LinphonePreferences; import org.linphone.utils.FileUtils; -import org.linphone.utils.LinphoneUtils; -import static android.content.Intent.ACTION_MAIN; - -/** - * Launch Linphone main activity when Service is ready. - */ +/** Launch Linphone main activity when Service is ready. */ public class LinphoneLauncherActivity extends Activity { private final String ACTION_CALL_LINPHONE = "org.linphone.intent.action.CallLaunched"; @@ -75,7 +71,10 @@ public class LinphoneLauncherActivity extends Activity { } } else if (Intent.ACTION_VIEW.equals(action)) { if (LinphoneService.isReady()) { - addressToCall = ContactsManager.getInstance().getAddressOrNumberForAndroidContact(getContentResolver(), intent.getData()); + addressToCall = + ContactsManager.getInstance() + .getAddressOrNumberForAndroidContact( + getContentResolver(), intent.getData()); } else { uriToResolve = intent.getData(); } @@ -104,72 +103,90 @@ public class LinphoneLauncherActivity extends Activity { protected void onServiceReady() { final Class classToStart; - /*if (getResources().getBoolean(R.bool.show_tutorials_instead_of_app)) { - classToStart = TutorialLauncherActivity.class; - } else */ - if (getResources().getBoolean(R.bool.display_sms_remote_provisioning_activity) && LinphonePreferences.instance().isFirstRemoteProvisioning()) { + /*if (getResources().getBoolean(R.bool.show_tutorials_instead_of_app)) { + classToStart = TutorialLauncherActivity.class; + } else */ + if (getResources().getBoolean(R.bool.display_sms_remote_provisioning_activity) + && LinphonePreferences.instance().isFirstRemoteProvisioning()) { classToStart = RemoteProvisioningActivity.class; } else { classToStart = LinphoneActivity.class; } - mHandler.postDelayed(new Runnable() { - @Override - public void run() { - Intent newIntent = new Intent(LinphoneLauncherActivity.this, classToStart); - Intent intent = getIntent(); - String stringFileShared = null; - String stringUriFileShared = null; - Uri fileUri = null; - if (intent != null) { - String action = intent.getAction(); - String type = intent.getType(); - newIntent.setData(intent.getData()); - if (Intent.ACTION_SEND.equals(action) && type != null) { - if (("text/plain").equals(type) && (String) intent.getStringExtra(Intent.EXTRA_TEXT) != null) { - stringFileShared = intent.getStringExtra(Intent.EXTRA_TEXT); - newIntent.putExtra("msgShared", stringFileShared); - } else { - fileUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM); - stringUriFileShared = FileUtils.getFilePath(getBaseContext(), fileUri); - newIntent.putExtra("fileShared", stringUriFileShared); + mHandler.postDelayed( + new Runnable() { + @Override + public void run() { + Intent newIntent = new Intent(LinphoneLauncherActivity.this, classToStart); + Intent intent = getIntent(); + String stringFileShared = null; + String stringUriFileShared = null; + Uri fileUri = null; + if (intent != null) { + String action = intent.getAction(); + String type = intent.getType(); + newIntent.setData(intent.getData()); + if (Intent.ACTION_SEND.equals(action) && type != null) { + if (("text/plain").equals(type) + && (String) intent.getStringExtra(Intent.EXTRA_TEXT) + != null) { + stringFileShared = intent.getStringExtra(Intent.EXTRA_TEXT); + newIntent.putExtra("msgShared", stringFileShared); + } else { + fileUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM); + stringUriFileShared = + FileUtils.getFilePath(getBaseContext(), fileUri); + newIntent.putExtra("fileShared", stringUriFileShared); + } + } else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) { + if (type.startsWith("image/")) { + // TODO : Manage multiple files sharing + } + } else if (ACTION_CALL_LINPHONE.equals(action) + && (intent.getStringExtra("NumberToCall") != null)) { + String numberToCall = intent.getStringExtra("NumberToCall"); + if (CallActivity.isInstanciated()) { + CallActivity.instance().startIncomingCallActivity(); + } else { + LinphoneManager.getInstance() + .newOutgoingCall(numberToCall, null); + } + } } - } else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) { - if (type.startsWith("image/")) { - //TODO : Manage multiple files sharing + if (uriToResolve != null) { + addressToCall = + ContactsManager.getInstance() + .getAddressOrNumberForAndroidContact( + getContentResolver(), uriToResolve); + Log.i( + "LinphoneLauncher", + "Intent has uri to resolve : " + uriToResolve.toString()); + uriToResolve = null; } - } else if (ACTION_CALL_LINPHONE.equals(action) && (intent.getStringExtra("NumberToCall") != null)) { - String numberToCall = intent.getStringExtra("NumberToCall"); - if (CallActivity.isInstanciated()) { - CallActivity.instance().startIncomingCallActivity(); - } else { - LinphoneManager.getInstance().newOutgoingCall(numberToCall, null); + if (addressToCall != null) { + newIntent.putExtra("SipUriOrNumber", addressToCall); + Log.i( + "LinphoneLauncher", + "Intent has address to call : " + addressToCall); + addressToCall = null; + } + startActivity(newIntent); + if (classToStart == LinphoneActivity.class + && LinphoneActivity.isInstanciated() + && (stringFileShared != null || fileUri != null)) { + if (stringFileShared != null) { + LinphoneActivity.instance() + .displayChat(null, stringFileShared, null); + } else if (fileUri != null) { + LinphoneActivity.instance() + .displayChat(null, null, stringUriFileShared); + } } } - } - if (uriToResolve != null) { - addressToCall = ContactsManager.getInstance().getAddressOrNumberForAndroidContact(getContentResolver(), uriToResolve); - Log.i("LinphoneLauncher", "Intent has uri to resolve : " + uriToResolve.toString()); - uriToResolve = null; - } - if (addressToCall != null) { - newIntent.putExtra("SipUriOrNumber", addressToCall); - Log.i("LinphoneLauncher", "Intent has address to call : " + addressToCall); - addressToCall = null; - } - startActivity(newIntent); - if (classToStart == LinphoneActivity.class && LinphoneActivity.isInstanciated() && (stringFileShared != null || fileUri != null)) { - if (stringFileShared != null) { - LinphoneActivity.instance().displayChat(null, stringFileShared, null); - } else if (fileUri != null) { - LinphoneActivity.instance().displayChat(null, null, stringUriFileShared); - } - } - } - }, 1000); + }, + 1000); } - private class ServiceWaitThread extends Thread { public void run() { while (!LinphoneService.isReady()) { @@ -179,16 +196,14 @@ public class LinphoneLauncherActivity extends Activity { throw new RuntimeException("waiting thread sleep() has been interrupted"); } } - mHandler.post(new Runnable() { - @Override - public void run() { - onServiceReady(); - } - }); + mHandler.post( + new Runnable() { + @Override + public void run() { + onServiceReady(); + } + }); mServiceThread = null; } } - } - - diff --git a/app/src/main/java/org/linphone/LinphoneManager.java b/app/src/main/java/org/linphone/LinphoneManager.java index 29fb0b6a4..34671ad88 100644 --- a/app/src/main/java/org/linphone/LinphoneManager.java +++ b/app/src/main/java/org/linphone/LinphoneManager.java @@ -19,6 +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. */ +import static android.media.AudioManager.MODE_RINGTONE; +import static android.media.AudioManager.STREAM_RING; +import static android.media.AudioManager.STREAM_VOICE_CALL; + import android.annotation.SuppressLint; import android.app.AlertDialog; import android.app.Dialog; @@ -52,7 +56,17 @@ import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.Toast; - +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.sql.Timestamp; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.Timer; +import java.util.TimerTask; import org.linphone.assistant.AssistantActivity; import org.linphone.call.CallActivity; import org.linphone.call.CallIncomingActivity; @@ -116,36 +130,37 @@ import org.linphone.utils.LinphoneMediaScanner; import org.linphone.utils.LinphoneUtils; import org.linphone.utils.MediaScannerListener; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.sql.Timestamp; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; -import java.util.Timer; -import java.util.TimerTask; - -import static android.media.AudioManager.MODE_RINGTONE; -import static android.media.AudioManager.STREAM_RING; -import static android.media.AudioManager.STREAM_VOICE_CALL; - /** - * Manager of the low level LibLinphone stuff.
- * Including:
    - *
  • Starting C liblinphone
  • - *
  • Reacting to C liblinphone state changes
  • - *
  • Calling Linphone android service listener methods
  • - *
  • Interacting from Android GUI/service with low level SIP stuff/
  • + * Manager of the low level LibLinphone stuff.
    + * Including: + * + *
      + *
    • Starting C liblinphone + *
    • Reacting to C liblinphone state changes + *
    • Calling Linphone android service listener methods + *
    • Interacting from Android GUI/service with low level SIP stuff/ *
    - *

    - * Add Service Listener to react to Linphone state changes. + * + *

    Add Service Listener to react to Linphone state changes. */ public class LinphoneManager implements CoreListener, SensorEventListener, AccountCreatorListener { + private static final int LINPHONE_VOLUME_STREAM = STREAM_VOICE_CALL; + private static final int dbStep = 4; private static LinphoneManager instance; + private static boolean sExited; + public final String mConfigFile; + /** Called when the activity is first created. */ + private final String mLPConfigXsd; + + private final String mLinphoneFactoryConfigFile; + private final String mDynamicConfigFile; + private final String mChatDatabaseFile; + private final String mRingSoundFile; + private final String mCallLogDatabaseFile; + private final String mFriendsDatabaseFile; + private final String mUserCertsPath; + public String wizardLoginViewDomain = null; private Context mServiceContext; private AudioManager mAudioManager; private PowerManager mPowerManager; @@ -155,7 +170,6 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou private OpenH264DownloadHelper mCodecDownloader; private OpenH264DownloadHelperListener mCodecListener; private String basePath; - private static boolean sExited; private boolean mAudioFocused; private boolean echoTesterIsRunning; private boolean dozeModeEnabled; @@ -180,8 +194,13 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou private boolean mProximitySensingEnabled; private boolean handsetON = false; private Address mCurrentChatRoomAddress; - - public String wizardLoginViewDomain = null; + private Timer mTimer; + private Map mUnreadChatsPerRoom; + private LinphoneMediaScanner mMediaScanner; + private Call ringingCall; + private MediaPlayer mRingerPlayer; + private Vibrator mVibrator; + private boolean isRinging; protected LinphoneManager(final Context c) { mUnreadChatsPerRoom = new HashMap(); @@ -203,41 +222,135 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou mAudioManager = ((AudioManager) c.getSystemService(Context.AUDIO_SERVICE)); mVibrator = (Vibrator) c.getSystemService(Context.VIBRATOR_SERVICE); mPowerManager = (PowerManager) c.getSystemService(Context.POWER_SERVICE); - mConnectivityManager = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE); + mConnectivityManager = + (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE); mSensorManager = (SensorManager) c.getSystemService(Context.SENSOR_SERVICE); mProximity = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY); mR = c.getResources(); - - File f=new File(mUserCertsPath); - if(!f.exists()){ - if(!f.mkdir()){ - Log.e(mUserCertsPath+" can't be created."); + + File f = new File(mUserCertsPath); + if (!f.exists()) { + if (!f.mkdir()) { + Log.e(mUserCertsPath + " can't be created."); } } mMediaScanner = new LinphoneMediaScanner(c); } - private static final int LINPHONE_VOLUME_STREAM = STREAM_VOICE_CALL; - private static final int dbStep = 4; - /** - * Called when the activity is first created. - */ - private final String mLPConfigXsd; - private final String mLinphoneFactoryConfigFile; - private final String mDynamicConfigFile; - public final String mConfigFile; - private final String mChatDatabaseFile; - private final String mRingSoundFile; - private final String mCallLogDatabaseFile; - private final String mFriendsDatabaseFile; - private final String mUserCertsPath; - private Timer mTimer; - private Map mUnreadChatsPerRoom; - private LinphoneMediaScanner mMediaScanner; + public static final synchronized LinphoneManager createAndStart(Context c) { + if (instance != null) { + Log.e( + "Linphone Manager is already initialized ! Destroying it and creating a new one..."); + destroy(); + } + + instance = new LinphoneManager(c); + instance.startLibLinphone(c); + instance.initOpenH264DownloadHelper(); + + // H264 codec Management - set to auto mode -> MediaCodec >= android 5.0 >= OpenH264 + H264Helper.setH264Mode(H264Helper.MODE_AUTO, getLc()); + + return instance; + } + + public static final synchronized LinphoneManager getInstance() { + if (instance != null) return instance; + + if (sExited) { + throw new RuntimeException( + "Linphone Manager was already destroyed. " + + "Better use getLcIfManagerNotDestroyedOrNull and check returned value"); + } + + throw new RuntimeException("Linphone Manager should be created before accessed"); + } + + public static final synchronized Core getLc() { + return getInstance().mLc; + } + + public static Boolean isProximitySensorNearby(final SensorEvent event) { + float threshold = 4.001f; // <= 4 cm is near + + final float distanceInCm = event.values[0]; + final float maxDistance = event.sensor.getMaximumRange(); + Log.d( + "Proximity sensor report [" + + distanceInCm + + "] , for max range [" + + maxDistance + + "]"); + + if (maxDistance <= threshold) { + // Case binary 0/1 and short sensors + threshold = maxDistance; + } + return distanceInCm < threshold; + } + + public static void ContactsManagerDestroy() { + if (LinphoneManager.instance != null && LinphoneManager.instance.mServiceContext != null) + LinphoneManager.instance + .mServiceContext + .getContentResolver() + .unregisterContentObserver(ContactsManager.getInstance()); + ContactsManager.getInstance().destroy(); + } + + public static void BluetoothManagerDestroy() { + BluetoothManager.getInstance().destroy(); + } + + public static synchronized void destroy() { + if (instance == null) return; + instance.changeStatusToOffline(); + instance.mMediaScanner.destroy(); + sExited = true; + instance.destroyCore(); + instance = null; + } + + public static String extractADisplayName(Resources r, Address address) { + if (address == null) return r.getString(R.string.unknown_incoming_call_name); + + final String displayName = address.getDisplayName(); + if (displayName != null) { + return displayName; + } else if (address.getUsername() != null) { + return address.getUsername(); + } else { + String rms = address.toString(); + if (rms != null && rms.length() > 1) return rms; + + return r.getString(R.string.unknown_incoming_call_name); + } + } + + public static boolean reinviteWithVideo() { + return CallManager.getInstance().reinviteWithVideo(); + } + + public static synchronized Core getLcIfManagerNotDestroyedOrNull() { + if (sExited || instance == null) { + // Can occur if the UI thread play a posted event but in the meantime the + // LinphoneManager was destroyed + // Ex: stop call and quickly terminate application. + return null; + } + return getLc(); + } + + public static final boolean isInstanciated() { + return instance != null; + } private void routeAudioToSpeakerHelper(boolean speakerOn) { - Log.w("Routing audio to " + (speakerOn ? "speaker" : "earpiece") + ", disabling bluetooth audio route"); + Log.w( + "Routing audio to " + + (speakerOn ? "speaker" : "earpiece") + + ", disabling bluetooth audio route"); BluetoothManager.getInstance().disableBluetoothSCO(); enableSpeaker(speakerOn); @@ -259,57 +372,79 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou } mCodecDownloader = Factory.instance().createOpenH264DownloadHelper(getContext()); - mCodecListener = new OpenH264DownloadHelperListener() { - ProgressDialog progress; - int ctxt = 0; - int box = 1; + mCodecListener = + new OpenH264DownloadHelperListener() { + ProgressDialog progress; + int ctxt = 0; + int box = 1; - @Override - public void OnProgress(final int current, final int max) { - mHandler.post(new Runnable() { @Override - public void run() { - OpenH264DownloadHelper ohcodec = LinphoneManager.getInstance().getOpenH264DownloadHelper(); - if (progress == null) { - progress = new ProgressDialog((Context) ohcodec.getUserData(ctxt)); - progress.setCanceledOnTouchOutside(false); - progress.setCancelable(false); - progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); - } else if (current <= max) { - progress.setMessage(getString(R.string.assistant_openh264_downloading)); - progress.setMax(max); - progress.setProgress(current); - progress.show(); - } else { - progress.dismiss(); - progress = null; - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { - LinphoneManager.getLc().reloadMsPlugins(AssistantActivity.instance().getApplicationInfo().nativeLibraryDir); - AssistantActivity.instance().endDownloadCodec(); - } else { - // We need to restart due to bad android linker - AssistantActivity.instance().restartApplication(); - } - } + public void OnProgress(final int current, final int max) { + mHandler.post( + new Runnable() { + @Override + public void run() { + OpenH264DownloadHelper ohcodec = + LinphoneManager.getInstance() + .getOpenH264DownloadHelper(); + if (progress == null) { + progress = + new ProgressDialog( + (Context) ohcodec.getUserData(ctxt)); + progress.setCanceledOnTouchOutside(false); + progress.setCancelable(false); + progress.setProgressStyle( + ProgressDialog.STYLE_HORIZONTAL); + } else if (current <= max) { + progress.setMessage( + getString( + R.string + .assistant_openh264_downloading)); + progress.setMax(max); + progress.setProgress(current); + progress.show(); + } else { + progress.dismiss(); + progress = null; + if (Build.VERSION.SDK_INT + >= Build.VERSION_CODES.LOLLIPOP_MR1) { + LinphoneManager.getLc() + .reloadMsPlugins( + AssistantActivity.instance() + .getApplicationInfo() + .nativeLibraryDir); + AssistantActivity.instance().endDownloadCodec(); + } else { + // We need to restart due to bad android linker + AssistantActivity.instance().restartApplication(); + } + } + } + }); } - }); - } - @Override - public void OnError(final String error) { - mHandler.post(new Runnable() { @Override - public void run() { - if (progress != null) progress.dismiss(); - AlertDialog.Builder builder = new AlertDialog.Builder((Context) LinphoneManager.getInstance().getOpenH264DownloadHelper().getUserData(ctxt)); - builder.setMessage(getString(R.string.assistant_openh264_error)); - builder.setCancelable(false); - builder.setNeutralButton(getString(R.string.ok), null); - builder.show(); + public void OnError(final String error) { + mHandler.post( + new Runnable() { + @Override + public void run() { + if (progress != null) progress.dismiss(); + AlertDialog.Builder builder = + new AlertDialog.Builder( + (Context) + LinphoneManager.getInstance() + .getOpenH264DownloadHelper() + .getUserData(ctxt)); + builder.setMessage( + getString(R.string.assistant_openh264_error)); + builder.setCancelable(false); + builder.setNeutralButton(getString(R.string.ok), null); + builder.show(); + } + }); } - }); - } - }; + }; mCodecDownloader.setOpenH264HelperListener(mCodecListener); } @@ -329,23 +464,6 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou routeAudioToSpeakerHelper(false); } - public synchronized static final LinphoneManager createAndStart(Context c) { - if (instance != null) { - Log.e("Linphone Manager is already initialized ! Destroying it and creating a new one..."); - destroy(); - } - - instance = new LinphoneManager(c); - instance.startLibLinphone(c); - instance.initOpenH264DownloadHelper(); - - // H264 codec Management - set to auto mode -> MediaCodec >= android 5.0 >= OpenH264 - H264Helper.setH264Mode(H264Helper.MODE_AUTO, getLc()); - - - return instance; - } - private boolean isPresenceModelActivitySet() { Core lc = getLcIfManagerNotDestroyedOrNull(); if (isInstanciated() && lc != null) { @@ -360,24 +478,28 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou PresenceModel model = lc.createPresenceModel(); model.setBasicStatus(PresenceBasicStatus.Open); lc.setPresenceModel(model); - /* - if (isInstanciated() && lc != null && isPresenceModelActivitySet() && lc.getPresenceModel().getActivity().getType() != PresenceActivity.Type.TV) { - lc.getPresenceModel().getActivity().setType(PresenceActivity.Type.TV); - } else if (isInstanciated() && lc != null && !isPresenceModelActivitySet()) { - PresenceModel model = lc.createPresenceModelWithActivity(PresenceActivity.Type.TV, null); - lc.setPresenceModel(model); - } - */ + /* + if (isInstanciated() && lc != null && isPresenceModelActivitySet() && lc.getPresenceModel().getActivity().getType() != PresenceActivity.Type.TV) { + lc.getPresenceModel().getActivity().setType(PresenceActivity.Type.TV); + } else if (isInstanciated() && lc != null && !isPresenceModelActivitySet()) { + PresenceModel model = lc.createPresenceModelWithActivity(PresenceActivity.Type.TV, null); + lc.setPresenceModel(model); + } + */ } public void changeStatusToOnThePhone() { Core lc = getLcIfManagerNotDestroyedOrNull(); if (lc == null) return; - if (isInstanciated() && isPresenceModelActivitySet() && lc.getPresenceModel().getActivity().getType() != PresenceActivity.Type.OnThePhone) { + if (isInstanciated() + && isPresenceModelActivitySet() + && lc.getPresenceModel().getActivity().getType() + != PresenceActivity.Type.OnThePhone) { lc.getPresenceModel().getActivity().setType(PresenceActivity.Type.OnThePhone); } else if (isInstanciated() && !isPresenceModelActivitySet()) { - PresenceModel model = lc.createPresenceModelWithActivity(PresenceActivity.Type.OnThePhone, null); + PresenceModel model = + lc.createPresenceModelWithActivity(PresenceActivity.Type.OnThePhone, null); lc.setPresenceModel(model); } } @@ -400,22 +522,6 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou } } - - public static synchronized final LinphoneManager getInstance() { - if (instance != null) return instance; - - if (sExited) { - throw new RuntimeException("Linphone Manager was already destroyed. " - + "Better use getLcIfManagerNotDestroyedOrNull and check returned value"); - } - - throw new RuntimeException("Linphone Manager should be created before accessed"); - } - - public static synchronized final Core getLc() { - return getInstance().mLc; - } - public String getLPConfigXsdPath() { return mLPConfigXsd; } @@ -426,10 +532,10 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou } public void newOutgoingCall(String to, String displayName) { -// if (mLc.inCall()) { -// listenerDispatcher.tryingNewOutgoingCallButAlreadyInCall(); -// return; -// } + // if (mLc.inCall()) { + // listenerDispatcher.tryingNewOutgoingCallButAlreadyInCall(); + // return; + // } if (to == null) return; // If to is only a username, try to find the contact to get an alias if existing @@ -451,29 +557,39 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou } ProxyConfig lpc = mLc.getDefaultProxyConfig(); - if (mR.getBoolean(R.bool.forbid_self_call) && lpc != null && lAddress.asStringUriOnly().equals(lpc.getIdentityAddress())) { + if (mR.getBoolean(R.bool.forbid_self_call) + && lpc != null + && lAddress.asStringUriOnly().equals(lpc.getIdentityAddress())) { return; } lAddress.setDisplayName(displayName); - boolean isLowBandwidthConnection = !LinphoneUtils.isHighBandwidthConnection(LinphoneService.instance().getApplicationContext()); + boolean isLowBandwidthConnection = + !LinphoneUtils.isHighBandwidthConnection( + LinphoneService.instance().getApplicationContext()); if (mLc.isNetworkReachable()) { try { if (Version.isVideoCapable()) { boolean prefVideoEnable = mPrefs.isVideoEnabled(); boolean prefInitiateWithVideo = mPrefs.shouldInitiateVideoCall(); - CallManager.getInstance().inviteAddress(lAddress, prefVideoEnable && prefInitiateWithVideo, isLowBandwidthConnection); + CallManager.getInstance() + .inviteAddress( + lAddress, + prefVideoEnable && prefInitiateWithVideo, + isLowBandwidthConnection); } else { - CallManager.getInstance().inviteAddress(lAddress, false, isLowBandwidthConnection); + CallManager.getInstance() + .inviteAddress(lAddress, false, isLowBandwidthConnection); } - } catch (CoreException e) { return; } } else if (LinphoneActivity.isInstanciated()) { - LinphoneActivity.instance().displayCustomToast(getString(R.string.error_network_unreachable), Toast.LENGTH_LONG); + LinphoneActivity.instance() + .displayCustomToast( + getString(R.string.error_network_unreachable), Toast.LENGTH_LONG); } else { Log.e("Error: " + getString(R.string.error_network_unreachable)); } @@ -491,28 +607,21 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou } String[] devices = getLc().getVideoDevicesList(); if (camId >= devices.length) { - Log.e("Trying to use a camera id that's higher than the linphone's devices list, using 0 to prevent crash..."); + Log.e( + "Trying to use a camera id that's higher than the linphone's devices list, using 0 to prevent crash..."); camId = 0; } String newDevice = devices[camId]; LinphoneManager.getLc().setVideoDevice(newDevice); } - public interface AddressType { - void setText(CharSequence s); - - CharSequence getText(); - - void setDisplayedName(String s); - - String getDisplayedName(); - } - public void enableCamera(Call call, boolean enable) { if (call != null) { call.enableCamera(enable); if (mServiceContext.getResources().getBoolean(R.bool.enable_call_notification)) - LinphoneService.instance().getNotificationManager().displayCallNotification(mLc.getCurrentCall()); + LinphoneService.instance() + .getNotificationManager() + .displayCallNotification(mLc.getCurrentCall()); } } @@ -535,8 +644,7 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou } public void initTunnelFromConf() { - if (!mLc.tunnelAvailable()) - return; + if (!mLc.tunnelAvailable()) return; NetworkInfo info = mConnectivityManager.getActiveNetworkInfo(); Tunnel tunnel = mLc.getTunnel(); @@ -569,6 +677,16 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou return false; } + // public void loadConfig(){ + // try { + // copyIfNotExist(R.raw.configrc, mConfigFile); + // } catch (Exception e){ + // Log.w(e); + // } + // LinphonePreferences.instance().setRemoteProvisioningUrl("file://" + mConfigFile); + // getLc().getConfig().setInt("misc","transient_provisioning",1); + // } + private void manageTunnelServer(NetworkInfo info) { if (mLc == null) return; if (!mLc.tunnelAvailable()) return; @@ -588,7 +706,7 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou } } - public synchronized final void destroyCore() { + public final synchronized void destroyCore() { sExited = true; ContactsManagerDestroy(); BluetoothManagerDestroy(); @@ -631,7 +749,6 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou } } - public void restartCore() { destroyCore(); startLibLinphone(mServiceContext); @@ -641,23 +758,25 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou private synchronized void startLibLinphone(Context c) { try { copyAssetsFromPackage(); - //traces alway start with traces enable to not missed first initialization + // traces alway start with traces enable to not missed first initialization mLc = Factory.instance().createCore(mConfigFile, mLinphoneFactoryConfigFile, c); mLc.addListener(this); mLc.start(); - TimerTask lTask = new TimerTask() { - @Override - public void run() { - LinphoneUtils.dispatchOnUIThread(new Runnable() { + TimerTask lTask = + new TimerTask() { @Override public void run() { - if (mLc != null) { - mLc.iterate(); - } + LinphoneUtils.dispatchOnUIThread( + new Runnable() { + @Override + public void run() { + if (mLc != null) { + mLc.iterate(); + } + } + }); } - }); - } - }; + }; /*use schedule instead of scheduleAtFixedRate to avoid iterate from being call in burst after cpu wake up*/ mTimer = new Timer("Linphone scheduler"); mTimer.schedule(lTask, 0, 20); @@ -669,14 +788,20 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou private void initPushNotificationsService() { if (getString(R.string.push_type).equals("firebase")) { try { - Class firebaseClass = Class.forName("com.google.firebase.iid.FirebaseInstanceId"); + Class firebaseClass = + Class.forName("com.google.firebase.iid.FirebaseInstanceId"); Object firebaseInstance = firebaseClass.getMethod("getInstance").invoke(null); - final String refreshedToken = (String) firebaseClass.getMethod("getToken").invoke(firebaseInstance); + final String refreshedToken = + (String) firebaseClass.getMethod("getToken").invoke(firebaseInstance); - //final String refreshedToken = com.google.firebase.iid.FirebaseInstanceId.getInstance().getToken(); + // final String refreshedToken = + // com.google.firebase.iid.FirebaseInstanceId.getInstance().getToken(); if (refreshedToken != null) { - Log.i("[Push Notification] init push notif service token is: " + refreshedToken); - LinphonePreferences.instance().setPushNotificationRegistrationID(refreshedToken); + Log.i( + "[Push Notification] init push notif service token is: " + + refreshedToken); + LinphonePreferences.instance() + .setPushNotificationRegistrationID(refreshedToken); } } catch (Exception e) { Log.i("[Push Notification] firebase not available."); @@ -702,7 +827,7 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou mLc.setCallLogsDatabasePath(mCallLogDatabaseFile); mLc.setFriendsDatabasePath(mFriendsDatabaseFile); mLc.setUserCertificatesPath(mUserCertsPath); - //mLc.setCallErrorTone(Reason.NotFound, mErrorToneFile); + // mLc.setCallErrorTone(Reason.NotFound, mErrorToneFile); enableDeviceRingtone(mPrefs.isDeviceRingtoneEnabled()); int availableCores = Runtime.getRuntime().availableProcessors(); @@ -712,7 +837,10 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou // Migrate existing linphone accounts to have conference factory uri set for (ProxyConfig lpc : mLc.getProxyConfigList()) { - if (lpc.getConferenceFactoryUri() == null && lpc.getIdentityAddress().getDomain().equals(getString(R.string.default_domain))) { + if (lpc.getConferenceFactoryUri() == null + && lpc.getIdentityAddress() + .getDomain() + .equals(getString(R.string.default_domain))) { lpc.edit(); lpc.setConferenceFactoryUri(getString(R.string.default_conference_factory_uri)); lpc.done(); @@ -723,11 +851,11 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou initPushNotificationsService(); } - /* - You cannot receive this through components declared in manifests, only - by explicitly registering for it with Context.registerReceiver(). This is a protected intent that can only - be sent by the system. - */ + /* + You cannot receive this through components declared in manifests, only + by explicitly registering for it with Context.registerReceiver(). This is a protected intent that can only + be sent by the system. + */ mKeepAliveIntentFilter = new IntentFilter(Intent.ACTION_SCREEN_ON); mKeepAliveIntentFilter.addAction(Intent.ACTION_SCREEN_OFF); @@ -742,14 +870,18 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou } catch (IllegalArgumentException e) { e.printStackTrace(); } - mProximityWakelock = mPowerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, mServiceContext.getPackageName() + ";manager_proximity_sensor"); - + mProximityWakelock = + mPowerManager.newWakeLock( + PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, + mServiceContext.getPackageName() + ";manager_proximity_sensor"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { mDozeIntentFilter = new IntentFilter(); mDozeIntentFilter.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED); mDozeReceiver = new DozeReceiver(); - dozeModeEnabled = ((PowerManager) mServiceContext.getSystemService(Context.POWER_SERVICE)).isDeviceIdleMode(); + dozeModeEnabled = + ((PowerManager) mServiceContext.getSystemService(Context.POWER_SERVICE)) + .isDeviceIdleMode(); mServiceContext.registerReceiver(mDozeReceiver, mDozeIntentFilter); } @@ -769,7 +901,9 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou resetCameraFromPreferences(); - accountCreator = LinphoneManager.getLc().createAccountCreator(LinphonePreferences.instance().getXmlrpcUrl()); + accountCreator = + LinphoneManager.getLc() + .createAccountCreator(LinphonePreferences.instance().getXmlrpcUrl()); accountCreator.setListener(this); callGsmON = false; @@ -822,16 +956,6 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou lInputStream.close(); } - //public void loadConfig(){ - // try { - // copyIfNotExist(R.raw.configrc, mConfigFile); - // } catch (Exception e){ - // Log.w(e); - // } - // LinphonePreferences.instance().setRemoteProvisioningUrl("file://" + mConfigFile); - // getLc().getConfig().setInt("misc","transient_provisioning",1); - //} - public void updateNetworkReachability() { if (mConnectivityManager == null) return; @@ -872,8 +996,9 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou int curtype = networkInfo.getType(); if (curtype != mLastNetworkType) { - //if kind of network has changed, we need to notify network_reachable(false) to make sure all current connections are destroyed. - //they will be re-created during setNetworkReachable(true). + // if kind of network has changed, we need to notify network_reachable(false) to + // make sure all current connections are destroyed. + // they will be re-created during setNetworkReachable(true). Log.i("Connectivity has changed."); mLc.setNetworkReachable(false); } @@ -883,7 +1008,8 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou } if (mLc.isNetworkReachable()) { - // When network isn't available, push informations might not be set. This should fix the issue. + // When network isn't available, push informations might not be set. This should fix the + // issue. LinphonePreferences prefs = LinphonePreferences.instance(); prefs.setPushNotificationEnabled(prefs.isPushNotificationEnabled()); } @@ -891,7 +1017,8 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou private void destroyLinphoneCore() { if (LinphonePreferences.instance() != null) { - // We set network reachable at false before destroy LC to not send register with expires at 0 + // We set network reachable at false before destroy LC to not send register with expires + // at 0 if (LinphonePreferences.instance().isPushNotificationEnabled() || LinphonePreferences.instance().isBackgroundModeEnabled()) { mLc.setNetworkReachable(false); @@ -921,7 +1048,8 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou public void enableProximitySensing(boolean enable) { if (enable) { if (!mProximitySensingEnabled) { - mSensorManager.registerListener(this, mProximity, SensorManager.SENSOR_DELAY_NORMAL); + mSensorManager.registerListener( + this, mProximity, SensorManager.SENSOR_DELAY_NORMAL); mProximitySensingEnabled = true; } } else { @@ -936,20 +1064,6 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou } } - public static Boolean isProximitySensorNearby(final SensorEvent event) { - float threshold = 4.001f; // <= 4 cm is near - - final float distanceInCm = event.values[0]; - final float maxDistance = event.sensor.getMaximumRange(); - Log.d("Proximity sensor report [" + distanceInCm + "] , for max range [" + maxDistance + "]"); - - if (maxDistance <= threshold) { - // Case binary 0/1 and short sensors - threshold = maxDistance; - } - return distanceInCm < threshold; - } - @Override public void onSensorChanged(SensorEvent event) { if (event.timestamp == 0) return; @@ -965,28 +1079,7 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou } @Override - public void onAccuracyChanged(Sensor sensor, int accuracy) { - - } - - public static void ContactsManagerDestroy() { - if (LinphoneManager.instance != null && LinphoneManager.instance.mServiceContext != null) - LinphoneManager.instance.mServiceContext.getContentResolver().unregisterContentObserver(ContactsManager.getInstance()); - ContactsManager.getInstance().destroy(); - } - - public static void BluetoothManagerDestroy() { - BluetoothManager.getInstance().destroy(); - } - - public static synchronized void destroy() { - if (instance == null) return; - instance.changeStatusToOffline(); - instance.mMediaScanner.destroy(); - sExited = true; - instance.destroyCore(); - instance = null; - } + public void onAccuracyChanged(Sensor sensor, int accuracy) {} public LinphoneMediaScanner getMediaScanner() { return mMediaScanner; @@ -1008,21 +1101,12 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou updateNetworkReachability(); } - private Call ringingCall; + public void onNewSubscriptionRequested(Core lc, Friend lf, String url) {} - private MediaPlayer mRingerPlayer; - private Vibrator mVibrator; - - public void onNewSubscriptionRequested(Core lc, Friend lf, String url) { - } - - public void onNotifyPresenceReceived(Core lc, Friend lf) { - } + public void onNotifyPresenceReceived(Core lc, Friend lf) {} @Override - public void onEcCalibrationAudioInit(Core lc) { - - } + public void onEcCalibrationAudioInit(Core lc) {} @Override public void onDtmfReceived(Core lc, Call call, int dtmf) { @@ -1035,12 +1119,16 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou return; } - if (mCurrentChatRoomAddress != null && cr.getPeerAddress().asStringUriOnly().equals(mCurrentChatRoomAddress.asStringUriOnly())) { + if (mCurrentChatRoomAddress != null + && cr.getPeerAddress() + .asStringUriOnly() + .equals(mCurrentChatRoomAddress.asStringUriOnly())) { Log.i("Message received for currently displayed chat room, do not make a notification"); return; } - if (message.getErrorInfo() != null && message.getErrorInfo().getReason() == Reason.UnsupportedContent) { + if (message.getErrorInfo() != null + && message.getErrorInfo().getReason() == Reason.UnsupportedContent) { Log.w("Message received but content is unsupported, do not notify it"); return; } @@ -1052,24 +1140,38 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou increaseUnreadCountForChatRoom(cr); - if (mServiceContext.getResources().getBoolean(R.bool.disable_chat_message_notification) || message.isOutgoing()) { + if (mServiceContext.getResources().getBoolean(R.bool.disable_chat_message_notification) + || message.isOutgoing()) { return; } final Address from = message.getFromAddress(); final LinphoneContact contact = ContactsManager.getInstance().findContactFromAddress(from); - final String textMessage = (message.hasTextContent()) ? message.getTextContent() : getString(R.string.content_description_incoming_file); + final String textMessage = + (message.hasTextContent()) + ? message.getTextContent() + : getString(R.string.content_description_incoming_file); String file = null; for (Content c : message.getContents()) { if (c.isFile()) { file = c.getFilePath(); - getMediaScanner().scanFile(new File(file), new MediaScannerListener() { - @Override - public void onMediaScanned(String path, Uri uri) { - createNotification(cr, contact, from, textMessage, message.getTime(), uri, FileUtils.getMimeFromFile(path)); - } - }); + getMediaScanner() + .scanFile( + new File(file), + new MediaScannerListener() { + @Override + public void onMediaScanned(String path, Uri uri) { + createNotification( + cr, + contact, + from, + textMessage, + message.getTime(), + uri, + FileUtils.getMimeFromFile(path)); + } + }); break; } } @@ -1079,31 +1181,82 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou } } - private void createNotification(ChatRoom cr, LinphoneContact contact, Address from, String textMessage, long time, Uri file, String mime) { + private void createNotification( + ChatRoom cr, + LinphoneContact contact, + Address from, + String textMessage, + long time, + Uri file, + String mime) { if (cr.hasCapability(ChatRoomCapabilities.OneToOne.toInt())) { if (contact != null) { - LinphoneService.instance().getNotificationManager().displayMessageNotification(cr.getPeerAddress().asStringUriOnly(), contact.getFullName(), contact.getThumbnailUri(), textMessage, cr.getLocalAddress(), time, file, mime); + LinphoneService.instance() + .getNotificationManager() + .displayMessageNotification( + cr.getPeerAddress().asStringUriOnly(), + contact.getFullName(), + contact.getThumbnailUri(), + textMessage, + cr.getLocalAddress(), + time, + file, + mime); } else { - LinphoneService.instance().getNotificationManager().displayMessageNotification(cr.getPeerAddress().asStringUriOnly(), from.getUsername(), null, textMessage, cr.getLocalAddress(), time, file, mime); + LinphoneService.instance() + .getNotificationManager() + .displayMessageNotification( + cr.getPeerAddress().asStringUriOnly(), + from.getUsername(), + null, + textMessage, + cr.getLocalAddress(), + time, + file, + mime); } } else { String subject = cr.getSubject(); if (contact != null) { - LinphoneService.instance().getNotificationManager().displayGroupChatMessageNotification(subject, cr.getPeerAddress().asStringUriOnly(), contact.getFullName(), contact.getThumbnailUri(), textMessage, cr.getLocalAddress(), time, file, mime); + LinphoneService.instance() + .getNotificationManager() + .displayGroupChatMessageNotification( + subject, + cr.getPeerAddress().asStringUriOnly(), + contact.getFullName(), + contact.getThumbnailUri(), + textMessage, + cr.getLocalAddress(), + time, + file, + mime); } else { - LinphoneService.instance().getNotificationManager().displayGroupChatMessageNotification(subject, cr.getPeerAddress().asStringUriOnly(), from.getUsername(), null, textMessage, cr.getLocalAddress(), time, file, mime); + LinphoneService.instance() + .getNotificationManager() + .displayGroupChatMessageNotification( + subject, + cr.getPeerAddress().asStringUriOnly(), + from.getUsername(), + null, + textMessage, + cr.getLocalAddress(), + time, + file, + mime); } } } public void setCurrentChatRoomAddress(Address address) { mCurrentChatRoomAddress = address; - LinphoneService.instance().setCurrentlyDisplayedChatRoom(address != null ? address.asStringUriOnly() : null); + LinphoneService.instance() + .setCurrentlyDisplayedChatRoom(address != null ? address.asStringUriOnly() : null); } @Override public void onEcCalibrationResult(Core lc, EcCalibratorStatus status, int delay_ms) { - ((AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE)).setMode(AudioManager.MODE_NORMAL); + ((AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE)) + .setMode(AudioManager.MODE_NORMAL); mAudioManager.abandonAudioFocus(null); Log.i("Set audio mode on 'Normal'"); } @@ -1123,7 +1276,11 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou } } - public void onRegistrationStateChanged(final Core lc, final ProxyConfig proxy, final RegistrationState state, final String message) { + public void onRegistrationStateChanged( + final Core lc, + final ProxyConfig proxy, + final RegistrationState state, + final String message) { Log.i("New registration state [" + state + "]"); if (LinphoneManager.getLc().getDefaultProxyConfig() == null) { subscribeFriendList(false); @@ -1132,14 +1289,10 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou public Context getContext() { try { - if (LinphoneActivity.isInstanciated()) - return LinphoneActivity.instance(); - else if (CallActivity.isInstanciated()) - return CallActivity.instance(); - else if (CallIncomingActivity.isInstanciated()) - return CallIncomingActivity.instance(); - else if (mServiceContext != null) - return mServiceContext; + if (LinphoneActivity.isInstanciated()) return LinphoneActivity.instance(); + else if (CallActivity.isInstanciated()) return CallActivity.instance(); + else if (CallIncomingActivity.isInstanciated()) return CallIncomingActivity.instance(); + else if (mServiceContext != null) return mServiceContext; else if (LinphoneService.isReady()) return LinphoneService.instance().getApplicationContext(); } catch (Exception e) { @@ -1163,7 +1316,8 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou } @SuppressLint("Wakelock") - public void onCallStateChanged(final Core lc, final Call call, final State state, final String message) { + public void onCallStateChanged( + final Core lc, final Call call, final State state, final String message) { Log.i("New call state [", state, "]"); if (state == State.IncomingReceived && !call.equals(lc.getCurrentCall())) { if (call.getReplacedCall() != null) { @@ -1177,25 +1331,30 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou if (mLc != null) { mLc.declineCall(call, Reason.Busy); } - } else if (state == State.IncomingReceived && (LinphonePreferences.instance().isAutoAnswerEnabled()) && !getCallGsmON()) { - TimerTask lTask = new TimerTask() { - @Override - public void run() { - if (mLc != null) { - if (mLc.getCallsNb() > 0) { - acceptCall(call); - if (LinphoneManager.getInstance() != null) { - LinphoneManager.getInstance().routeAudioToReceiver(); - if (LinphoneActivity.instance() != null) - LinphoneActivity.instance().startIncallActivity(); + } else if (state == State.IncomingReceived + && (LinphonePreferences.instance().isAutoAnswerEnabled()) + && !getCallGsmON()) { + TimerTask lTask = + new TimerTask() { + @Override + public void run() { + if (mLc != null) { + if (mLc.getCallsNb() > 0) { + acceptCall(call); + if (LinphoneManager.getInstance() != null) { + LinphoneManager.getInstance().routeAudioToReceiver(); + if (LinphoneActivity.instance() != null) + LinphoneActivity.instance().startIncallActivity(); + } + } } } - } - } - }; + }; mTimer = new Timer("Auto answer"); mTimer.schedule(lTask, mPrefs.getAutoAnswerTime()); - } else if (state == State.IncomingReceived || (state == State.IncomingEarlyMedia && mR.getBoolean(R.bool.allow_ringing_while_early_media))) { + } else if (state == State.IncomingReceived + || (state == State.IncomingEarlyMedia + && mR.getBoolean(R.bool.allow_ringing_while_early_media))) { // Brighten screen for at least 10 seconds if (mLc.getCallsNb() == 1) { requestAudioFocus(STREAM_RING); @@ -1205,17 +1364,18 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou // otherwise there is the beep } } else if (call == ringingCall && isRinging) { - //previous state was ringing, so stop ringing + // previous state was ringing, so stop ringing stopRinging(); } if (state == State.Connected) { if (mLc.getCallsNb() == 1) { - //It is for incoming calls, because outgoing calls enter MODE_IN_COMMUNICATION immediately when they start. - //However, incoming call first use the MODE_RINGING to play the local ring. + // It is for incoming calls, because outgoing calls enter MODE_IN_COMMUNICATION + // immediately when they start. + // However, incoming call first use the MODE_RINGING to play the local ring. if (call.getDir() == Call.Dir.Incoming) { setAudioManagerInCallMode(); - //mAudioManager.abandonAudioFocus(null); + // mAudioManager.abandonAudioFocus(null); requestAudioFocus(STREAM_VOICE_CALL); } } @@ -1228,16 +1388,21 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou if (state == State.End || state == State.Error) { if (mLc.getCallsNb() == 0) { - //Disabling proximity sensor + // Disabling proximity sensor enableProximitySensing(false); Context activity = getContext(); if (mAudioFocused) { int res = mAudioManager.abandonAudioFocus(null); - Log.d("Audio focus released a bit later: " + (res == AudioManager.AUDIOFOCUS_REQUEST_GRANTED ? "Granted" : "Denied")); + Log.d( + "Audio focus released a bit later: " + + (res == AudioManager.AUDIOFOCUS_REQUEST_GRANTED + ? "Granted" + : "Denied")); mAudioFocused = false; } if (activity != null) { - TelephonyManager tm = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE); + TelephonyManager tm = + (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE); if (tm.getCallState() == TelephonyManager.CALL_STATE_IDLE) { Log.d("---AudioManager: back to MODE_NORMAL"); mAudioManager.setMode(AudioManager.MODE_NORMAL); @@ -1251,14 +1416,18 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou // If the correspondent proposes video while audio call boolean remoteVideo = call.getRemoteParams().videoEnabled(); boolean localVideo = call.getCurrentParams().videoEnabled(); - boolean autoAcceptCameraPolicy = LinphonePreferences.instance().shouldAutomaticallyAcceptVideoRequests(); - if (remoteVideo && !localVideo && !autoAcceptCameraPolicy && !(LinphoneManager.getLc().getConference() != null)) { + boolean autoAcceptCameraPolicy = + LinphonePreferences.instance().shouldAutomaticallyAcceptVideoRequests(); + if (remoteVideo + && !localVideo + && !autoAcceptCameraPolicy + && !(LinphoneManager.getLc().getConference() != null)) { LinphoneManager.getLc().deferCallUpdate(call); } } if (state == State.OutgoingInit) { - //Enter the MODE_IN_COMMUNICATION mode as soon as possible, so that ringback - //is heard normally in earpiece or bluetooth receiver. + // Enter the MODE_IN_COMMUNICATION mode as soon as possible, so that ringback + // is heard normally in earpiece or bluetooth receiver. setAudioManagerInCallMode(); requestAudioFocus(STREAM_VOICE_CALL); startBluetooth(); @@ -1276,17 +1445,13 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou } } - public void onCallStatsUpdated(final Core lc, final Call call, final CallStats stats) { - } + public void onCallStatsUpdated(final Core lc, final Call call, final CallStats stats) {} @Override - public void onChatRoomStateChanged(Core lc, ChatRoom cr, ChatRoom.State state) { + public void onChatRoomStateChanged(Core lc, ChatRoom cr, ChatRoom.State state) {} - } - - public void onCallEncryptionChanged(Core lc, Call call, - boolean encrypted, String authenticationToken) { - } + public void onCallEncryptionChanged( + Core lc, Call call, boolean encrypted, String authenticationToken) {} public void startEcCalibration() throws CoreException { routeAudioToSpeaker(); @@ -1310,44 +1475,48 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou int sampleRate = 44100; mAudioManager.setStreamVolume(STREAM_VOICE_CALL, maxVolume, 0); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { - String sampleRateProperty = mAudioManager.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE); + String sampleRateProperty = + mAudioManager.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE); sampleRate = Integer.parseInt(sampleRateProperty); } - /*int status = */ - mLc.startEchoTester(sampleRate); + /*int status = */ mLc.startEchoTester(sampleRate); /*if (status > 0)*/ echoTesterIsRunning = true; - /*else { - echoTesterIsRunning = false; - routeAudioToReceiver(); - mAudioManager.setStreamVolume(STREAM_VOICE_CALL, oldVolume, 0); - ((AudioManager)getContext().getSystemService(Context.AUDIO_SERVICE)).setMode(AudioManager.MODE_NORMAL); - Log.i("Set audio mode on 'Normal'"); - }*/ + /*else { + echoTesterIsRunning = false; + routeAudioToReceiver(); + mAudioManager.setStreamVolume(STREAM_VOICE_CALL, oldVolume, 0); + ((AudioManager)getContext().getSystemService(Context.AUDIO_SERVICE)).setMode(AudioManager.MODE_NORMAL); + Log.i("Set audio mode on 'Normal'"); + }*/ return 1; - //return status; + // return status; } public int stopEchoTester() throws CoreException { echoTesterIsRunning = false; - /*int status = */ - mLc.stopEchoTester(); + /*int status = */ mLc.stopEchoTester(); routeAudioToReceiver(); - ((AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE)).setMode(AudioManager.MODE_NORMAL); + ((AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE)) + .setMode(AudioManager.MODE_NORMAL); Log.i("Set audio mode on 'Normal'"); - return 1;//status; + return 1; // status; } public boolean getEchoTesterStatus() { return echoTesterIsRunning; } - private boolean isRinging; - private void requestAudioFocus(int stream) { if (!mAudioFocused) { - int res = mAudioManager.requestAudioFocus(null, stream, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE); - Log.d("Audio focus requested: " + (res == AudioManager.AUDIOFOCUS_REQUEST_GRANTED ? "Granted" : "Denied")); + int res = + mAudioManager.requestAudioFocus( + null, stream, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE); + Log.d( + "Audio focus requested: " + + (res == AudioManager.AUDIOFOCUS_REQUEST_GRANTED + ? "Granted" + : "Denied")); if (res == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) mAudioFocused = true; } } @@ -1371,12 +1540,14 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou routeAudioToSpeaker(); // Need to be able to ear the ringtone during the early media } - //if (Hacks.needGalaxySAudioHack()) + // if (Hacks.needGalaxySAudioHack()) mAudioManager.setMode(MODE_RINGTONE); try { - if ((mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE || mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL) - && mVibrator != null && LinphonePreferences.instance().isIncomingCallVibrationEnabled()) { + if ((mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE + || mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL) + && mVibrator != null + && LinphonePreferences.instance().isIncomingCallVibrationEnabled()) { long[] patern = {0, 1000, 1000}; mVibrator.vibrate(patern, 1); } @@ -1385,7 +1556,9 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou mRingerPlayer = new MediaPlayer(); mRingerPlayer.setAudioStreamType(STREAM_RING); - String ringtone = LinphonePreferences.instance().getRingtone(Settings.System.DEFAULT_RINGTONE_URI.toString()); + String ringtone = + LinphonePreferences.instance() + .getRingtone(Settings.System.DEFAULT_RINGTONE_URI.toString()); try { if (ringtone.startsWith("content://")) { mRingerPlayer.setDataSource(mServiceContext, Uri.parse(ringtone)); @@ -1420,8 +1593,7 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou mVibrator.cancel(); } - if (Hacks.needGalaxySAudioHack()) - mAudioManager.setMode(AudioManager.MODE_NORMAL); + if (Hacks.needGalaxySAudioHack()) mAudioManager.setMode(AudioManager.MODE_NORMAL); isRinging = false; // You may need to call galaxys audio hack after this method @@ -1438,37 +1610,15 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou public boolean hasLinphoneAccount() { for (ProxyConfig proxyConfig : mLc.getProxyConfigList()) { - if (getString(R.string.default_domain).equals(proxyConfig.getIdentityAddress().getDomain())) { + if (getString(R.string.default_domain) + .equals(proxyConfig.getIdentityAddress().getDomain())) { return true; } } return false; } - public static String extractADisplayName(Resources r, Address address) { - if (address == null) return r.getString(R.string.unknown_incoming_call_name); - - final String displayName = address.getDisplayName(); - if (displayName != null) { - return displayName; - } else if (address.getUsername() != null) { - return address.getUsername(); - } else { - String rms = address.toString(); - if (rms != null && rms.length() > 1) - return rms; - - return r.getString(R.string.unknown_incoming_call_name); - } - } - - public static boolean reinviteWithVideo() { - return CallManager.getInstance().reinviteWithVideo(); - } - - /** - * @return false if already in video call. - */ + /** @return false if already in video call. */ public boolean addVideo() { Call call = mLc.getCurrentCall(); enableCamera(call, true); @@ -1480,11 +1630,14 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou CallParams params = LinphoneManager.getLc().createCallParams(call); - boolean isLowBandwidthConnection = !LinphoneUtils.isHighBandwidthConnection(LinphoneService.instance().getApplicationContext()); + boolean isLowBandwidthConnection = + !LinphoneUtils.isHighBandwidthConnection( + LinphoneService.instance().getApplicationContext()); if (params != null) { params.enableLowBandwidth(isLowBandwidthConnection); - params.setRecordFile(FileUtils.getCallRecordingFilename(getContext(), call.getRemoteAddress())); + params.setRecordFile( + FileUtils.getCallRecordingFilename(getContext(), call.getRemoteAddress())); } else { Log.e("Could not create call params for call"); return false; @@ -1509,21 +1662,12 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou mLc.setPlaybackGainDb((nextVolume - maxVolume) * dbStep); } else - // starting from ICS, volume must be adjusted by the application, at least for STREAM_VOICE_CALL volume stream - mAudioManager.adjustStreamVolume(LINPHONE_VOLUME_STREAM, i < 0 ? AudioManager.ADJUST_LOWER : AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI); - } - - public static synchronized Core getLcIfManagerNotDestroyedOrNull() { - if (sExited || instance == null) { - // Can occur if the UI thread play a posted event but in the meantime the LinphoneManager was destroyed - // Ex: stop call and quickly terminate application. - return null; - } - return getLc(); - } - - public static final boolean isInstanciated() { - return instance != null; + // 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() { @@ -1531,7 +1675,10 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou long now = new Timestamp(new Date().getTime()).getTime(); if (accountCreator != null && LinphonePreferences.instance().getLinkPopupTime() == null || Long.parseLong(LinphonePreferences.instance().getLinkPopupTime()) < now) { - accountCreator.setUsername(LinphonePreferences.instance().getAccountUsername(LinphonePreferences.instance().getDefaultAccountIndex())); + accountCreator.setUsername( + LinphonePreferences.instance() + .getAccountUsername( + LinphonePreferences.instance().getDefaultAccountIndex())); accountCreator.isAccountExist(); } } else { @@ -1543,14 +1690,28 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou if (!LinphonePreferences.instance().isLinkPopupEnabled()) return; long now = new Timestamp(new Date().getTime()).getTime(); - if (LinphonePreferences.instance().getLinkPopupTime() != null && Long.parseLong(LinphonePreferences.instance().getLinkPopupTime()) >= now) return; + if (LinphonePreferences.instance().getLinkPopupTime() != null + && Long.parseLong(LinphonePreferences.instance().getLinkPopupTime()) >= now) return; - long future = new Timestamp(LinphoneActivity.instance().getResources().getInteger(R.integer.popup_time_interval)).getTime(); + long future = + new Timestamp( + LinphoneActivity.instance() + .getResources() + .getInteger(R.integer.popup_time_interval)) + .getTime(); long newDate = now + future; LinphonePreferences.instance().setLinkPopupTime(String.valueOf(newDate)); - final Dialog dialog = LinphoneActivity.instance().displayDialog(String.format(getString(R.string.link_account_popup), LinphoneManager.getLc().getDefaultProxyConfig().getIdentityAddress().asStringUriOnly())); + final Dialog dialog = + LinphoneActivity.instance() + .displayDialog( + String.format( + getString(R.string.link_account_popup), + LinphoneManager.getLc() + .getDefaultProxyConfig() + .getIdentityAddress() + .asStringUriOnly())); Button delete = dialog.findViewById(R.id.dialog_delete_button); delete.setVisibility(View.GONE); Button ok = dialog.findViewById(R.id.dialog_ok_button); @@ -1561,34 +1722,38 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou dialog.findViewById(R.id.dialog_do_not_ask_again_layout).setVisibility(View.VISIBLE); final CheckBox doNotAskAgain = dialog.findViewById(R.id.doNotAskAgain); - dialog.findViewById(R.id.doNotAskAgainLabel).setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - doNotAskAgain.setChecked(!doNotAskAgain.isChecked()); - } - }); + dialog.findViewById(R.id.doNotAskAgainLabel) + .setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View v) { + doNotAskAgain.setChecked(!doNotAskAgain.isChecked()); + } + }); - ok.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - Intent assistant = new Intent(); - assistant.setClass(LinphoneActivity.instance(), AssistantActivity.class); - assistant.putExtra("LinkPhoneNumber", true); - assistant.putExtra("LinkPhoneNumberAsk", true); - mServiceContext.startActivity(assistant); - dialog.dismiss(); - } - }); + ok.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View view) { + Intent assistant = new Intent(); + assistant.setClass(LinphoneActivity.instance(), AssistantActivity.class); + assistant.putExtra("LinkPhoneNumber", true); + assistant.putExtra("LinkPhoneNumberAsk", true); + mServiceContext.startActivity(assistant); + dialog.dismiss(); + } + }); - cancel.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - if (doNotAskAgain.isChecked()) { - LinphonePreferences.instance().enableLinkPopup(false); - } - dialog.dismiss(); - } - }); + cancel.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View view) { + if (doNotAskAgain.isChecked()) { + LinphonePreferences.instance().enableLinkPopup(false); + } + dialog.dismiss(); + } + }); dialog.show(); } @@ -1609,43 +1774,47 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou } @Override - public void onTransferStateChanged(Core lc, Call call, - State new_call_state) { - - } + public void onTransferStateChanged(Core lc, Call call, State new_call_state) {} @Override public void onInfoReceived(Core lc, Call call, InfoMessage info) { Log.d("Info message received from " + call.getRemoteAddress().asString()); Content ct = info.getContent(); if (ct != null) { - Log.d("Info received with body with mime type " + ct.getType() + "/" + ct.getSubtype() + " and data [" + ct.getStringBuffer() + "]"); + Log.d( + "Info received with body with mime type " + + ct.getType() + + "/" + + ct.getSubtype() + + " and data [" + + ct.getStringBuffer() + + "]"); } } @Override - public void onSubscriptionStateChanged(Core lc, Event ev, - SubscriptionState state) { + public void onSubscriptionStateChanged(Core lc, Event ev, SubscriptionState state) { Log.d("Subscription state changed to " + state + " event name is " + ev.getName()); } @Override - public void onCallLogUpdated(Core lc, CallLog newcl) { - - } + public void onCallLogUpdated(Core lc, CallLog newcl) {} @Override - public void onNotifyReceived(Core lc, Event ev, - String eventName, Content content) { + public void onNotifyReceived(Core lc, Event ev, String eventName, Content content) { Log.d("Notify received for event " + eventName); if (content != null) - Log.d("with content " + content.getType() + "/" + content.getSubtype() + " data:" + content.getStringBuffer()); + Log.d( + "with content " + + content.getType() + + "/" + + content.getSubtype() + + " data:" + + content.getStringBuffer()); } @Override - public void onSubscribeReceived(Core lc, Event lev, String subscribeEvent, Content body) { - - } + public void onSubscribeReceived(Core lc, Event lev, String subscribeEvent, Content body) {} @Override public void onPublishStateChanged(Core lc, Event ev, PublishState state) { @@ -1658,13 +1827,10 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou } @Override - public void onMessageReceivedUnableDecrypt(Core lc, ChatRoom room, ChatMessage message) { - - } + public void onMessageReceivedUnableDecrypt(Core lc, ChatRoom room, ChatMessage message) {} @Override - public void onConfiguringStatus(Core lc, - ConfiguringState state, String message) { + public void onConfiguringStatus(Core lc, ConfiguringState state, String message) { Log.d("Remote provisioning status = " + state.toString() + " (" + message + ")"); LinphonePreferences prefs = LinphonePreferences.instance(); @@ -1679,50 +1845,60 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou } @Override - public void onCallCreated(Core lc, Call call) { - - } + public void onCallCreated(Core lc, Call call) {} @Override public void onLogCollectionUploadProgressIndication(Core linphoneCore, int offset, int total) { if (total > 0) - Log.d("Log upload progress: currently uploaded = " + offset + " , total = " + total + ", % = " + String.valueOf((offset * 100) / total)); + Log.d( + "Log upload progress: currently uploaded = " + + offset + + " , total = " + + total + + ", % = " + + String.valueOf((offset * 100) / total)); } @Override - public void onVersionUpdateCheckResultReceived(Core lc, VersionUpdateCheckResult result, String version, String url) { + public void onVersionUpdateCheckResultReceived( + Core lc, VersionUpdateCheckResult result, String version, String url) { if (result == VersionUpdateCheckResult.NewVersionAvailable) { final String urlToUse = url; final String versionAv = version; - mHandler.postDelayed(new Runnable() { - @Override - public void run() { - AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); - builder.setMessage(getString(R.string.update_available) + ": " + versionAv); - builder.setCancelable(false); - builder.setNeutralButton(getString(R.string.ok), new DialogInterface.OnClickListener() { + mHandler.postDelayed( + new Runnable() { @Override - public void onClick(DialogInterface dialogInterface, int i) { - if (urlToUse != null) { - Intent urlIntent = new Intent(Intent.ACTION_VIEW); - urlIntent.setData(Uri.parse(urlToUse)); - getContext().startActivity(urlIntent); - } + public void run() { + AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); + builder.setMessage( + getString(R.string.update_available) + ": " + versionAv); + builder.setCancelable(false); + builder.setNeutralButton( + getString(R.string.ok), + new DialogInterface.OnClickListener() { + @Override + public void onClick( + DialogInterface dialogInterface, int i) { + if (urlToUse != null) { + Intent urlIntent = new Intent(Intent.ACTION_VIEW); + urlIntent.setData(Uri.parse(urlToUse)); + getContext().startActivity(urlIntent); + } + } + }); + builder.show(); } - }); - builder.show(); - } - }, 1000); + }, + 1000); } } @Override - public void onEcCalibrationAudioUninit(Core lc) { - - } + public void onEcCalibrationAudioUninit(Core lc) {} @Override - public void onLogCollectionUploadStateChanged(Core linphoneCore, LogCollectionUploadState state, String info) { + public void onLogCollectionUploadStateChanged( + Core linphoneCore, LogCollectionUploadState state, String info) { Log.d("Log upload state: " + state.toString() + ", info = " + info); } @@ -1739,81 +1915,75 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou } @Override - public void onReferReceived(Core lc, String refer_to) { - - } + public void onReferReceived(Core lc, String refer_to) {} @Override - public void onNetworkReachable(Core lc, boolean enable) { - - } + public void onNetworkReachable(Core lc, boolean enable) {} @Override - public void onAuthenticationRequested(Core lc, - AuthInfo authInfo, AuthMethod method) { + public void onAuthenticationRequested(Core lc, AuthInfo authInfo, AuthMethod method) { // TODO Auto-generated method stub } @Override - public void onNotifyPresenceReceivedForUriOrTel(Core lc, Friend lf, String uri_or_tel, PresenceModel presence_model) { - - } + public void onNotifyPresenceReceivedForUriOrTel( + Core lc, Friend lf, String uri_or_tel, PresenceModel presence_model) {} @Override - public void onBuddyInfoUpdated(Core lc, Friend lf) { - - } + public void onBuddyInfoUpdated(Core lc, Friend lf) {} @Override - public void onIsAccountExist(AccountCreator accountCreator, AccountCreator.Status status, String resp) { + public void onIsAccountExist( + AccountCreator accountCreator, AccountCreator.Status status, String resp) { if (status.equals(AccountCreator.Status.AccountExist)) { accountCreator.isAccountLinked(); } } @Override - public void onCreateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - } + public void onCreateAccount( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onActivateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - } + public void onActivateAccount( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onLinkAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { + public void onLinkAccount( + AccountCreator accountCreator, AccountCreator.Status status, String resp) { if (status.equals(AccountCreator.Status.AccountNotLinked)) { askLinkWithPhoneNumber(); } } @Override - public void onActivateAlias(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - } + public void onActivateAlias( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onIsAccountActivated(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - } + public void onIsAccountActivated( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onRecoverAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - } + public void onRecoverAccount( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onIsAccountLinked(AccountCreator accountCreator, AccountCreator.Status status, String resp) { + public void onIsAccountLinked( + AccountCreator accountCreator, AccountCreator.Status status, String resp) { if (status.equals(AccountCreator.Status.AccountNotLinked)) { askLinkWithPhoneNumber(); } } @Override - public void onIsAliasUsed(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - } + public void onIsAliasUsed( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onUpdateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - - } + public void onUpdateAccount( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} private void updateMissedChatCount() { for (ChatRoom cr : LinphoneManager.getLc().getChatRooms()) { @@ -1833,7 +2003,6 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou mUnreadChatsPerRoom.put(key, value); } - public void updateUnreadCountForChatRoom(ChatRoom cr, Integer value) { String key = cr.getPeerAddress().asStringUriOnly(); updateUnreadCountForChatRoom(key, value); @@ -1848,6 +2017,15 @@ public class LinphoneManager implements CoreListener, SensorEventListener, Accou } } - public void onQrcodeFound(Core lc, String something) { + public void onQrcodeFound(Core lc, String something) {} + + public interface AddressType { + CharSequence getText(); + + void setText(CharSequence s); + + String getDisplayedName(); + + void setDisplayedName(String s); } } diff --git a/app/src/main/java/org/linphone/LinphoneService.java b/app/src/main/java/org/linphone/LinphoneService.java index 6b1bcbae7..e2a911172 100644 --- a/app/src/main/java/org/linphone/LinphoneService.java +++ b/app/src/main/java/org/linphone/LinphoneService.java @@ -35,7 +35,7 @@ import android.os.IBinder; import android.os.SystemClock; import android.provider.ContactsContract; import android.view.WindowManager; - +import java.util.ArrayList; import org.linphone.contacts.ContactsManager; import org.linphone.core.Call; import org.linphone.core.Call.State; @@ -51,19 +51,19 @@ import org.linphone.notifications.NotificationsManager; import org.linphone.receivers.BluetoothManager; import org.linphone.receivers.KeepAliveReceiver; import org.linphone.settings.LinphonePreferences; -import org.linphone.views.LinphoneOverlay; import org.linphone.utils.LinphoneUtils; - -import java.util.ArrayList; +import org.linphone.views.LinphoneOverlay; /** - * Linphone service, reacting to Incoming calls, ...
    - *

    - * Roles include:

      - *
    • Initializing LinphoneManager
    • - *
    • Starting C libLinphone through LinphoneManager
    • - *
    • Reacting to LinphoneManager state changes
    • - *
    • Delegating GUI state change actions to GUI listener
    • + * Linphone service, reacting to Incoming calls, ...
      + * + *

      Roles include: + * + *

        + *
      • Initializing LinphoneManager + *
      • Starting C libLinphone through LinphoneManager + *
      • Reacting to LinphoneManager state changes + *
      • Delegating GUI state change actions to GUI listener */ public final class LinphoneService extends Service { /* Listener needs to be implemented in the Service as it calls @@ -72,6 +72,15 @@ public final class LinphoneService extends Service { public static final String START_LINPHONE_LOGS = " ==== Phone information dump ===="; private static LinphoneService instance; + public Handler mHandler = new Handler(); + private boolean mTestDelayElapsed = true; + private CoreListenerStub mListener; + private WindowManager mWindowManager; + private LinphoneOverlay mOverlay; + private Application.ActivityLifecycleCallbacks mActivityCallbacks; + private NotificationsManager mNotificationManager; + private String incomingReceivedActivityName; + private Class incomingReceivedActivity = LinphoneActivity.class; public static boolean isReady() { return instance != null && instance.mTestDelayElapsed; @@ -83,17 +92,6 @@ public final class LinphoneService extends Service { throw new RuntimeException("LinphoneService not instantiated yet"); } - public Handler mHandler = new Handler(); - - private boolean mTestDelayElapsed = true; - private CoreListenerStub mListener; - private WindowManager mWindowManager; - private LinphoneOverlay mOverlay; - private Application.ActivityLifecycleCallbacks mActivityCallbacks; - private NotificationsManager mNotificationManager; - private String incomingReceivedActivityName; - private Class incomingReceivedActivity = LinphoneActivity.class; - public NotificationsManager getNotificationManager() { return mNotificationManager; } @@ -110,7 +108,8 @@ public final class LinphoneService extends Service { protected void onBackgroundMode() { Log.i("App has entered background mode"); - if (LinphonePreferences.instance() != null && LinphonePreferences.instance().isFriendlistsubscriptionEnabled()) { + if (LinphonePreferences.instance() != null + && LinphonePreferences.instance().isFriendlistsubscriptionEnabled()) { if (LinphoneManager.isInstanciated()) LinphoneManager.getInstance().subscribeFriendList(false); } @@ -121,7 +120,8 @@ public final class LinphoneService extends Service { protected void onForegroundMode() { Log.i("App has left background mode"); - if (LinphonePreferences.instance() != null && LinphonePreferences.instance().isFriendlistsubscriptionEnabled()) { + if (LinphonePreferences.instance() != null + && LinphonePreferences.instance().isFriendlistsubscriptionEnabled()) { if (LinphoneManager.isInstanciated()) LinphoneManager.getInstance().subscribeFriendList(true); } @@ -132,7 +132,8 @@ public final class LinphoneService extends Service { private void setupActivityMonitor() { if (mActivityCallbacks != null) return; - getApplication().registerActivityLifecycleCallbacks(mActivityCallbacks = new ActivityMonitor()); + getApplication() + .registerActivityLifecycleCallbacks(mActivityCallbacks = new ActivityMonitor()); } @Override @@ -152,69 +153,101 @@ public final class LinphoneService extends Service { instance = this; // instance is ready once linphone manager has been created mNotificationManager = new NotificationsManager(this); - LinphoneManager.getLc().addListener(mListener = new CoreListenerStub() { - @Override - public void onCallStateChanged(Core lc, Call call, Call.State state, String message) { - if (instance == null) { - Log.i("Service not ready, discarding call state change to ", state.toString()); - return; - } + LinphoneManager.getLc() + .addListener( + mListener = + new CoreListenerStub() { + @Override + public void onCallStateChanged( + Core lc, Call call, Call.State state, String message) { + if (instance == null) { + Log.i( + "Service not ready, discarding call state change to ", + state.toString()); + return; + } - if (getResources().getBoolean(R.bool.enable_call_notification)) { - mNotificationManager.displayCallNotification(call); - } + if (getResources() + .getBoolean(R.bool.enable_call_notification)) { + mNotificationManager.displayCallNotification(call); + } - if (state == Call.State.IncomingReceived) { - if (!LinphoneManager.getInstance().getCallGsmON()) - onIncomingReceived(); - } + if (state == Call.State.IncomingReceived) { + if (!LinphoneManager.getInstance().getCallGsmON()) + onIncomingReceived(); + } - if (state == State.End || state == State.Released || state == State.Error) { - destroyOverlay(); - } + if (state == State.End + || state == State.Released + || state == State.Error) { + destroyOverlay(); + } - if (state == State.Released && call.getCallLog().getStatus() == Call.Status.Missed) { - mNotificationManager.displayMissedCallNotification(call); - } - } + if (state == State.Released + && call.getCallLog().getStatus() + == Call.Status.Missed) { + mNotificationManager.displayMissedCallNotification( + call); + } + } - @Override - public void onGlobalStateChanged(Core lc, GlobalState state, String message) { - //TODO global state if ON - } + @Override + public void onGlobalStateChanged( + Core lc, GlobalState state, String message) { + // TODO global state if ON + } - @Override - public void onRegistrationStateChanged(Core lc, ProxyConfig cfg, RegistrationState state, String smessage) { - //TODO registration status - } - }); + @Override + public void onRegistrationStateChanged( + Core lc, + ProxyConfig cfg, + RegistrationState state, + String smessage) { + // TODO registration status + } + }); - if (Version.sdkAboveOrEqual(Version.API26_O_80) && intent.getBooleanExtra("ForceStartForeground", false)) { + if (Version.sdkAboveOrEqual(Version.API26_O_80) + && intent.getBooleanExtra("ForceStartForeground", false)) { mNotificationManager.startForeground(); } if (!Version.sdkAboveOrEqual(Version.API26_O_80) - || (ContactsManager.getInstance() != null && ContactsManager.getInstance().hasContactsAccess())) { - getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, ContactsManager.getInstance()); + || (ContactsManager.getInstance() != null + && ContactsManager.getInstance().hasContactsAccess())) { + getContentResolver() + .registerContentObserver( + ContactsContract.Contacts.CONTENT_URI, + true, + ContactsManager.getInstance()); } if (!mTestDelayElapsed) { // Only used when testing. Simulates a 5 seconds delay for launching service - mHandler.postDelayed(new Runnable() { - @Override - public void run() { - mTestDelayElapsed = true; - } - }, 5000); + mHandler.postDelayed( + new Runnable() { + @Override + public void run() { + mTestDelayElapsed = true; + } + }, + 5000); } - //make sure the application will at least wakes up every 10 mn - if (LinphonePreferences.instance().isBackgroundModeEnabled() && - (!LinphonePreferences.instance().isPushNotificationEnabled() || !LinphoneManager.getInstance().hasLinphoneAccount())) { + // make sure the application will at least wakes up every 10 mn + if (LinphonePreferences.instance().isBackgroundModeEnabled() + && (!LinphonePreferences.instance().isPushNotificationEnabled() + || !LinphoneManager.getInstance().hasLinphoneAccount())) { Intent keepAliveIntent = new Intent(this, KeepAliveReceiver.class); - PendingIntent keepAlivePendingIntent = PendingIntent.getBroadcast(this, 0, keepAliveIntent, PendingIntent.FLAG_ONE_SHOT); - AlarmManager alarmManager = ((AlarmManager) this.getSystemService(Context.ALARM_SERVICE)); - alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 600000, keepAlivePendingIntent); + PendingIntent keepAlivePendingIntent = + PendingIntent.getBroadcast( + this, 0, keepAliveIntent, PendingIntent.FLAG_ONE_SHOT); + AlarmManager alarmManager = + ((AlarmManager) this.getSystemService(Context.ALARM_SERVICE)); + alarmManager.setExact( + AlarmManager.ELAPSED_REALTIME_WAKEUP, + SystemClock.elapsedRealtime() + 600000, + keepAlivePendingIntent); } BluetoothManager.getInstance().initBluetooth(); @@ -240,9 +273,11 @@ public final class LinphoneService extends Service { dumpDeviceInformation(); dumpInstalledLinphoneInformation(); - incomingReceivedActivityName = LinphonePreferences.instance().getActivityToLaunchOnIncomingReceived(); + incomingReceivedActivityName = + LinphonePreferences.instance().getActivityToLaunchOnIncomingReceived(); try { - incomingReceivedActivity = (Class) Class.forName(incomingReceivedActivityName); + incomingReceivedActivity = + (Class) Class.forName(incomingReceivedActivityName); } catch (ClassNotFoundException e) { Log.e(e); } @@ -356,17 +391,19 @@ public final class LinphoneService extends Service { try { incomingReceivedActivity = (Class) Class.forName(activityName); incomingReceivedActivityName = activityName; - LinphonePreferences.instance().setActivityToLaunchOnIncomingReceived(incomingReceivedActivityName); + LinphonePreferences.instance() + .setActivityToLaunchOnIncomingReceived(incomingReceivedActivityName); } catch (ClassNotFoundException e) { Log.e(e); } } protected void onIncomingReceived() { - //wakeup linphone - startActivity(new Intent() - .setClass(this, incomingReceivedActivity) - .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); + // wakeup linphone + startActivity( + new Intent() + .setClass(this, incomingReceivedActivity) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); } /*Believe me or not, but knowing the application visibility state on Android is a nightmare. @@ -376,34 +413,12 @@ public final class LinphoneService extends Service { private ArrayList activities = new ArrayList<>(); private boolean mActive = false; private int mRunningActivities = 0; - - class InactivityChecker implements Runnable { - private boolean isCanceled; - - public void cancel() { - isCanceled = true; - } - - @Override - public void run() { - synchronized (LinphoneService.this) { - if (!isCanceled) { - if (ActivityMonitor.this.mRunningActivities == 0 && mActive) { - mActive = false; - LinphoneService.this.onBackgroundMode(); - } - } - } - } - } - private InactivityChecker mLastChecker; @Override public synchronized void onActivityCreated(Activity activity, Bundle savedInstanceState) { Log.i("Activity created:" + activity); - if (!activities.contains(activity)) - activities.add(activity); + if (!activities.contains(activity)) activities.add(activity); } @Override @@ -419,7 +434,6 @@ public final class LinphoneService extends Service { Log.i("runningActivities=" + mRunningActivities); checkActivity(); } - } @Override @@ -430,7 +444,6 @@ public final class LinphoneService extends Service { Log.i("runningActivities=" + mRunningActivities); checkActivity(); } - } @Override @@ -439,9 +452,7 @@ public final class LinphoneService extends Service { } @Override - public void onActivitySaveInstanceState(Activity activity, Bundle outState) { - - } + public void onActivitySaveInstanceState(Activity activity, Bundle outState) {} @Override public synchronized void onActivityDestroyed(Activity activity) { @@ -471,6 +482,25 @@ public final class LinphoneService extends Service { } } } + + class InactivityChecker implements Runnable { + private boolean isCanceled; + + public void cancel() { + isCanceled = true; + } + + @Override + public void run() { + synchronized (LinphoneService.this) { + if (!isCanceled) { + if (ActivityMonitor.this.mRunningActivities == 0 && mActive) { + mActive = false; + LinphoneService.this.onBackgroundMode(); + } + } + } + } + } } } - diff --git a/app/src/main/java/org/linphone/assistant/AssistantActivity.java b/app/src/main/java/org/linphone/assistant/AssistantActivity.java index 026fb1bbb..e70bbe92e 100644 --- a/app/src/main/java/org/linphone/assistant/AssistantActivity.java +++ b/app/src/main/java/org/linphone/assistant/AssistantActivity.java @@ -36,8 +36,6 @@ import android.content.pm.PackageManager; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; -import androidx.core.app.ActivityCompat; -import androidx.core.content.ContextCompat; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; @@ -51,15 +49,16 @@ import android.widget.Filterable; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; - -import org.linphone.LinphoneManager; -import org.linphone.settings.LinphonePreferences; -import org.linphone.settings.LinphonePreferences.AccountBuilder; -import org.linphone.LinphoneService; -import org.linphone.utils.LinphoneUtils; -import org.linphone.R; +import androidx.core.app.ActivityCompat; +import androidx.core.content.ContextCompat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import org.linphone.LinphoneActivity; import org.linphone.LinphoneLauncherActivity; +import org.linphone.LinphoneManager; +import org.linphone.LinphoneService; +import org.linphone.R; import org.linphone.core.AccountCreator; import org.linphone.core.AccountCreatorListener; import org.linphone.core.Address; @@ -77,13 +76,19 @@ import org.linphone.core.tools.OpenH264DownloadHelper; import org.linphone.fragments.StatusFragment; import org.linphone.mediastream.Log; import org.linphone.mediastream.Version; +import org.linphone.settings.LinphonePreferences; +import org.linphone.settings.LinphonePreferences.AccountBuilder; +import org.linphone.utils.LinphoneUtils; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -public class AssistantActivity extends Activity implements OnClickListener, ActivityCompat.OnRequestPermissionsResultCallback, AccountCreatorListener { +public class AssistantActivity extends Activity + implements OnClickListener, + ActivityCompat.OnRequestPermissionsResultCallback, + AccountCreatorListener { + private static final int PERMISSIONS_REQUEST_RECORD_AUDIO = 201; private static AssistantActivity instance; + public DialPlan country; + public String phone_number; + public String email; private ImageView back, cancel; private AssistantFragmentsEnum currentFragment; private AssistantFragmentsEnum lastFragment; @@ -98,13 +103,12 @@ public class AssistantActivity extends Activity implements OnClickListener, Acti private Dialog dialog; private boolean remoteProvisioningInProgress; private boolean echoCancellerAlreadyDone; - private static final int PERMISSIONS_REQUEST_RECORD_AUDIO = 201; private AccountCreator mAccountCreator; private CountryListAdapter countryListAdapter; - public DialPlan country; - public String phone_number; - public String email; + public static AssistantActivity instance() { + return instance; + } protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -118,20 +122,29 @@ public class AssistantActivity extends Activity implements OnClickListener, Acti if (getIntent().getBooleanExtra("LinkPhoneNumber", false)) { isLink = true; - if (getIntent().getBooleanExtra("FromPref", false)) - fromPref = true; + if (getIntent().getBooleanExtra("FromPref", false)) fromPref = true; displayCreateAccount(); } else { - firstFragment = getResources().getBoolean(R.bool.assistant_use_linphone_login_as_first_fragment) ? AssistantFragmentsEnum.LINPHONE_LOGIN : AssistantFragmentsEnum.WELCOME; + firstFragment = + getResources().getBoolean(R.bool.assistant_use_linphone_login_as_first_fragment) + ? AssistantFragmentsEnum.LINPHONE_LOGIN + : AssistantFragmentsEnum.WELCOME; if (firstFragment == AssistantFragmentsEnum.WELCOME) { - firstFragment = getResources().getBoolean(R.bool.assistant_use_create_linphone_account_as_first_fragment) ? AssistantFragmentsEnum.CREATE_ACCOUNT : AssistantFragmentsEnum.WELCOME; + firstFragment = + getResources() + .getBoolean( + R.bool.assistant_use_create_linphone_account_as_first_fragment) + ? AssistantFragmentsEnum.CREATE_ACCOUNT + : AssistantFragmentsEnum.WELCOME; } if (findViewById(R.id.fragment_container) != null) { if (savedInstanceState == null) { display(firstFragment); } else { - currentFragment = (AssistantFragmentsEnum) savedInstanceState.getSerializable("CurrentFragment"); + currentFragment = + (AssistantFragmentsEnum) + savedInstanceState.getSerializable("CurrentFragment"); } } } @@ -144,56 +157,70 @@ public class AssistantActivity extends Activity implements OnClickListener, Acti status.enableSideMenu(false); if (LinphoneManager.getLcIfManagerNotDestroyedOrNull() != null) { - mAccountCreator = LinphoneManager.getLc().createAccountCreator(LinphonePreferences.instance().getXmlrpcUrl()); + mAccountCreator = + LinphoneManager.getLc() + .createAccountCreator(LinphonePreferences.instance().getXmlrpcUrl()); mAccountCreator.setListener(this); } countryListAdapter = new CountryListAdapter(getApplicationContext()); - mListener = new CoreListenerStub() { + mListener = + new CoreListenerStub() { - @Override - public void onConfiguringStatus(Core lc, final ConfiguringState state, String message) { - if (progress != null) progress.dismiss(); - if (state == ConfiguringState.Successful) { - goToLinphoneActivity(); - } else if (state == ConfiguringState.Failed) { - Toast.makeText(AssistantActivity.instance(), getString(R.string.remote_provisioning_failure), Toast.LENGTH_LONG).show(); - } - } - - @Override - public void onRegistrationStateChanged(Core lc, ProxyConfig cfg, RegistrationState state, String smessage) { - if (remoteProvisioningInProgress) { - if (progress != null) progress.dismiss(); - if (state == RegistrationState.Ok) { - remoteProvisioningInProgress = false; - success(); - } - } else if (accountCreated && !newAccount) { - if (address != null && address.asString().equals(cfg.getIdentityAddress().asString())) { - if (state == RegistrationState.Ok) { - if (progress != null) progress.dismiss(); - if (getResources().getBoolean(R.bool.use_phone_number_validation) - && cfg.getDomain().equals(getString(R.string.default_domain)) - && LinphoneManager.getLc().getDefaultProxyConfig() != null) { - loadAccountCreator(cfg).isAccountExist(); - } else { - success(); - } - } else if (state == RegistrationState.Failed) { - if (progress != null) progress.dismiss(); - if (dialog == null || !dialog.isShowing()) { - dialog = createErrorDialog(cfg, smessage); - dialog.setCancelable(false); - dialog.show(); - } - } else if (!(state == RegistrationState.Progress)) { - if (progress != null) progress.dismiss(); + @Override + public void onConfiguringStatus( + Core lc, final ConfiguringState state, String message) { + if (progress != null) progress.dismiss(); + if (state == ConfiguringState.Successful) { + goToLinphoneActivity(); + } else if (state == ConfiguringState.Failed) { + Toast.makeText( + AssistantActivity.instance(), + getString(R.string.remote_provisioning_failure), + Toast.LENGTH_LONG) + .show(); } } - } - } - }; + + @Override + public void onRegistrationStateChanged( + Core lc, ProxyConfig cfg, RegistrationState state, String smessage) { + if (remoteProvisioningInProgress) { + if (progress != null) progress.dismiss(); + if (state == RegistrationState.Ok) { + remoteProvisioningInProgress = false; + success(); + } + } else if (accountCreated && !newAccount) { + if (address != null + && address.asString() + .equals(cfg.getIdentityAddress().asString())) { + if (state == RegistrationState.Ok) { + if (progress != null) progress.dismiss(); + if (getResources() + .getBoolean(R.bool.use_phone_number_validation) + && cfg.getDomain() + .equals(getString(R.string.default_domain)) + && LinphoneManager.getLc().getDefaultProxyConfig() + != null) { + loadAccountCreator(cfg).isAccountExist(); + } else { + success(); + } + } else if (state == RegistrationState.Failed) { + if (progress != null) progress.dismiss(); + if (dialog == null || !dialog.isShowing()) { + dialog = createErrorDialog(cfg, smessage); + dialog.setCancelable(false); + dialog.show(); + } + } else if (!(state == RegistrationState.Progress)) { + if (progress != null) progress.dismiss(); + } + } + } + } + }; instance = this; } @@ -224,10 +251,6 @@ public class AssistantActivity extends Activity implements OnClickListener, Acti super.onSaveInstanceState(outState); } - public static AssistantActivity instance() { - return instance; - } - public void updateStatusFragment(StatusFragment fragment) { status = fragment; } @@ -315,7 +338,8 @@ public class AssistantActivity extends Activity implements OnClickListener, Acti } public void hideKeyboard() { - InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); + InputMethodManager imm = + (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); View view = this.getCurrentFocus(); if (imm != null && view != null) { imm.hideSoftInputFromWindow(view.getWindowToken(), 0); @@ -328,20 +352,34 @@ public class AssistantActivity extends Activity implements OnClickListener, Acti public void checkAndRequestPermission(String permission, int result) { int permissionGranted = getPackageManager().checkPermission(permission, getPackageName()); - Log.i("[Permission] " + permission + " is " + (permissionGranted == PackageManager.PERMISSION_GRANTED ? "granted" : "denied")); + Log.i( + "[Permission] " + + permission + + " is " + + (permissionGranted == PackageManager.PERMISSION_GRANTED + ? "granted" + : "denied")); if (permissionGranted != PackageManager.PERMISSION_GRANTED) { - if (LinphonePreferences.instance().firstTimeAskingForPermission(permission) || ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) { + if (LinphonePreferences.instance().firstTimeAskingForPermission(permission) + || ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) { Log.i("[Permission] Asking for " + permission); - ActivityCompat.requestPermissions(this, new String[]{permission}, result); + ActivityCompat.requestPermissions(this, new String[] {permission}, result); } } } @Override - public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { + public void onRequestPermissionsResult( + int requestCode, String[] permissions, int[] grantResults) { for (int i = 0; i < permissions.length; i++) { - Log.i("[Permission] " + permissions[i] + " is " + (grantResults[i] == PackageManager.PERMISSION_GRANTED ? "granted" : "denied")); + Log.i( + "[Permission] " + + permissions[i] + + " is " + + (grantResults[i] == PackageManager.PERMISSION_GRANTED + ? "granted" + : "denied")); } if (requestCode == PERMISSIONS_REQUEST_RECORD_AUDIO) { @@ -354,8 +392,14 @@ public class AssistantActivity extends Activity implements OnClickListener, Acti } private void launchEchoCancellerCalibration(boolean sendEcCalibrationResult) { - int recordAudio = getPackageManager().checkPermission(Manifest.permission.RECORD_AUDIO, getPackageName()); - Log.i("[Permission] Record audio permission is " + (recordAudio == PackageManager.PERMISSION_GRANTED ? "granted" : "denied")); + int recordAudio = + getPackageManager() + .checkPermission(Manifest.permission.RECORD_AUDIO, getPackageName()); + Log.i( + "[Permission] Record audio permission is " + + (recordAudio == PackageManager.PERMISSION_GRANTED + ? "granted" + : "denied")); if (recordAudio == PackageManager.PERMISSION_GRANTED) { EchoCancellerCalibrationFragment fragment = new EchoCancellerCalibrationFragment(); @@ -385,22 +429,23 @@ public class AssistantActivity extends Activity implements OnClickListener, Acti address = addr; proxyConfig.edit(); - proxyConfig.setIdentityAddress(addr); if (accountCreator.getPhoneNumber() != null && accountCreator.getPhoneNumber().length() > 0) - proxyConfig.setDialPrefix(org.linphone.core.Utils.getPrefixFromE164(accountCreator.getPhoneNumber())); + proxyConfig.setDialPrefix( + org.linphone.core.Utils.getPrefixFromE164(accountCreator.getPhoneNumber())); proxyConfig.done(); - authInfo = Factory.instance().createAuthInfo( - accountCreator.getUsername(), - null, - accountCreator.getPassword(), - accountCreator.getHa1(), - proxyConfig.getRealm(), - proxyConfig.getDomain()); - + authInfo = + Factory.instance() + .createAuthInfo( + accountCreator.getUsername(), + null, + accountCreator.getPassword(), + accountCreator.getHa1(), + proxyConfig.getRealm(), + proxyConfig.getDomain()); lc.addProxyConfig(proxyConfig); @@ -412,9 +457,11 @@ public class AssistantActivity extends Activity implements OnClickListener, Acti LinphonePreferences.instance().setPushNotificationEnabled(true); if (LinphonePreferences.instance() != null) - mPrefs.enabledFriendlistSubscription(getResources().getBoolean(R.bool.use_friendlist_subscription)); + mPrefs.enabledFriendlistSubscription( + getResources().getBoolean(R.bool.use_friendlist_subscription)); - LinphoneManager.getInstance().subscribeFriendList(getResources().getBoolean(R.bool.use_friendlist_subscription)); + LinphoneManager.getInstance() + .subscribeFriendList(getResources().getBoolean(R.bool.use_friendlist_subscription)); if (!newAccount) { displayRegistrationInProgressDialog(); @@ -423,12 +470,22 @@ public class AssistantActivity extends Activity implements OnClickListener, Acti } public void linphoneLogIn(AccountCreator accountCreator) { - LinphoneManager.getLc().getConfig().loadFromXmlFile(LinphoneManager.getInstance().getmDynamicConfigFile()); + LinphoneManager.getLc() + .getConfig() + .loadFromXmlFile(LinphoneManager.getInstance().getmDynamicConfigFile()); configureProxyConfig(accountCreator); } - public void genericLogIn(String username, String userid, String password, String displayname, String prefix, String domain, TransportType transport) { - saveCreatedAccount(username, userid, password, displayname, null, prefix, domain, transport); + public void genericLogIn( + String username, + String userid, + String password, + String displayname, + String prefix, + String domain, + TransportType transport) { + saveCreatedAccount( + username, userid, password, displayname, null, prefix, domain, transport); } private void display(AssistantFragmentsEnum fragment) { @@ -503,15 +560,17 @@ public class AssistantActivity extends Activity implements OnClickListener, Acti private void launchDownloadCodec() { if (OpenH264DownloadHelper.isOpenH264DownloadEnabled()) { - OpenH264DownloadHelper downloadHelper = Factory.instance().createOpenH264DownloadHelper(this); - if (Version.getCpuAbis().contains("armeabi-v7a") && !Version.getCpuAbis().contains("x86") && !downloadHelper.isCodecFound()) { + OpenH264DownloadHelper downloadHelper = + Factory.instance().createOpenH264DownloadHelper(this); + if (Version.getCpuAbis().contains("armeabi-v7a") + && !Version.getCpuAbis().contains("x86") + && !downloadHelper.isCodecFound()) { CodecDownloaderFragment codecFragment = new CodecDownloaderFragment(); changeFragment(codecFragment); currentFragment = AssistantFragmentsEnum.DOWNLOAD_CODEC; back.setVisibility(View.VISIBLE); cancel.setEnabled(false); - } else - goToLinphoneActivity(); + } else goToLinphoneActivity(); } else { goToLinphoneActivity(); } @@ -523,11 +582,20 @@ public class AssistantActivity extends Activity implements OnClickListener, Acti public String getPhoneWithCountry() { if (country == null || phone_number == null) return ""; - String phoneNumberWithCountry = country.getCountryCallingCode() + phone_number.replace("\\D", ""); + String phoneNumberWithCountry = + country.getCountryCallingCode() + phone_number.replace("\\D", ""); return phoneNumberWithCountry; } - public void saveCreatedAccount(String username, String userid, String password, String displayname, String ha1, String prefix, String domain, TransportType transport) { + public void saveCreatedAccount( + String username, + String userid, + String password, + String displayname, + String ha1, + String prefix, + String domain, + TransportType transport) { username = LinphoneUtils.getDisplayableUsernameFromAddress(username); domain = LinphoneUtils.getDisplayableUsernameFromAddress(domain); @@ -535,13 +603,14 @@ public class AssistantActivity extends Activity implements OnClickListener, Acti String identity = "sip:" + username + "@" + domain; address = Factory.instance().createAddress(identity); - AccountBuilder builder = new AccountBuilder(LinphoneManager.getLc()) - .setUsername(username) - .setDomain(domain) - .setHa1(ha1) - .setUserid(userid) - .setDisplayName(displayname) - .setPassword(password); + AccountBuilder builder = + new AccountBuilder(LinphoneManager.getLc()) + .setUsername(username) + .setDomain(domain) + .setHa1(ha1) + .setUserid(userid) + .setDisplayName(displayname) + .setPassword(password); if (prefix != null) { builder.setPrefix(prefix); @@ -549,9 +618,7 @@ public class AssistantActivity extends Activity implements OnClickListener, Acti String forcedProxy = ""; if (!TextUtils.isEmpty(forcedProxy)) { - builder.setServerAddr(forcedProxy) - .setOutboundProxyEnabled(true) - .setAvpfRrInterval(5); + builder.setServerAddr(forcedProxy).setOutboundProxyEnabled(true).setAvpfRrInterval(5); } if (transport != null) { builder.setTransport(transport); @@ -573,7 +640,10 @@ public class AssistantActivity extends Activity implements OnClickListener, Acti progress = ProgressDialog.show(this, null, null); Drawable d = new ColorDrawable(ContextCompat.getColor(this, R.color.colorE)); d.setAlpha(200); - progress.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT); + progress.getWindow() + .setLayout( + WindowManager.LayoutParams.MATCH_PARENT, + WindowManager.LayoutParams.MATCH_PARENT); progress.getWindow().setBackgroundDrawable(d); progress.setContentView(R.layout.progress_dialog); progress.show(); @@ -586,7 +656,10 @@ public class AssistantActivity extends Activity implements OnClickListener, Acti progress = ProgressDialog.show(this, null, null); Drawable d = new ColorDrawable(ContextCompat.getColor(this, R.color.colorE)); d.setAlpha(200); - progress.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT); + progress.getWindow() + .setLayout( + WindowManager.LayoutParams.MATCH_PARENT, + WindowManager.LayoutParams.MATCH_PARENT); progress.getWindow().setBackgroundDrawable(d); progress.setContentView(R.layout.progress_dialog); progress.show(); @@ -606,7 +679,8 @@ public class AssistantActivity extends Activity implements OnClickListener, Acti back.setVisibility(View.INVISIBLE); } - public void displayAssistantCodeConfirm(String username, String phone, String dialcode, boolean recoverAccount) { + public void displayAssistantCodeConfirm( + String username, String phone, String dialcode, boolean recoverAccount) { CreateAccountCodeActivationFragment fragment = new CreateAccountCodeActivationFragment(); newAccount = true; Bundle extras = new Bundle(); @@ -636,7 +710,8 @@ public class AssistantActivity extends Activity implements OnClickListener, Acti } public void isAccountVerified(String username) { - Toast.makeText(this, getString(R.string.assistant_account_validated), Toast.LENGTH_LONG).show(); + Toast.makeText(this, getString(R.string.assistant_account_validated), Toast.LENGTH_LONG) + .show(); hideKeyboard(); success(); } @@ -652,19 +727,25 @@ public class AssistantActivity extends Activity implements OnClickListener, Acti } builder.setMessage(message) .setTitle(proxy.getState().toString()) - .setPositiveButton(getString(R.string.continue_text), new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - success(); - } - }) - .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - LinphoneManager.getLc().removeProxyConfig(LinphoneManager.getLc().getDefaultProxyConfig()); - LinphonePreferences.instance().resetDefaultProxyConfig(); - LinphoneManager.getLc().refreshRegisters(); - dialog.dismiss(); - } - }); + .setPositiveButton( + getString(R.string.continue_text), + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + success(); + } + }) + .setNegativeButton( + getString(R.string.cancel), + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + LinphoneManager.getLc() + .removeProxyConfig( + LinphoneManager.getLc().getDefaultProxyConfig()); + LinphonePreferences.instance().resetDefaultProxyConfig(); + LinphoneManager.getLc().refreshRegisters(); + dialog.dismiss(); + } + }); return builder.show(); } @@ -679,7 +760,10 @@ public class AssistantActivity extends Activity implements OnClickListener, Acti private void goToLinphoneActivity() { mPrefs.firstLaunchSuccessful(); - startActivity(new Intent().setClass(this, LinphoneActivity.class).putExtra("isNewProxyConfig", true)); + startActivity( + new Intent() + .setClass(this, LinphoneActivity.class) + .putExtra("isNewProxyConfig", true)); finish(); } @@ -697,7 +781,12 @@ public class AssistantActivity extends Activity implements OnClickListener, Acti mPrefs.firstLaunchSuccessful(); Intent mStartActivity = new Intent(this, LinphoneLauncherActivity.class); - PendingIntent mPendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT); + PendingIntent mPendingIntent = + PendingIntent.getActivity( + this, + (int) System.currentTimeMillis(), + mStartActivity, + PendingIntent.FLAG_CANCEL_CURRENT); AlarmManager mgr = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE); mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 500, mPendingIntent); @@ -709,7 +798,8 @@ public class AssistantActivity extends Activity implements OnClickListener, Acti } @Override - public void onIsAccountExist(AccountCreator accountCreator, AccountCreator.Status status, String resp) { + public void onIsAccountExist( + AccountCreator accountCreator, AccountCreator.Status status, String resp) { if (status.equals(AccountCreator.Status.AccountExistWithAlias)) { success(); } else { @@ -720,57 +810,48 @@ public class AssistantActivity extends Activity implements OnClickListener, Acti } @Override - public void onCreateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - - } + public void onCreateAccount( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onActivateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - - } + public void onActivateAccount( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onLinkAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - - } + public void onLinkAccount( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onActivateAlias(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - - } + public void onActivateAlias( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onIsAccountActivated(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - - } + public void onIsAccountActivated( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onRecoverAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - - } + public void onRecoverAccount( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onIsAccountLinked(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - - } + public void onIsAccountLinked( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onIsAliasUsed(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - - } + public void onIsAliasUsed( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onUpdateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - - } + public void onUpdateAccount( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} public CountryListAdapter getCountryListAdapter() { return countryListAdapter; } /** - * This class reads a JSON file containing Country-specific phone number description, - * and allows to present them into a ListView + * This class reads a JSON file containing Country-specific phone number description, and allows + * to present them into a ListView */ public class CountryListAdapter extends BaseAdapter implements Filterable { @@ -789,12 +870,10 @@ public class AssistantActivity extends Activity implements OnClickListener, Acti mInflater = inf; } - public DialPlan getCountryFromCountryCode(String countryCode) { countryCode = (countryCode.startsWith("+")) ? countryCode.substring(1) : countryCode; for (DialPlan c : allCountries) { - if (c.getCountryCallingCode().compareTo(countryCode) == 0) - return c; + if (c.getCountryCallingCode().compareTo(countryCode) == 0) return c; } return null; } @@ -831,7 +910,10 @@ public class AssistantActivity extends Activity implements OnClickListener, Acti TextView dial_code = (TextView) view.findViewById(R.id.country_prefix); if (context != null) - dial_code.setText(String.format(context.getString(R.string.country_code), c.getCountryCallingCode())); + dial_code.setText( + String.format( + context.getString(R.string.country_code), + c.getCountryCallingCode())); view.setTag(c); return view; diff --git a/app/src/main/java/org/linphone/assistant/CodecDownloaderFragment.java b/app/src/main/java/org/linphone/assistant/CodecDownloaderFragment.java index fb32833a7..9fbed11de 100644 --- a/app/src/main/java/org/linphone/assistant/CodecDownloaderFragment.java +++ b/app/src/main/java/org/linphone/assistant/CodecDownloaderFragment.java @@ -29,7 +29,6 @@ import android.view.ViewGroup; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; - import org.linphone.LinphoneManager; import org.linphone.R; import org.linphone.core.PayloadType; @@ -48,8 +47,8 @@ public class CodecDownloaderFragment extends Fragment { private TextView downloadingInfo; @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View view = inflater.inflate(R.layout.assistant_codec_downloader, container, false); question = view.findViewById(R.id.question); @@ -61,101 +60,112 @@ public class CodecDownloaderFragment extends Fragment { bar = view.findViewById(R.id.progressBar); downloadingInfo = view.findViewById(R.id.downloadingInfo); - final OpenH264DownloadHelper codecDownloader = LinphoneManager.getInstance().getOpenH264DownloadHelper(); - final OpenH264DownloadHelperListener codecListener = new OpenH264DownloadHelperListener() { + final OpenH264DownloadHelper codecDownloader = + LinphoneManager.getInstance().getOpenH264DownloadHelper(); + final OpenH264DownloadHelperListener codecListener = + new OpenH264DownloadHelperListener() { - @Override - public void OnProgress(final int current, final int max) { - mHandler.post(new Runnable() { @Override - public void run() { - if (current <= max) { - hideAllItems(); - downloadingInfo.setText(current + " / " + max); - downloadingInfo.setVisibility(View.VISIBLE); - downloading.setVisibility(View.VISIBLE); - bar.setMax(max); - bar.setProgress(current); - bar.setVisibility(View.VISIBLE); - } else { - hideAllItems(); - downloaded.setVisibility(View.VISIBLE); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { - enabledH264(true); - LinphoneManager.getLc().reloadMsPlugins(AssistantActivity.instance().getApplicationInfo().nativeLibraryDir); - AssistantActivity.instance().endDownloadCodec(); - } else { - // We need to restart due to bad android linker - AssistantActivity.instance().restartApplication(); - } - } + public void OnProgress(final int current, final int max) { + mHandler.post( + new Runnable() { + @Override + public void run() { + if (current <= max) { + hideAllItems(); + downloadingInfo.setText(current + " / " + max); + downloadingInfo.setVisibility(View.VISIBLE); + downloading.setVisibility(View.VISIBLE); + bar.setMax(max); + bar.setProgress(current); + bar.setVisibility(View.VISIBLE); + } else { + hideAllItems(); + downloaded.setVisibility(View.VISIBLE); + if (Build.VERSION.SDK_INT + >= Build.VERSION_CODES.LOLLIPOP_MR1) { + enabledH264(true); + LinphoneManager.getLc() + .reloadMsPlugins( + AssistantActivity.instance() + .getApplicationInfo() + .nativeLibraryDir); + AssistantActivity.instance().endDownloadCodec(); + } else { + // We need to restart due to bad android linker + AssistantActivity.instance().restartApplication(); + } + } + } + }); + } + + @Override + public void OnError(final String error) { + mHandler.post( + new Runnable() { + @Override + public void run() { + hideAllItems(); + downloaded.setText("Sorry an error has occurred."); + downloaded.setVisibility(View.VISIBLE); + ok.setVisibility(View.VISIBLE); + enabledH264(false); + AssistantActivity.instance().endDownloadCodec(); + } + }); + } + }; + + codecDownloader.setOpenH264HelperListener(codecListener); + + yes.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View v) { + hideAllItems(); + bar.setVisibility(View.VISIBLE); + codecDownloader.downloadCodec(); } }); - } - @Override - public void OnError(final String error) { - mHandler.post(new Runnable() { + no.setOnClickListener( + new View.OnClickListener() { @Override - public void run() { - hideAllItems(); - downloaded.setText("Sorry an error has occurred."); - downloaded.setVisibility(View.VISIBLE); - ok.setVisibility(View.VISIBLE); + public void onClick(View v) { enabledH264(false); AssistantActivity.instance().endDownloadCodec(); } }); - } - }; - - codecDownloader.setOpenH264HelperListener(codecListener); - - yes.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - hideAllItems(); - bar.setVisibility(View.VISIBLE); - codecDownloader.downloadCodec(); - } - }); - - no.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - enabledH264(false); - AssistantActivity.instance().endDownloadCodec(); - } - }); hideAllItems(); if (savedInstanceState != null) { if (savedInstanceState.containsKey("question")) question.setVisibility((Integer) savedInstanceState.getSerializable("question")); - else - question.setVisibility(View.VISIBLE); + else question.setVisibility(View.VISIBLE); if (savedInstanceState.containsKey("yes")) yes.setVisibility((Integer) savedInstanceState.getSerializable("yes")); - else - yes.setVisibility(View.VISIBLE); + else yes.setVisibility(View.VISIBLE); if (savedInstanceState.containsKey("no")) no.setVisibility((Integer) savedInstanceState.getSerializable("no")); - else - no.setVisibility(View.VISIBLE); + else no.setVisibility(View.VISIBLE); if (savedInstanceState.containsKey("downloading")) - downloading.setVisibility((Integer) savedInstanceState.getSerializable("downloading")); + downloading.setVisibility( + (Integer) savedInstanceState.getSerializable("downloading")); if (savedInstanceState.containsKey("downloaded")) - downloaded.setVisibility((Integer) savedInstanceState.getSerializable("downloaded")); + downloaded.setVisibility( + (Integer) savedInstanceState.getSerializable("downloaded")); if (savedInstanceState.containsKey("context_bar")) bar.setVisibility((Integer) savedInstanceState.getSerializable("context_bar")); if (savedInstanceState.containsKey("downloadingInfo")) - downloadingInfo.setVisibility((Integer) savedInstanceState.getSerializable("downloadingInfo")); + downloadingInfo.setVisibility( + (Integer) savedInstanceState.getSerializable("downloadingInfo")); if (savedInstanceState.containsKey("ok")) ok.setVisibility((Integer) savedInstanceState.getSerializable("ok")); diff --git a/app/src/main/java/org/linphone/assistant/CountryListFragment.java b/app/src/main/java/org/linphone/assistant/CountryListFragment.java index 93a1a2eff..71184ab5a 100644 --- a/app/src/main/java/org/linphone/assistant/CountryListFragment.java +++ b/app/src/main/java/org/linphone/assistant/CountryListFragment.java @@ -30,19 +30,19 @@ import android.widget.AdapterView; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; - import org.linphone.R; import org.linphone.core.DialPlan; -public class CountryListFragment extends Fragment implements AdapterView.OnItemClickListener, View.OnClickListener { +public class CountryListFragment extends Fragment + implements AdapterView.OnItemClickListener, View.OnClickListener { private ListView list; private EditText search; private ImageView clearSearchField; private AssistantActivity.CountryListAdapter adapter; @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.assistant_country_list, container, false); adapter = AssistantActivity.instance().getCountryListAdapter(); @@ -56,21 +56,20 @@ public class CountryListFragment extends Fragment implements AdapterView.OnItemC list.setAdapter(adapter); list.setOnItemClickListener(this); - search.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - } + search.addTextChangedListener( + new TextWatcher() { + @Override + public void beforeTextChanged( + CharSequence s, int start, int count, int after) {} - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - adapter.getFilter().filter(s); - } + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + adapter.getFilter().filter(s); + } - @Override - public void afterTextChanged(Editable s) { - - } - }); + @Override + public void afterTextChanged(Editable s) {} + }); search.setText(""); return view; diff --git a/app/src/main/java/org/linphone/assistant/CreateAccountActivationFragment.java b/app/src/main/java/org/linphone/assistant/CreateAccountActivationFragment.java index b2252377f..5bfb6dbf6 100644 --- a/app/src/main/java/org/linphone/assistant/CreateAccountActivationFragment.java +++ b/app/src/main/java/org/linphone/assistant/CreateAccountActivationFragment.java @@ -27,25 +27,29 @@ import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; - import org.linphone.LinphoneManager; -import org.linphone.settings.LinphonePreferences; import org.linphone.R; import org.linphone.core.AccountCreator; import org.linphone.core.AccountCreatorListener; +import org.linphone.settings.LinphonePreferences; -public class CreateAccountActivationFragment extends Fragment implements OnClickListener, AccountCreatorListener { +public class CreateAccountActivationFragment extends Fragment + implements OnClickListener, AccountCreatorListener { private String username, password; private Button checkAccount; private TextView email; private AccountCreator accountCreator; @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.assistant_account_creation_email_activation, container, false); + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + View view = + inflater.inflate( + R.layout.assistant_account_creation_email_activation, container, false); - accountCreator = LinphoneManager.getLc().createAccountCreator(LinphonePreferences.instance().getXmlrpcUrl()); + accountCreator = + LinphoneManager.getLc() + .createAccountCreator(LinphonePreferences.instance().getXmlrpcUrl()); accountCreator.setListener(this); username = getArguments().getString("Username"); @@ -72,55 +76,63 @@ public class CreateAccountActivationFragment extends Fragment implements OnClick } @Override - public void onIsAccountExist(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - } + public void onIsAccountExist( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onCreateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - } + public void onCreateAccount( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onActivateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - } + public void onActivateAccount( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onLinkAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - } + public void onLinkAccount( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onActivateAlias(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - } + public void onActivateAlias( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onIsAccountActivated(AccountCreator accountCreator, AccountCreator.Status status, String resp) { + public void onIsAccountActivated( + AccountCreator accountCreator, AccountCreator.Status status, String resp) { if (AssistantActivity.instance() == null) { return; } if (status.equals(AccountCreator.Status.AccountNotActivated)) { - Toast.makeText(getActivity(), getString(R.string.assistant_account_not_validated), Toast.LENGTH_LONG).show(); + Toast.makeText( + getActivity(), + getString(R.string.assistant_account_not_validated), + Toast.LENGTH_LONG) + .show(); } else if (status.equals(AccountCreator.Status.AccountActivated)) { AssistantActivity.instance().linphoneLogIn(accountCreator); AssistantActivity.instance().isAccountVerified(username); } else { - Toast.makeText(getActivity(), getString(R.string.wizard_server_unavailable), Toast.LENGTH_LONG).show(); + Toast.makeText( + getActivity(), + getString(R.string.wizard_server_unavailable), + Toast.LENGTH_LONG) + .show(); } checkAccount.setEnabled(true); } @Override - public void onRecoverAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - } + public void onRecoverAccount( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onIsAccountLinked(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - } + public void onIsAccountLinked( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onIsAliasUsed(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - } + public void onIsAliasUsed( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onUpdateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - - } + public void onUpdateAccount( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} } diff --git a/app/src/main/java/org/linphone/assistant/CreateAccountCodeActivationFragment.java b/app/src/main/java/org/linphone/assistant/CreateAccountCodeActivationFragment.java index ccddaab75..bb18d7932 100644 --- a/app/src/main/java/org/linphone/assistant/CreateAccountCodeActivationFragment.java +++ b/app/src/main/java/org/linphone/assistant/CreateAccountCodeActivationFragment.java @@ -31,14 +31,14 @@ import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; - import org.linphone.LinphoneManager; -import org.linphone.settings.LinphonePreferences; import org.linphone.R; import org.linphone.core.AccountCreator; import org.linphone.core.AccountCreatorListener; +import org.linphone.settings.LinphonePreferences; -public class CreateAccountCodeActivationFragment extends Fragment implements AccountCreatorListener { +public class CreateAccountCodeActivationFragment extends Fragment + implements AccountCreatorListener { private String username, phone, dialcode; private TextView title, phonenumber; private EditText code; @@ -49,9 +49,11 @@ public class CreateAccountCodeActivationFragment extends Fragment implements Acc private AccountCreator accountCreator; @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.assistant_account_creation_code_activation, container, false); + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + View view = + inflater.inflate( + R.layout.assistant_account_creation_code_activation, container, false); username = getArguments().getString("Username"); phone = getArguments().getString("Phone"); @@ -61,14 +63,15 @@ public class CreateAccountCodeActivationFragment extends Fragment implements Acc accountNumber = getArguments().getInt("AccountNumber"); code_length = LinphonePreferences.instance().getCodeLength(); - accountCreator = LinphoneManager.getLc().createAccountCreator(LinphonePreferences.instance().getXmlrpcUrl()); + accountCreator = + LinphoneManager.getLc() + .createAccountCreator(LinphonePreferences.instance().getXmlrpcUrl()); accountCreator.setListener(this); accountCreator.setUsername(username); accountCreator.setPhoneNumber(phone, dialcode); back = view.findViewById(R.id.back); - if (back != null) - back.setVisibility(Button.INVISIBLE); + if (back != null) back.setVisibility(Button.INVISIBLE); title = view.findViewById(R.id.title_account_activation); if (linkAccount) { @@ -81,46 +84,47 @@ public class CreateAccountCodeActivationFragment extends Fragment implements Acc phonenumber.setText(accountCreator.getPhoneNumber()); code = view.findViewById(R.id.assistant_code); - code.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - } + code.addTextChangedListener( + new TextWatcher() { + @Override + public void beforeTextChanged( + CharSequence s, int start, int count, int after) {} - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - } + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) {} - @Override - public void afterTextChanged(Editable s) { - if (s.length() == code_length) { - checkAccount.setEnabled(true); - } else { - checkAccount.setEnabled(false); - } - } - }); + @Override + public void afterTextChanged(Editable s) { + if (s.length() == code_length) { + checkAccount.setEnabled(true); + } else { + checkAccount.setEnabled(false); + } + } + }); checkAccount = view.findViewById(R.id.assistant_check); checkAccount.setEnabled(false); - checkAccount.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - checkAccount.setEnabled(false); - accountCreator.setActivationCode(code.getText().toString()); - if (linkAccount) { - linkAccount(); - } else { - activateAccount(); - } - } - }); - + checkAccount.setOnClickListener( + new OnClickListener() { + @Override + public void onClick(View v) { + checkAccount.setEnabled(false); + accountCreator.setActivationCode(code.getText().toString()); + if (linkAccount) { + linkAccount(); + } else { + activateAccount(); + } + } + }); return view; } private void linkAccount() { - accountCreator.setUsername(LinphonePreferences.instance().getAccountUsername(accountNumber)); + accountCreator.setUsername( + LinphonePreferences.instance().getAccountUsername(accountNumber)); accountCreator.setHa1(LinphonePreferences.instance().getAccountHa1(accountNumber)); accountCreator.activateAlias(); } @@ -133,15 +137,16 @@ public class CreateAccountCodeActivationFragment extends Fragment implements Acc } @Override - public void onIsAccountExist(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - } + public void onIsAccountExist( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onCreateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - } + public void onCreateAccount( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onActivateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { + public void onActivateAccount( + AccountCreator accountCreator, AccountCreator.Status status, String resp) { if (AssistantActivity.instance() == null) { return; } @@ -163,25 +168,37 @@ public class CreateAccountCodeActivationFragment extends Fragment implements Acc } } } else if (status.equals(AccountCreator.Status.RequestFailed)) { - Toast.makeText(getActivity(), getString(R.string.wizard_server_unavailable), Toast.LENGTH_LONG).show(); + Toast.makeText( + getActivity(), + getString(R.string.wizard_server_unavailable), + Toast.LENGTH_LONG) + .show(); } else { - Toast.makeText(getActivity(), getString(R.string.assistant_error_confirmation_code), Toast.LENGTH_LONG).show(); + Toast.makeText( + getActivity(), + getString(R.string.assistant_error_confirmation_code), + Toast.LENGTH_LONG) + .show(); AssistantActivity.instance().displayAssistantLinphoneLogin(phone, dialcode); } } @Override - public void onLinkAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - - } + public void onLinkAccount( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onActivateAlias(AccountCreator accountCreator, AccountCreator.Status status, String resp) { + public void onActivateAlias( + AccountCreator accountCreator, AccountCreator.Status status, String resp) { if (AssistantActivity.instance() == null) { return; } if (status.equals(AccountCreator.Status.AccountActivated)) { - LinphonePreferences.instance().setPrefix(accountNumber, org.linphone.core.Utils.getPrefixFromE164(accountCreator.getPhoneNumber())); + LinphonePreferences.instance() + .setPrefix( + accountNumber, + org.linphone.core.Utils.getPrefixFromE164( + accountCreator.getPhoneNumber())); LinphonePreferences.instance().setLinkPopupTime(""); AssistantActivity.instance().hideKeyboard(); AssistantActivity.instance().success(); @@ -189,26 +206,22 @@ public class CreateAccountCodeActivationFragment extends Fragment implements Acc } @Override - public void onIsAccountActivated(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - - } + public void onIsAccountActivated( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onRecoverAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - } + public void onRecoverAccount( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onIsAccountLinked(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - - } + public void onIsAccountLinked( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onIsAliasUsed(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - - } + public void onIsAliasUsed( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onUpdateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - - } + public void onUpdateAccount( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} } diff --git a/app/src/main/java/org/linphone/assistant/CreateAccountFragment.java b/app/src/main/java/org/linphone/assistant/CreateAccountFragment.java index 72041d1af..104297b72 100644 --- a/app/src/main/java/org/linphone/assistant/CreateAccountFragment.java +++ b/app/src/main/java/org/linphone/assistant/CreateAccountFragment.java @@ -40,25 +40,36 @@ import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; - +import java.util.Locale; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import org.linphone.LinphoneManager; -import org.linphone.settings.LinphonePreferences; -import org.linphone.utils.LinphoneUtils; import org.linphone.R; import org.linphone.core.AccountCreator; import org.linphone.core.AccountCreator.Status; import org.linphone.core.AccountCreatorListener; import org.linphone.core.DialPlan; +import org.linphone.settings.LinphonePreferences; +import org.linphone.utils.LinphoneUtils; -import java.util.Locale; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class CreateAccountFragment extends Fragment implements CompoundButton.OnCheckedChangeListener, OnClickListener, AccountCreatorListener { - private EditText phoneNumberEdit, usernameEdit, passwordEdit, passwordConfirmEdit, emailEdit, dialCode; - private TextView phoneNumberError, passwordError, passwordConfirmError, emailError, assisstantTitle, sipUri, skip, instruction; +public class CreateAccountFragment extends Fragment + implements CompoundButton.OnCheckedChangeListener, OnClickListener, AccountCreatorListener { + private final Pattern UPPER_CASE_REGEX = Pattern.compile("[A-Z]"); + private EditText phoneNumberEdit, + usernameEdit, + passwordEdit, + passwordConfirmEdit, + emailEdit, + dialCode; + private TextView phoneNumberError, + passwordError, + passwordConfirmError, + emailError, + assisstantTitle, + sipUri, + skip, + instruction; private ImageView phoneNumberInfo; - private boolean passwordOk = false; private boolean emailOk = false; private boolean confirmPasswordOk = false; @@ -67,16 +78,22 @@ public class CreateAccountFragment extends Fragment implements CompoundButton.On private CheckBox useUsername, useEmail; private String addressSip = ""; private int countryCode; - private LinearLayout phoneNumberLayout, usernameLayout, emailLayout, passwordLayout, passwordConfirmLayout; - private final Pattern UPPER_CASE_REGEX = Pattern.compile("[A-Z]"); + private LinearLayout phoneNumberLayout, + usernameLayout, + emailLayout, + passwordLayout, + passwordConfirmLayout; private AccountCreator accountCreator; @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.assistant_account_creation, container, false); - //Initialize accountCreator - accountCreator = LinphoneManager.getLc().createAccountCreator(LinphonePreferences.instance().getXmlrpcUrl()); + // Initialize accountCreator + accountCreator = + LinphoneManager.getLc() + .createAccountCreator(LinphonePreferences.instance().getXmlrpcUrl()); accountCreator.setListener(this); instruction = view.findViewById(R.id.message_create_account); @@ -115,13 +132,15 @@ public class CreateAccountFragment extends Fragment implements CompoundButton.On skip = view.findViewById(R.id.assistant_skip); - //Phone number + // Phone number if (getResources().getBoolean(R.bool.use_phone_number_validation)) { getActivity().getApplicationContext(); - //Automatically get the country code from the phone + // Automatically get the country code from the phone TelephonyManager tm = - (TelephonyManager) getActivity().getApplicationContext().getSystemService( - Context.TELEPHONY_SERVICE); + (TelephonyManager) + getActivity() + .getApplicationContext() + .getSystemService(Context.TELEPHONY_SERVICE); String countryIso = tm.getNetworkCountryIso(); countryCode = org.linphone.core.Utils.getCccFromIso(countryIso.toUpperCase()); @@ -137,19 +156,25 @@ public class CreateAccountFragment extends Fragment implements CompoundButton.On DialPlan c = AssistantActivity.instance().country; if (c != null) { selectCountry.setText(c.getCountry()); - dialCode.setText(c.getCountryCallingCode().contains("+") ? - c.getCountryCallingCode() : "+" + c.getCountryCallingCode()); + dialCode.setText( + c.getCountryCallingCode().contains("+") + ? c.getCountryCallingCode() + : "+" + c.getCountryCallingCode()); } else { - c = AssistantActivity.instance().getCountryListAdapter() - .getCountryFromCountryCode(String.valueOf(countryCode)); + c = + AssistantActivity.instance() + .getCountryListAdapter() + .getCountryFromCountryCode(String.valueOf(countryCode)); if (c != null) { selectCountry.setText(c.getCountry()); - dialCode.setText(c.getCountryCallingCode().contains("+") ? - c.getCountryCallingCode() : "+" + c.getCountryCallingCode()); + dialCode.setText( + c.getCountryCallingCode().contains("+") + ? c.getCountryCallingCode() + : "+" + c.getCountryCallingCode()); } } - //Allow user to enter a username instead use the phone number as username + // Allow user to enter a username instead use the phone number as username if (getResources().getBoolean(R.bool.assistant_allow_username)) { useUsername.setVisibility(View.VISIBLE); useUsername.setOnCheckedChangeListener(this); @@ -158,14 +183,15 @@ public class CreateAccountFragment extends Fragment implements CompoundButton.On addPhoneNumberHandler(dialCode, null); } - //Password & email address + // Password & email address if (getResources().getBoolean(R.bool.isTablet) || !getResources().getBoolean(R.bool.use_phone_number_validation)) { useEmail.setVisibility(View.VISIBLE); useEmail.setOnCheckedChangeListener(this); if (getResources().getBoolean(R.bool.pre_fill_email_in_assistant)) { - Account[] accounts = AccountManager.get(getActivity()).getAccountsByType("com.google"); + Account[] accounts = + AccountManager.get(getActivity()).getAccountsByType("com.google"); for (Account account : accounts) { if (isEmailCorrect(account.name)) { @@ -183,7 +209,7 @@ public class CreateAccountFragment extends Fragment implements CompoundButton.On addEmailHandler(emailEdit, null); } - //Hide phone number and display username/email/password + // Hide phone number and display username/email/password if (!getResources().getBoolean(R.bool.use_phone_number_validation)) { useEmail.setVisibility(View.GONE); useUsername.setVisibility(View.GONE); @@ -194,7 +220,7 @@ public class CreateAccountFragment extends Fragment implements CompoundButton.On emailLayout.setVisibility(View.VISIBLE); } - //Link account with phone number + // Link account with phone number if (getArguments().getBoolean("LinkPhoneNumber")) { linkAccount = true; useEmail.setVisibility(View.GONE); @@ -296,8 +322,12 @@ public class CreateAccountFragment extends Fragment implements CompoundButton.On if (linkAccount) { new AlertDialog.Builder(getActivity()) .setTitle(getString(R.string.phone_number_info_title)) - .setMessage(getString(R.string.phone_number_link_info_content) + "\n" - + getString(R.string.phone_number_link_info_content_already_account)) + .setMessage( + getString(R.string.phone_number_link_info_content) + + "\n" + + getString( + R.string + .phone_number_link_info_content_already_account)) .show(); } else { new AlertDialog.Builder(getActivity()) @@ -312,11 +342,15 @@ public class CreateAccountFragment extends Fragment implements CompoundButton.On } else { if (useEmail.isChecked()) accountCreator.setPhoneNumber(null, null); if (!getResources().getBoolean(R.bool.isTablet) || getUsername().length() > 0) { - LinphoneManager.getLc().getConfig().loadFromXmlFile(LinphoneManager.getInstance().getmDynamicConfigFile()); + LinphoneManager.getLc() + .getConfig() + .loadFromXmlFile(LinphoneManager.getInstance().getmDynamicConfigFile()); accountCreator.isAccountExist(); } else { - LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForUsernameStatus(AccountCreator.UsernameStatus.TooShort) - , AssistantActivity.instance()); + LinphoneUtils.displayErrorAlert( + LinphoneUtils.errorForUsernameStatus( + AccountCreator.UsernameStatus.TooShort), + AssistantActivity.instance()); createAccount.setEnabled(true); } } @@ -333,23 +367,29 @@ public class CreateAccountFragment extends Fragment implements CompoundButton.On } private void addAlias() { - accountCreator.setUsername(LinphonePreferences.instance().getAccountUsername( - LinphonePreferences.instance().getDefaultAccountIndex()) - ); - int status = accountCreator.setPhoneNumber( - phoneNumberEdit.getText().toString(), LinphoneUtils.getCountryCode(dialCode)); + accountCreator.setUsername( + LinphonePreferences.instance() + .getAccountUsername( + LinphonePreferences.instance().getDefaultAccountIndex())); + int status = + accountCreator.setPhoneNumber( + phoneNumberEdit.getText().toString(), + LinphoneUtils.getCountryCode(dialCode)); boolean isOk = status == AccountCreator.PhoneNumberStatus.Ok.toInt(); if (isOk) { accountCreator.linkAccount(); } else { createAccount.setEnabled(true); - LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForPhoneNumberStatus(status), AssistantActivity.instance()); - LinphoneUtils.displayError(isOk, phoneNumberError, LinphoneUtils.errorForPhoneNumberStatus(status)); + LinphoneUtils.displayErrorAlert( + LinphoneUtils.errorForPhoneNumberStatus(status), AssistantActivity.instance()); + LinphoneUtils.displayError( + isOk, phoneNumberError, LinphoneUtils.errorForPhoneNumberStatus(status)); } } private void createAccount() { - if ((getResources().getBoolean(R.bool.isTablet) || !getResources().getBoolean(R.bool.use_phone_number_validation)) + if ((getResources().getBoolean(R.bool.isTablet) + || !getResources().getBoolean(R.bool.use_phone_number_validation)) && useEmail.isChecked()) { AccountCreator.EmailStatus emailStatus; AccountCreator.PasswordStatus passwordStatus; @@ -358,16 +398,23 @@ public class CreateAccountFragment extends Fragment implements CompoundButton.On emailStatus = accountCreator.setEmail(emailEdit.getText().toString()); if (!emailOk) { - LinphoneUtils.displayError(false, emailError, LinphoneUtils.errorForEmailStatus(emailStatus)); - LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForEmailStatus(emailStatus) - , AssistantActivity.instance()); + LinphoneUtils.displayError( + false, emailError, LinphoneUtils.errorForEmailStatus(emailStatus)); + LinphoneUtils.displayErrorAlert( + LinphoneUtils.errorForEmailStatus(emailStatus), + AssistantActivity.instance()); } else if (!passwordOk) { - LinphoneUtils.displayError(false, passwordError, LinphoneUtils.errorForPasswordStatus(passwordStatus)); - LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForPasswordStatus(passwordStatus) - , AssistantActivity.instance()); + LinphoneUtils.displayError( + false, passwordError, LinphoneUtils.errorForPasswordStatus(passwordStatus)); + LinphoneUtils.displayErrorAlert( + LinphoneUtils.errorForPasswordStatus(passwordStatus), + AssistantActivity.instance()); } else if (!confirmPasswordOk) { String msg; - if (passwordConfirmEdit.getText().toString().equals(passwordEdit.getText().toString())) { + if (passwordConfirmEdit + .getText() + .toString() + .equals(passwordEdit.getText().toString())) { msg = getString(R.string.wizard_password_incorrect); } else { msg = getString(R.string.wizard_passwords_unmatched); @@ -381,8 +428,10 @@ public class CreateAccountFragment extends Fragment implements CompoundButton.On if (phoneNumberEdit.length() > 0 || dialCode.length() > 1) { int phoneStatus; boolean isOk; - phoneStatus = accountCreator.setPhoneNumber( - phoneNumberEdit.getText().toString(), LinphoneUtils.getCountryCode(dialCode)); + phoneStatus = + accountCreator.setPhoneNumber( + phoneNumberEdit.getText().toString(), + LinphoneUtils.getCountryCode(dialCode)); isOk = phoneStatus == AccountCreator.PhoneNumberStatus.Ok.toInt(); if (!useUsername.isChecked() && accountCreator.getUsername() == null) { accountCreator.setUsername(accountCreator.getPhoneNumber()); @@ -394,22 +443,28 @@ public class CreateAccountFragment extends Fragment implements CompoundButton.On if (isOk) { accountCreator.createAccount(); } else { - LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForPhoneNumberStatus(phoneStatus) - , AssistantActivity.instance()); - LinphoneUtils.displayError(isOk, phoneNumberError - , LinphoneUtils.errorForPhoneNumberStatus(phoneStatus)); + LinphoneUtils.displayErrorAlert( + LinphoneUtils.errorForPhoneNumberStatus(phoneStatus), + AssistantActivity.instance()); + LinphoneUtils.displayError( + isOk, + phoneNumberError, + LinphoneUtils.errorForPhoneNumberStatus(phoneStatus)); } } else { - LinphoneUtils.displayErrorAlert(getString(R.string.assistant_create_account_part_1) - , AssistantActivity.instance()); + LinphoneUtils.displayErrorAlert( + getString(R.string.assistant_create_account_part_1), + AssistantActivity.instance()); } } createAccount.setEnabled(true); } private int getPhoneNumberStatus() { - int status = accountCreator.setPhoneNumber( - phoneNumberEdit.getText().toString(), LinphoneUtils.getCountryCode(dialCode)); + int status = + accountCreator.setPhoneNumber( + phoneNumberEdit.getText().toString(), + LinphoneUtils.getCountryCode(dialCode)); addressSip = accountCreator.getPhoneNumber(); return status; } @@ -418,13 +473,16 @@ public class CreateAccountFragment extends Fragment implements CompoundButton.On String msg = ""; accountCreator.setUsername(getUsername()); - if (!useEmail.isChecked() && getResources().getBoolean(R.bool.use_phone_number_validation)) { + if (!useEmail.isChecked() + && getResources().getBoolean(R.bool.use_phone_number_validation)) { int status = getPhoneNumberStatus(); boolean isOk = (status == AccountCreator.PhoneNumberStatus.Ok.toInt()); - LinphoneUtils.displayError(isOk, phoneNumberError, LinphoneUtils.errorForPhoneNumberStatus(status)); + LinphoneUtils.displayError( + isOk, phoneNumberError, LinphoneUtils.errorForPhoneNumberStatus(status)); // Username or phone number - if (getResources().getBoolean(R.bool.assistant_allow_username) && useUsername.isChecked()) { + if (getResources().getBoolean(R.bool.assistant_allow_username) + && useUsername.isChecked()) { addressSip = getUsername(); } @@ -441,133 +499,168 @@ public class CreateAccountFragment extends Fragment implements CompoundButton.On dialCode.setBackgroundResource(R.drawable.resizable_textfield); phoneNumberEdit.setBackgroundResource(R.drawable.resizable_textfield); if (!linkAccount && addressSip.length() > 0) { - msg = getResources().getString(R.string.assistant_create_account_phone_number_address) - + " <" + addressSip + "@" + getResources().getString(R.string.default_domain) + ">"; + msg = + getResources() + .getString( + R.string + .assistant_create_account_phone_number_address) + + " <" + + addressSip + + "@" + + getResources().getString(R.string.default_domain) + + ">"; } } } else { addressSip = getUsername(); if (addressSip.length() > 0) { - msg = getResources().getString(R.string.assistant_create_account_phone_number_address) - + " "; + msg = + getResources() + .getString( + R.string + .assistant_create_account_phone_number_address) + + " "; } } sipUri.setText(msg); } private void addPhoneNumberHandler(final EditText field, final ImageView icon) { - field.addTextChangedListener(new TextWatcher() { - public void afterTextChanged(Editable s) { - if (field.equals(dialCode)) { - DialPlan c = AssistantActivity.instance().getCountryListAdapter() - .getCountryFromCountryCode(dialCode.getText().toString()); - if (c != null) { - AssistantActivity.instance().country = c; - selectCountry.setText(c.getCountry()); - } else { - selectCountry.setText(R.string.select_your_country); + field.addTextChangedListener( + new TextWatcher() { + public void afterTextChanged(Editable s) { + if (field.equals(dialCode)) { + DialPlan c = + AssistantActivity.instance() + .getCountryListAdapter() + .getCountryFromCountryCode( + dialCode.getText().toString()); + if (c != null) { + AssistantActivity.instance().country = c; + selectCountry.setText(c.getCountry()); + } else { + selectCountry.setText(R.string.select_your_country); + } + } } - } - } - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - } + public void beforeTextChanged( + CharSequence s, int start, int count, int after) {} - public void onTextChanged(CharSequence s, int start, int count, int after) { - onTextChanged2(); - } - }); + public void onTextChanged(CharSequence s, int start, int count, int after) { + onTextChanged2(); + } + }); } private void addUsernameHandler(final EditText field, final ImageView icon) { - field.addTextChangedListener(new TextWatcher() { - public void afterTextChanged(Editable s) { - Matcher matcher = UPPER_CASE_REGEX.matcher(s); - while (matcher.find()) { - CharSequence upperCaseRegion = s.subSequence(matcher.start(), matcher.end()); - s.replace(matcher.start(), matcher.end(), upperCaseRegion.toString().toLowerCase()); - } - } + field.addTextChangedListener( + new TextWatcher() { + public void afterTextChanged(Editable s) { + Matcher matcher = UPPER_CASE_REGEX.matcher(s); + while (matcher.find()) { + CharSequence upperCaseRegion = + s.subSequence(matcher.start(), matcher.end()); + s.replace( + matcher.start(), + matcher.end(), + upperCaseRegion.toString().toLowerCase()); + } + } - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - } + public void beforeTextChanged( + CharSequence s, int start, int count, int after) {} - public void onTextChanged(CharSequence s, int start, int count, int after) { - onTextChanged2(); - } - }); + public void onTextChanged(CharSequence s, int start, int count, int after) { + onTextChanged2(); + } + }); } private void addEmailHandler(final EditText field, final ImageView icon) { - field.addTextChangedListener(new TextWatcher() { - public void afterTextChanged(Editable s) { - emailOk = false; - AccountCreator.EmailStatus status = accountCreator.setEmail(field.getText().toString()); - if (status.equals(AccountCreator.EmailStatus.Ok)) { - emailOk = true; - LinphoneUtils.displayError(emailOk, emailError, ""); - } else { - LinphoneUtils.displayError(emailOk - , emailError, LinphoneUtils.errorForEmailStatus(status)); - } - } + field.addTextChangedListener( + new TextWatcher() { + public void afterTextChanged(Editable s) { + emailOk = false; + AccountCreator.EmailStatus status = + accountCreator.setEmail(field.getText().toString()); + if (status.equals(AccountCreator.EmailStatus.Ok)) { + emailOk = true; + LinphoneUtils.displayError(emailOk, emailError, ""); + } else { + LinphoneUtils.displayError( + emailOk, emailError, LinphoneUtils.errorForEmailStatus(status)); + } + } - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - } + public void beforeTextChanged( + CharSequence s, int start, int count, int after) {} - public void onTextChanged(CharSequence s, int start, int count, int after) { - } - }); + public void onTextChanged(CharSequence s, int start, int count, int after) {} + }); } private void addPasswordHandler(final EditText field1, final ImageView icon) { - TextWatcher passwordListener = new TextWatcher() { - public void afterTextChanged(Editable s) { - passwordOk = false; - AccountCreator.PasswordStatus status = accountCreator.setPassword(field1.getText().toString()); - if (isPasswordCorrect(field1.getText().toString())) { - passwordOk = true; - LinphoneUtils.displayError(passwordOk, passwordError, ""); - } else { - LinphoneUtils.displayError(passwordOk - , passwordError, LinphoneUtils.errorForPasswordStatus(status)); - } - } + TextWatcher passwordListener = + new TextWatcher() { + public void afterTextChanged(Editable s) { + passwordOk = false; + AccountCreator.PasswordStatus status = + accountCreator.setPassword(field1.getText().toString()); + if (isPasswordCorrect(field1.getText().toString())) { + passwordOk = true; + LinphoneUtils.displayError(passwordOk, passwordError, ""); + } else { + LinphoneUtils.displayError( + passwordOk, + passwordError, + LinphoneUtils.errorForPasswordStatus(status)); + } + } - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - } + public void beforeTextChanged( + CharSequence s, int start, int count, int after) {} - public void onTextChanged(CharSequence s, int start, int count, int after) { - } - }; + public void onTextChanged(CharSequence s, int start, int count, int after) {} + }; field1.addTextChangedListener(passwordListener); } - private void addConfirmPasswordHandler(final EditText field1, final EditText field2, final ImageView icon) { - TextWatcher passwordListener = new TextWatcher() { - public void afterTextChanged(Editable s) { - confirmPasswordOk = false; - if (field1.getText().toString().equals(field2.getText().toString())) { - confirmPasswordOk = true; - if (!isPasswordCorrect(field1.getText().toString())) { - LinphoneUtils.displayError(passwordOk - , passwordError, getString(R.string.wizard_password_incorrect)); - } else { - LinphoneUtils.displayError(confirmPasswordOk, passwordConfirmError, ""); + private void addConfirmPasswordHandler( + final EditText field1, final EditText field2, final ImageView icon) { + TextWatcher passwordListener = + new TextWatcher() { + public void afterTextChanged(Editable s) { + confirmPasswordOk = false; + if (field1.getText().toString().equals(field2.getText().toString())) { + confirmPasswordOk = true; + if (!isPasswordCorrect(field1.getText().toString())) { + LinphoneUtils.displayError( + passwordOk, + passwordError, + getString(R.string.wizard_password_incorrect)); + } else { + LinphoneUtils.displayError( + confirmPasswordOk, passwordConfirmError, ""); + } + } else { + LinphoneUtils.displayError( + confirmPasswordOk, + passwordConfirmError, + getString(R.string.wizard_passwords_unmatched)); + } } - } else { - LinphoneUtils.displayError(confirmPasswordOk - , passwordConfirmError, getString(R.string.wizard_passwords_unmatched)); - } - } - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - } + public void beforeTextChanged( + CharSequence s, int start, int count, int after) {} - public void onTextChanged(CharSequence s, int start, int count, int after) { - } - }; + public void onTextChanged(CharSequence s, int start, int count, int after) {} + }; field1.addTextChangedListener(passwordListener); field2.addTextChangedListener(passwordListener); } @@ -577,10 +670,12 @@ public class CreateAccountFragment extends Fragment implements CompoundButton.On if (status.equals(Status.AccountExist) || status.equals(Status.AccountExistWithAlias)) { if (useEmail.isChecked()) { createAccount.setEnabled(true); - LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForStatus(status) - , AssistantActivity.instance()); + LinphoneUtils.displayErrorAlert( + LinphoneUtils.errorForStatus(status), AssistantActivity.instance()); } else { - LinphoneManager.getLc().getConfig().loadFromXmlFile(LinphoneManager.getInstance().getmDynamicConfigFile()); + LinphoneManager.getLc() + .getConfig() + .loadFromXmlFile(LinphoneManager.getInstance().getmDynamicConfigFile()); accountCreator.isAliasUsed(); } } else { @@ -591,24 +686,30 @@ public class CreateAccountFragment extends Fragment implements CompoundButton.On @Override public void onCreateAccount(AccountCreator accountCreator, Status status, String resp) { if (status.equals(Status.AccountCreated)) { - if (useEmail.isChecked() || !getResources().getBoolean(R.bool.use_phone_number_validation)) { - AssistantActivity.instance().displayAssistantConfirm(getUsername() - , passwordEdit.getText().toString(), emailEdit.getText().toString()); + if (useEmail.isChecked() + || !getResources().getBoolean(R.bool.use_phone_number_validation)) { + AssistantActivity.instance() + .displayAssistantConfirm( + getUsername(), + passwordEdit.getText().toString(), + emailEdit.getText().toString()); } else { - AssistantActivity.instance().displayAssistantCodeConfirm(getUsername() - , phoneNumberEdit.getText().toString() - , LinphoneUtils.getCountryCode(dialCode), false); + AssistantActivity.instance() + .displayAssistantCodeConfirm( + getUsername(), + phoneNumberEdit.getText().toString(), + LinphoneUtils.getCountryCode(dialCode), + false); } } else { createAccount.setEnabled(true); - LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForStatus(status) - , AssistantActivity.instance()); + LinphoneUtils.displayErrorAlert( + LinphoneUtils.errorForStatus(status), AssistantActivity.instance()); } } @Override - public void onActivateAccount(AccountCreator accountCreator, Status status, String resp) { - } + public void onActivateAccount(AccountCreator accountCreator, Status status, String resp) {} @Override public void onLinkAccount(AccountCreator accountCreator, Status status, String resp) { @@ -616,9 +717,12 @@ public class CreateAccountFragment extends Fragment implements CompoundButton.On return; } if (status.equals(Status.RequestOk)) { - AssistantActivity.instance().displayAssistantCodeConfirm(getUsername() - , phoneNumberEdit.getText().toString() - , LinphoneUtils.getCountryCode(dialCode), false); + AssistantActivity.instance() + .displayAssistantCodeConfirm( + getUsername(), + phoneNumberEdit.getText().toString(), + LinphoneUtils.getCountryCode(dialCode), + false); } } @@ -628,9 +732,12 @@ public class CreateAccountFragment extends Fragment implements CompoundButton.On return; } if (status.equals(Status.RequestOk)) { - AssistantActivity.instance().displayAssistantCodeConfirm(getUsername() - , phoneNumberEdit.getText().toString() - , LinphoneUtils.getCountryCode(dialCode), false); + AssistantActivity.instance() + .displayAssistantCodeConfirm( + getUsername(), + phoneNumberEdit.getText().toString(), + LinphoneUtils.getCountryCode(dialCode), + false); } } @@ -642,14 +749,14 @@ public class CreateAccountFragment extends Fragment implements CompoundButton.On if (status.equals(Status.AccountNotActivated)) { if (getResources().getBoolean(R.bool.isTablet) || !getResources().getBoolean(R.bool.use_phone_number_validation)) { - //accountCreator.activateAccount(); // Resend email TODO + // accountCreator.activateAccount(); // Resend email TODO } else { accountCreator.recoverAccount(); // Resend SMS } } else { createAccount.setEnabled(true); - LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForStatus(status) - , AssistantActivity.instance()); + LinphoneUtils.displayErrorAlert( + LinphoneUtils.errorForStatus(status), AssistantActivity.instance()); } } @@ -659,19 +766,22 @@ public class CreateAccountFragment extends Fragment implements CompoundButton.On return; } if (status.equals(Status.RequestOk)) { - AssistantActivity.instance().displayAssistantCodeConfirm(getUsername() - , phoneNumberEdit.getText().toString(), dialCode.getText().toString(), false); + AssistantActivity.instance() + .displayAssistantCodeConfirm( + getUsername(), + phoneNumberEdit.getText().toString(), + dialCode.getText().toString(), + false); } else { createAccount.setEnabled(true); - //SMS error - LinphoneUtils.displayErrorAlert(getString(R.string.request_failed) - , AssistantActivity.instance()); + // SMS error + LinphoneUtils.displayErrorAlert( + getString(R.string.request_failed), AssistantActivity.instance()); } } @Override - public void onIsAccountLinked(AccountCreator accountCreator, Status status, String resp) { - } + public void onIsAccountLinked(AccountCreator accountCreator, Status status, String resp) {} @Override public void onIsAliasUsed(AccountCreator ac, Status status, String resp) { @@ -679,13 +789,15 @@ public class CreateAccountFragment extends Fragment implements CompoundButton.On return; } if (status.equals(Status.AliasIsAccount) || status.equals(Status.AliasExist)) { - if (accountCreator.getPhoneNumber() != null && accountCreator.getUsername() != null - && accountCreator.getPhoneNumber().compareTo(accountCreator.getUsername()) == 0) { + if (accountCreator.getPhoneNumber() != null + && accountCreator.getUsername() != null + && accountCreator.getPhoneNumber().compareTo(accountCreator.getUsername()) + == 0) { accountCreator.isAccountActivated(); } else { createAccount.setEnabled(true); - LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForStatus(status) - , AssistantActivity.instance()); + LinphoneUtils.displayErrorAlert( + LinphoneUtils.errorForStatus(status), AssistantActivity.instance()); } } else { accountCreator.isAccountActivated(); @@ -693,7 +805,5 @@ public class CreateAccountFragment extends Fragment implements CompoundButton.On } @Override - public void onUpdateAccount(AccountCreator accountCreator, Status status, String resp) { - - } + public void onUpdateAccount(AccountCreator accountCreator, Status status, String resp) {} } diff --git a/app/src/main/java/org/linphone/assistant/EchoCancellerCalibrationFragment.java b/app/src/main/java/org/linphone/assistant/EchoCancellerCalibrationFragment.java index 3a4ded4ef..48eab1de2 100644 --- a/app/src/main/java/org/linphone/assistant/EchoCancellerCalibrationFragment.java +++ b/app/src/main/java/org/linphone/assistant/EchoCancellerCalibrationFragment.java @@ -26,9 +26,7 @@ import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; - import org.linphone.LinphoneManager; -import org.linphone.settings.LinphonePreferences; import org.linphone.R; import org.linphone.core.Core; import org.linphone.core.CoreException; @@ -39,6 +37,7 @@ import org.linphone.core.XmlRpcRequest; import org.linphone.core.XmlRpcRequestListener; import org.linphone.core.XmlRpcSession; import org.linphone.mediastream.Log; +import org.linphone.settings.LinphonePreferences; public class EchoCancellerCalibrationFragment extends Fragment implements XmlRpcRequestListener { private Handler mHandler = new Handler(); @@ -49,30 +48,36 @@ public class EchoCancellerCalibrationFragment extends Fragment implements XmlRpc private Runnable runFinished; @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.assistant_ec_calibration, container, false); - mListener = new CoreListenerStub() { - @Override - public void onEcCalibrationResult(Core lc, EcCalibratorStatus status, int delay_ms) { - lc.removeListener(mListener); - LinphoneManager.getInstance().routeAudioToReceiver(); - if (mSendEcCalibrationResult) { - sendEcCalibrationResult(status, delay_ms); - } else { - AssistantActivity.instance().isEchoCalibrationFinished(); - } - } - }; - runFinished = new Runnable() { - public void run() { - AssistantActivity.instance().isEchoCalibrationFinished(); - } - }; + mListener = + new CoreListenerStub() { + @Override + public void onEcCalibrationResult( + Core lc, EcCalibratorStatus status, int delay_ms) { + lc.removeListener(mListener); + LinphoneManager.getInstance().routeAudioToReceiver(); + if (mSendEcCalibrationResult) { + sendEcCalibrationResult(status, delay_ms); + } else { + AssistantActivity.instance().isEchoCalibrationFinished(); + } + } + }; + runFinished = + new Runnable() { + public void run() { + AssistantActivity.instance().isEchoCalibrationFinished(); + } + }; - xmlRpcSession = LinphoneManager.getLcIfManagerNotDestroyedOrNull().createXmlRpcSession(LinphonePreferences.instance().getXmlrpcUrl()); - xmlRpcRequest = xmlRpcSession.createRequest(XmlRpcArgType.None, "add_ec_calibration_result"); + xmlRpcSession = + LinphoneManager.getLcIfManagerNotDestroyedOrNull() + .createXmlRpcSession(LinphonePreferences.instance().getXmlrpcUrl()); + xmlRpcRequest = + xmlRpcSession.createRequest(XmlRpcArgType.None, "add_ec_calibration_result"); xmlRpcRequest.setListener(this); try { @@ -96,7 +101,18 @@ public class EchoCancellerCalibrationFragment extends Fragment implements XmlRpc private void sendEcCalibrationResult(EcCalibratorStatus status, int delayMs) { Boolean hasBuiltInEchoCanceler = LinphoneManager.getLc().hasBuiltinEchoCanceller(); - Log.i("Add echo canceller calibration result: manufacturer=" + Build.MANUFACTURER + " model=" + Build.MODEL + " status=" + status + " delay=" + delayMs + "ms" + " hasBuiltInEchoCanceler " + hasBuiltInEchoCanceler); + Log.i( + "Add echo canceller calibration result: manufacturer=" + + Build.MANUFACTURER + + " model=" + + Build.MODEL + + " status=" + + status + + " delay=" + + delayMs + + "ms" + + " hasBuiltInEchoCanceler " + + hasBuiltInEchoCanceler); xmlRpcRequest.addStringArg(Build.MANUFACTURER); xmlRpcRequest.addStringArg(Build.MODEL); xmlRpcRequest.addStringArg(status.toString()); diff --git a/app/src/main/java/org/linphone/assistant/LinphoneLoginFragment.java b/app/src/main/java/org/linphone/assistant/LinphoneLoginFragment.java index 4686e8931..621c8f965 100644 --- a/app/src/main/java/org/linphone/assistant/LinphoneLoginFragment.java +++ b/app/src/main/java/org/linphone/assistant/LinphoneLoginFragment.java @@ -39,18 +39,20 @@ import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; - +import java.util.Locale; import org.linphone.LinphoneManager; -import org.linphone.settings.LinphonePreferences; -import org.linphone.utils.LinphoneUtils; import org.linphone.R; import org.linphone.core.AccountCreator; import org.linphone.core.AccountCreatorListener; import org.linphone.core.DialPlan; +import org.linphone.settings.LinphonePreferences; +import org.linphone.utils.LinphoneUtils; -import java.util.Locale; - -public class LinphoneLoginFragment extends Fragment implements CompoundButton.OnCheckedChangeListener, OnClickListener, TextWatcher, AccountCreatorListener { +public class LinphoneLoginFragment extends Fragment + implements CompoundButton.OnCheckedChangeListener, + OnClickListener, + TextWatcher, + AccountCreatorListener { private EditText login, password, phoneNumberEdit, dialCode; private Button apply, selectCountry; private CheckBox useUsername; @@ -63,11 +65,13 @@ public class LinphoneLoginFragment extends Fragment implements CompoundButton.On private ImageView phoneNumberInfo; @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.assistant_linphone_login, container, false); - accountCreator = LinphoneManager.getLc().createAccountCreator(LinphonePreferences.instance().getXmlrpcUrl()); + accountCreator = + LinphoneManager.getLc() + .createAccountCreator(LinphonePreferences.instance().getXmlrpcUrl()); accountCreator.setListener(this); String url = "http://linphone.org/free-sip-service.html&action=recover"; @@ -98,33 +102,40 @@ public class LinphoneLoginFragment extends Fragment implements CompoundButton.On apply.setEnabled(true); apply.setOnClickListener(this); - //Phone number + // Phone number if (getResources().getBoolean(R.bool.use_phone_number_validation)) { messagePhoneNumber.setText(getString(R.string.assistant_create_account_part_1)); phone = getArguments().getString("Phone"); dialcode = getArguments().getString("Dialcode"); getActivity().getApplicationContext(); - //Automatically get the country code from the phone + // Automatically get the country code from the phone TelephonyManager tm = - (TelephonyManager) getActivity().getApplicationContext().getSystemService( - Context.TELEPHONY_SERVICE); + (TelephonyManager) + getActivity() + .getApplicationContext() + .getSystemService(Context.TELEPHONY_SERVICE); String countryIso = tm.getNetworkCountryIso(); countryCode = org.linphone.core.Utils.getCccFromIso(countryIso.toUpperCase()); - DialPlan c = AssistantActivity.instance().country; if (c != null) { selectCountry.setText(c.getCountry()); - dialCode.setText(c.getCountryCallingCode().contains("+") ? - c.getCountryCallingCode() : "+" + c.getCountryCallingCode()); + dialCode.setText( + c.getCountryCallingCode().contains("+") + ? c.getCountryCallingCode() + : "+" + c.getCountryCallingCode()); } else { - c = AssistantActivity.instance().getCountryListAdapter() - .getCountryFromCountryCode(String.valueOf(countryCode)); + c = + AssistantActivity.instance() + .getCountryListAdapter() + .getCountryFromCountryCode(String.valueOf(countryCode)); if (c != null) { selectCountry.setText(c.getCountry()); - dialCode.setText(c.getCountryCallingCode().contains("+") ? - c.getCountryCallingCode() : "+" + c.getCountryCallingCode()); + dialCode.setText( + c.getCountryCallingCode().contains("+") + ? c.getCountryCallingCode() + : "+" + c.getCountryCallingCode()); } } @@ -137,27 +148,31 @@ public class LinphoneLoginFragment extends Fragment implements CompoundButton.On phoneNumberEdit.setText(previousPhone); } - //Allow user to enter a username instead use the phone number as username + // Allow user to enter a username instead use the phone number as username if (getResources().getBoolean(R.bool.assistant_allow_username)) { useUsername.setVisibility(View.VISIBLE); useUsername.setOnCheckedChangeListener(this); } - if (phone != null) - phoneNumberEdit.setText(phone); - if (dialcode != null) - dialCode.setText("+" + dialcode); + if (phone != null) phoneNumberEdit.setText(phone); + if (dialcode != null) dialCode.setText("+" + dialcode); } if (getResources().getBoolean(R.bool.assistant_allow_username)) { useUsername.setVisibility(View.VISIBLE); useUsername.setOnCheckedChangeListener(this); password.addTextChangedListener(this); - forgotPassword.setText(Html.fromHtml("" + getString(R.string.forgot_password) + "")); + forgotPassword.setText( + Html.fromHtml( + "" + + getString(R.string.forgot_password) + + "")); forgotPassword.setMovementMethod(LinkMovementMethod.getInstance()); } - //Hide phone number and display username/email/password + // Hide phone number and display username/email/password if (!getResources().getBoolean(R.bool.use_phone_number_validation)) { phoneNumberLayout.setVisibility(View.GONE); useUsername.setVisibility(View.GONE); @@ -187,8 +202,13 @@ public class LinphoneLoginFragment extends Fragment implements CompoundButton.On } public void linphoneLogIn() { - if (login.getText() == null || login.length() == 0 || password.getText() == null || password.length() == 0) { - LinphoneUtils.displayErrorAlert(getString(R.string.first_launch_no_login_password), AssistantActivity.instance()); + if (login.getText() == null + || login.length() == 0 + || password.getText() == null + || password.length() == 0) { + LinphoneUtils.displayErrorAlert( + getString(R.string.first_launch_no_login_password), + AssistantActivity.instance()); apply.setEnabled(true); return; } @@ -198,39 +218,43 @@ public class LinphoneLoginFragment extends Fragment implements CompoundButton.On } private int getPhoneNumberStatus() { - return accountCreator.setPhoneNumber(phoneNumberEdit.getText().toString(), LinphoneUtils.getCountryCode(dialCode)); + return accountCreator.setPhoneNumber( + phoneNumberEdit.getText().toString(), LinphoneUtils.getCountryCode(dialCode)); } private void addPhoneNumberHandler(final EditText field, final ImageView icon) { - field.addTextChangedListener(new TextWatcher() { - public void afterTextChanged(Editable s) { - if (field.equals(dialCode)) { - DialPlan c = AssistantActivity.instance().getCountryListAdapter().getCountryFromCountryCode(dialCode.getText().toString()); - if (c != null) { - AssistantActivity.instance().country = c; - selectCountry.setText(c.getCountry()); - } else { - selectCountry.setText(R.string.select_your_country); + field.addTextChangedListener( + new TextWatcher() { + public void afterTextChanged(Editable s) { + if (field.equals(dialCode)) { + DialPlan c = + AssistantActivity.instance() + .getCountryListAdapter() + .getCountryFromCountryCode( + dialCode.getText().toString()); + if (c != null) { + AssistantActivity.instance().country = c; + selectCountry.setText(c.getCountry()); + } else { + selectCountry.setText(R.string.select_your_country); + } + } } - } - } - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - } + public void beforeTextChanged( + CharSequence s, int start, int count, int after) {} - public void onTextChanged(CharSequence s, int start, int count, int after) { - onTextChanged2(); - } - }); + public void onTextChanged(CharSequence s, int start, int count, int after) { + onTextChanged2(); + } + }); } @Override public void onResume() { super.onResume(); - if (useUsername != null && useUsername.isChecked()) - recoverAccount = false; - else - recoverAccount = true; + if (useUsername != null && useUsername.isChecked()) recoverAccount = false; + else recoverAccount = true; } @Override @@ -251,7 +275,6 @@ public class LinphoneLoginFragment extends Fragment implements CompoundButton.On } else if (id == R.id.select_country) { AssistantActivity.instance().displayCountryChooser(); } - } private void recoverAccount() { @@ -259,29 +282,34 @@ public class LinphoneLoginFragment extends Fragment implements CompoundButton.On int status = getPhoneNumberStatus(); boolean isOk = status == AccountCreator.PhoneNumberStatus.Ok.toInt(); if (isOk) { - LinphoneManager.getLc().getConfig().loadFromXmlFile(LinphoneManager.getInstance().getmDynamicConfigFile()); + LinphoneManager.getLc() + .getConfig() + .loadFromXmlFile(LinphoneManager.getInstance().getmDynamicConfigFile()); accountCreator.isAliasUsed(); } else { apply.setEnabled(true); - LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForPhoneNumberStatus(status), + LinphoneUtils.displayErrorAlert( + LinphoneUtils.errorForPhoneNumberStatus(status), AssistantActivity.instance()); - LinphoneUtils.displayError(isOk, phoneNumberError, - LinphoneUtils.errorForPhoneNumberStatus(status)); + LinphoneUtils.displayError( + isOk, phoneNumberError, LinphoneUtils.errorForPhoneNumberStatus(status)); } } else { apply.setEnabled(true); - LinphoneUtils.displayErrorAlert(getString(R.string.assistant_create_account_part_1), AssistantActivity.instance()); + LinphoneUtils.displayErrorAlert( + getString(R.string.assistant_create_account_part_1), + AssistantActivity.instance()); } } @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() { int status = getPhoneNumberStatus(); boolean isOk = status == AccountCreator.PhoneNumberStatus.Ok.toInt(); - LinphoneUtils.displayError(isOk, phoneNumberError, LinphoneUtils.errorForPhoneNumberStatus(status)); + LinphoneUtils.displayError( + isOk, phoneNumberError, LinphoneUtils.errorForPhoneNumberStatus(status)); if (!isOk) { if ((1 == (status & AccountCreator.PhoneNumberStatus.InvalidCountryCode.toInt()))) { dialCode.setBackgroundResource(R.drawable.resizable_textfield_error); @@ -291,7 +319,8 @@ public class LinphoneLoginFragment extends Fragment implements CompoundButton.On phoneNumberEdit.setBackgroundResource(R.drawable.resizable_textfield_error); } } else { - accountCreator.setPhoneNumber(phoneNumberEdit.getText().toString(), dialCode.getText().toString()); + accountCreator.setPhoneNumber( + phoneNumberEdit.getText().toString(), dialCode.getText().toString()); dialCode.setBackgroundResource(R.drawable.resizable_textfield); phoneNumberEdit.setBackgroundResource(R.drawable.resizable_textfield); } @@ -303,8 +332,7 @@ public class LinphoneLoginFragment extends Fragment implements CompoundButton.On } @Override - public void afterTextChanged(Editable s) { - } + public void afterTextChanged(Editable s) {} @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { @@ -328,73 +356,86 @@ public class LinphoneLoginFragment extends Fragment implements CompoundButton.On } @Override - public void onIsAccountExist(AccountCreator accountCreator, AccountCreator.Status status, String resp) { + public void onIsAccountExist( + AccountCreator accountCreator, AccountCreator.Status status, String resp) { if (AssistantActivity.instance() == null) { apply.setEnabled(true); return; } - if (status.equals(AccountCreator.Status.AccountExist) || status.equals(AccountCreator.Status.AccountExistWithAlias)) { + if (status.equals(AccountCreator.Status.AccountExist) + || status.equals(AccountCreator.Status.AccountExistWithAlias)) { AssistantActivity.instance().linphoneLogIn(accountCreator); } else { - LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForStatus(status), AssistantActivity.instance()); + LinphoneUtils.displayErrorAlert( + LinphoneUtils.errorForStatus(status), AssistantActivity.instance()); } apply.setEnabled(true); } @Override - public void onCreateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - } + public void onCreateAccount( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onActivateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - } + public void onActivateAccount( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onLinkAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - } + public void onLinkAccount( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onActivateAlias(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - } + public void onActivateAlias( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onIsAccountActivated(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - } + public void onIsAccountActivated( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onRecoverAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { + public void onRecoverAccount( + AccountCreator accountCreator, AccountCreator.Status status, String resp) { if (AssistantActivity.instance() == null) { apply.setEnabled(true); return; } if (status.equals(AccountCreator.Status.ServerError)) { - LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForStatus(AccountCreator.Status.RequestFailed), AssistantActivity.instance()); + LinphoneUtils.displayErrorAlert( + LinphoneUtils.errorForStatus(AccountCreator.Status.RequestFailed), + AssistantActivity.instance()); apply.setEnabled(true); } else { - AssistantActivity.instance().displayAssistantCodeConfirm(accountCreator.getUsername(), phoneNumberEdit.getText().toString(), LinphoneUtils.getCountryCode(dialCode), true); + AssistantActivity.instance() + .displayAssistantCodeConfirm( + accountCreator.getUsername(), + phoneNumberEdit.getText().toString(), + LinphoneUtils.getCountryCode(dialCode), + true); } } @Override - public void onIsAccountLinked(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - } + public void onIsAccountLinked( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onIsAliasUsed(AccountCreator accountCreator, AccountCreator.Status status, String resp) { + public void onIsAliasUsed( + AccountCreator accountCreator, AccountCreator.Status status, String resp) { if (AssistantActivity.instance() == null) { apply.setEnabled(true); return; } - if (status.equals(AccountCreator.Status.AliasIsAccount) || status.equals(AccountCreator.Status.AliasExist)) { + if (status.equals(AccountCreator.Status.AliasIsAccount) + || status.equals(AccountCreator.Status.AliasExist)) { accountCreator.recoverAccount(); } else { apply.setEnabled(true); - LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForStatus(status), AssistantActivity.instance()); + LinphoneUtils.displayErrorAlert( + LinphoneUtils.errorForStatus(status), AssistantActivity.instance()); } } @Override - public void onUpdateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - - } + public void onUpdateAccount( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} } diff --git a/app/src/main/java/org/linphone/assistant/LoginFragment.java b/app/src/main/java/org/linphone/assistant/LoginFragment.java index e0088f7d9..fbd6068b2 100644 --- a/app/src/main/java/org/linphone/assistant/LoginFragment.java +++ b/app/src/main/java/org/linphone/assistant/LoginFragment.java @@ -30,7 +30,6 @@ import android.widget.Button; import android.widget.EditText; import android.widget.RadioGroup; import android.widget.Toast; - import org.linphone.R; import org.linphone.core.TransportType; @@ -40,8 +39,8 @@ public class LoginFragment extends Fragment implements OnClickListener, TextWatc private Button apply; @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.assistant_login, container, false); login = view.findViewById(R.id.assistant_username); @@ -67,8 +66,17 @@ public class LoginFragment extends Fragment implements OnClickListener, TextWatc int id = v.getId(); if (id == R.id.assistant_apply) { - if (login.getText() == null || login.length() == 0 || password.getText() == null || password.length() == 0 || domain.getText() == null || domain.length() == 0) { - Toast.makeText(getActivity(), getString(R.string.first_launch_no_login_password), Toast.LENGTH_LONG).show(); + if (login.getText() == null + || login.length() == 0 + || password.getText() == null + || password.length() == 0 + || domain.getText() == null + || domain.length() == 0) { + Toast.makeText( + getActivity(), + getString(R.string.first_launch_no_login_password), + Toast.LENGTH_LONG) + .show(); return; } @@ -84,24 +92,34 @@ public class LoginFragment extends Fragment implements OnClickListener, TextWatc } if (domain.getText().toString().compareTo(getString(R.string.default_domain)) == 0) { - AssistantActivity.instance().displayLoginLinphone(login.getText().toString(), password.getText().toString()); + AssistantActivity.instance() + .displayLoginLinphone( + login.getText().toString(), password.getText().toString()); } else { - AssistantActivity.instance().genericLogIn(login.getText().toString(), userid.getText().toString(), password.getText().toString(), displayName.getText().toString(), null, domain.getText().toString(), transport); + AssistantActivity.instance() + .genericLogIn( + login.getText().toString(), + userid.getText().toString(), + password.getText().toString(), + displayName.getText().toString(), + null, + domain.getText().toString(), + transport); } } } @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - } + public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void onTextChanged(CharSequence s, int start, int before, int count) { - apply.setEnabled(!login.getText().toString().isEmpty() && !password.getText().toString().isEmpty() && !domain.getText().toString().isEmpty()); + apply.setEnabled( + !login.getText().toString().isEmpty() + && !password.getText().toString().isEmpty() + && !domain.getText().toString().isEmpty()); } @Override - public void afterTextChanged(Editable s) { - - } + public void afterTextChanged(Editable s) {} } diff --git a/app/src/main/java/org/linphone/assistant/RemoteProvisioningActivity.java b/app/src/main/java/org/linphone/assistant/RemoteProvisioningActivity.java index a6e92efb9..c9814fe0e 100644 --- a/app/src/main/java/org/linphone/assistant/RemoteProvisioningActivity.java +++ b/app/src/main/java/org/linphone/assistant/RemoteProvisioningActivity.java @@ -28,19 +28,17 @@ import android.os.Handler; import android.view.View; import android.widget.ProgressBar; import android.widget.Toast; - +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import org.linphone.LinphoneLauncherActivity; import org.linphone.LinphoneManager; -import org.linphone.settings.LinphonePreferences; import org.linphone.LinphoneService; import org.linphone.R; -import org.linphone.LinphoneLauncherActivity; import org.linphone.core.ConfiguringState; import org.linphone.core.Core; import org.linphone.core.CoreListenerStub; import org.linphone.mediastream.Log; - -import java.io.UnsupportedEncodingException; -import java.net.URLDecoder; +import org.linphone.settings.LinphonePreferences; public class RemoteProvisioningActivity extends Activity { private Handler mHandler = new Handler(); @@ -54,17 +52,23 @@ public class RemoteProvisioningActivity extends Activity { setContentView(R.layout.remote_provisioning); spinner = findViewById(R.id.spinner); - mListener = new CoreListenerStub() { - @Override - public void onConfiguringStatus(Core lc, final ConfiguringState state, String message) { - if (spinner != null) spinner.setVisibility(View.GONE); - if (state == ConfiguringState.Successful) { - goToLinphoneActivity(); - } else if (state == ConfiguringState.Failed) { - Toast.makeText(RemoteProvisioningActivity.this, R.string.remote_provisioning_failure, Toast.LENGTH_LONG).show(); - } - } - }; + mListener = + new CoreListenerStub() { + @Override + public void onConfiguringStatus( + Core lc, final ConfiguringState state, String message) { + if (spinner != null) spinner.setVisibility(View.GONE); + if (state == ConfiguringState.Successful) { + goToLinphoneActivity(); + } else if (state == ConfiguringState.Failed) { + Toast.makeText( + RemoteProvisioningActivity.this, + R.string.remote_provisioning_failure, + Toast.LENGTH_LONG) + .show(); + } + } + }; } @Override @@ -100,75 +104,97 @@ public class RemoteProvisioningActivity extends Activity { } private void checkIntentForConfigUri(final Intent intent) { - new Thread(new Runnable() { + new Thread( + new Runnable() { - @Override - public void run() { - Uri openUri = intent.getData(); - if (openUri != null) { - // We expect something like linphone-config://http://linphone.org/config.xml - configUriParam = openUri.getEncodedSchemeSpecificPart().substring(2); // Removes the linphone-config:// - try { - configUriParam = URLDecoder.decode(configUriParam, "UTF-8"); - } catch (UnsupportedEncodingException e) { - Log.e(e); - } - Log.d("Using config uri: " + configUriParam); - } + @Override + public void run() { + Uri openUri = intent.getData(); + if (openUri != null) { + // We expect something like + // linphone-config://http://linphone.org/config.xml + configUriParam = + openUri.getEncodedSchemeSpecificPart() + .substring(2); // Removes the linphone-config:// + try { + configUriParam = URLDecoder.decode(configUriParam, "UTF-8"); + } catch (UnsupportedEncodingException e) { + Log.e(e); + } + Log.d("Using config uri: " + configUriParam); + } - if (configUriParam == null) { - if (!LinphonePreferences.instance().isFirstRemoteProvisioning()) { - mHandler.post(new Runnable() { - @Override - public void run() { - goToLinphoneActivity(); + if (configUriParam == null) { + if (!LinphonePreferences.instance() + .isFirstRemoteProvisioning()) { + mHandler.post( + new Runnable() { + @Override + public void run() { + goToLinphoneActivity(); + } + }); + } else if (!getResources() + .getBoolean( + R.bool.forbid_app_usage_until_remote_provisioning_completed)) { + // Show this view for a few seconds then go to the dialer + mHandler.postDelayed( + new Runnable() { + @Override + public void run() { + goToLinphoneActivity(); + } + }, + 1500); + } // else we do nothing if there is no config uri parameter and + // if user not allowed to leave this screen + } else { + if (getResources() + .getBoolean( + R.bool.display_confirmation_popup_after_first_configuration) + && !LinphonePreferences.instance() + .isFirstRemoteProvisioning()) { + mHandler.post( + new Runnable() { + @Override + public void run() { + displayDialogConfirmation(); + } + }); + } else { + mHandler.post( + new Runnable() { + @Override + public void run() { + setRemoteProvisioningAddressAndRestart( + configUriParam); + } + }); + } + } } - }); - } else if (!getResources().getBoolean(R.bool.forbid_app_usage_until_remote_provisioning_completed)) { - // Show this view for a few seconds then go to the dialer - mHandler.postDelayed(new Runnable() { - @Override - public void run() { - goToLinphoneActivity(); - } - }, 1500); - } // else we do nothing if there is no config uri parameter and if user not allowed to leave this screen - } else { - if (getResources().getBoolean(R.bool.display_confirmation_popup_after_first_configuration) - && !LinphonePreferences.instance().isFirstRemoteProvisioning()) { - mHandler.post(new Runnable() { - @Override - public void run() { - displayDialogConfirmation(); - } - }); - } else { - mHandler.post(new Runnable() { - @Override - public void run() { - setRemoteProvisioningAddressAndRestart(configUriParam); - } - }); - } - } - } - }).start(); + }) + .start(); } private void displayDialogConfirmation() { new AlertDialog.Builder(RemoteProvisioningActivity.this) .setTitle(getString(R.string.remote_provisioning_again_title)) .setMessage(getString(R.string.remote_provisioning_again_message)) - .setPositiveButton(R.string.accept, new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int which) { - setRemoteProvisioningAddressAndRestart(configUriParam); - } - }) - .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int which) { - goToLinphoneActivity(); - } - }) + .setPositiveButton( + R.string.accept, + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + setRemoteProvisioningAddressAndRestart(configUriParam); + } + }) + .setNegativeButton( + R.string.cancel, + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + goToLinphoneActivity(); + } + }) .show(); } @@ -178,22 +204,24 @@ public class RemoteProvisioningActivity extends Activity { LinphonePreferences.instance().setContext(this); // Needed, else the next call will crash LinphonePreferences.instance().setRemoteProvisioningUrl(configUri); - mHandler.postDelayed(new Runnable() { - @Override - public void run() { - LinphoneManager.getInstance().restartCore(); - } - }, 1000); + mHandler.postDelayed( + new Runnable() { + @Override + public void run() { + LinphoneManager.getInstance().restartCore(); + } + }, + 1000); } private void goToLinphoneActivity() { if (LinphoneService.isReady()) { - LinphoneService.instance().setActivityToLaunchOnIncomingReceived("org.linphone.LinphoneLauncherActivity"); - //finish(); // To prevent the user to come back to this page using back button + LinphoneService.instance() + .setActivityToLaunchOnIncomingReceived("org.linphone.LinphoneLauncherActivity"); + // finish(); // To prevent the user to come back to this page using back button startActivity(new Intent().setClass(this, LinphoneLauncherActivity.class)); } else { finish(); } } - } diff --git a/app/src/main/java/org/linphone/assistant/RemoteProvisioningFragment.java b/app/src/main/java/org/linphone/assistant/RemoteProvisioningFragment.java index 236d15201..352e1ccb5 100644 --- a/app/src/main/java/org/linphone/assistant/RemoteProvisioningFragment.java +++ b/app/src/main/java/org/linphone/assistant/RemoteProvisioningFragment.java @@ -28,18 +28,17 @@ import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; - import org.linphone.LinphoneManager; -import org.linphone.settings.LinphonePreferences; import org.linphone.R; +import org.linphone.settings.LinphonePreferences; public class RemoteProvisioningFragment extends Fragment implements OnClickListener, TextWatcher { private EditText remoteProvisioningUrl; private Button apply; @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.assistant_remote_provisioning, container, false); remoteProvisioningUrl = view.findViewById(R.id.assistant_remote_provisioning_url); @@ -66,9 +65,7 @@ public class RemoteProvisioningFragment extends Fragment implements OnClickListe } @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - - } + public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void onTextChanged(CharSequence s, int start, int before, int count) { @@ -76,7 +73,5 @@ public class RemoteProvisioningFragment extends Fragment implements OnClickListe } @Override - public void afterTextChanged(Editable s) { - - } + public void afterTextChanged(Editable s) {} } diff --git a/app/src/main/java/org/linphone/assistant/RemoteProvisioningLoginActivity.java b/app/src/main/java/org/linphone/assistant/RemoteProvisioningLoginActivity.java index 37c65ef94..0e3fd3bc0 100644 --- a/app/src/main/java/org/linphone/assistant/RemoteProvisioningLoginActivity.java +++ b/app/src/main/java/org/linphone/assistant/RemoteProvisioningLoginActivity.java @@ -25,13 +25,12 @@ import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; - import org.linphone.LinphoneManager; -import org.linphone.settings.LinphonePreferences; import org.linphone.R; import org.linphone.core.ConfiguringState; import org.linphone.core.Core; import org.linphone.core.CoreListenerStub; +import org.linphone.settings.LinphonePreferences; import org.linphone.xmlrpc.XmlRpcHelper; import org.linphone.xmlrpc.XmlRpcListenerBase; @@ -58,20 +57,28 @@ public class RemoteProvisioningLoginActivity extends Activity implements OnClick domain.setEnabled(false); } - mListener = new CoreListenerStub() { - @Override - public void onConfiguringStatus(Core lc, final ConfiguringState state, String message) { - if (state == ConfiguringState.Successful) { - //TODO - } else if (state == ConfiguringState.Failed) { - Toast.makeText(RemoteProvisioningLoginActivity.this, R.string.remote_provisioning_failure, Toast.LENGTH_LONG).show(); - } - } - }; + mListener = + new CoreListenerStub() { + @Override + public void onConfiguringStatus( + Core lc, final ConfiguringState state, String message) { + if (state == ConfiguringState.Successful) { + // TODO + } else if (state == ConfiguringState.Failed) { + Toast.makeText( + RemoteProvisioningLoginActivity.this, + R.string.remote_provisioning_failure, + Toast.LENGTH_LONG) + .show(); + } + } + }; } private void cancelWizard(boolean bypassCheck) { - if (bypassCheck || getResources().getBoolean(R.bool.allow_cancel_remote_provisioning_login_activity)) { + if (bypassCheck + || getResources() + .getBoolean(R.bool.allow_cancel_remote_provisioning_login_activity)) { LinphonePreferences.instance().disableProvisioningLoginView(); setResult(bypassCheck ? Activity.RESULT_OK : Activity.RESULT_CANCELED); finish(); @@ -80,13 +87,17 @@ public class RemoteProvisioningLoginActivity extends Activity implements OnClick private boolean storeAccount(String username, String password, String domain) { XmlRpcHelper xmlRpcHelper = new XmlRpcHelper(); - xmlRpcHelper.getRemoteProvisioningFilenameAsync(new XmlRpcListenerBase() { - @Override - public void onRemoteProvisioningFilenameSent(String result) { - LinphonePreferences.instance().setRemoteProvisioningUrl(result); - LinphoneManager.getInstance().restartCore(); - } - }, username.toString(), password.toString(), domain.toString()); + xmlRpcHelper.getRemoteProvisioningFilenameAsync( + new XmlRpcListenerBase() { + @Override + public void onRemoteProvisioningFilenameSent(String result) { + LinphonePreferences.instance().setRemoteProvisioningUrl(result); + LinphoneManager.getInstance().restartCore(); + } + }, + username.toString(), + password.toString(), + domain.toString()); LinphonePreferences.instance().firstLaunchSuccessful(); setResult(Activity.RESULT_OK); @@ -120,7 +131,10 @@ public class RemoteProvisioningLoginActivity extends Activity implements OnClick cancelWizard(false); } if (id == R.id.assistant_connect) { - storeAccount(login.getText().toString(), password.getText().toString(), domain.getText().toString()); + storeAccount( + login.getText().toString(), + password.getText().toString(), + domain.getText().toString()); } } diff --git a/app/src/main/java/org/linphone/assistant/WelcomeFragment.java b/app/src/main/java/org/linphone/assistant/WelcomeFragment.java index 8440b409f..08fbf265a 100644 --- a/app/src/main/java/org/linphone/assistant/WelcomeFragment.java +++ b/app/src/main/java/org/linphone/assistant/WelcomeFragment.java @@ -25,15 +25,14 @@ import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; - import org.linphone.R; public class WelcomeFragment extends Fragment implements OnClickListener { private Button createAccount, logLinphoneAccount, logGenericAccount, remoteProvisioning; @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.assistant_welcome, container, false); createAccount = view.findViewById(R.id.create_account); diff --git a/app/src/main/java/org/linphone/call/BandwidthManager.java b/app/src/main/java/org/linphone/call/BandwidthManager.java index d6d47e459..632747408 100644 --- a/app/src/main/java/org/linphone/call/BandwidthManager.java +++ b/app/src/main/java/org/linphone/call/BandwidthManager.java @@ -32,12 +32,6 @@ public class BandwidthManager { private int currentProfile = HIGH_RESOLUTION; - public static final synchronized BandwidthManager getInstance() { - if (instance == null) instance = new BandwidthManager(); - return instance; - } - - private BandwidthManager() { // FIXME register a listener on NetworkManager to get notified of network state // FIXME register a listener on Preference to get notified of change in video enable value @@ -45,6 +39,10 @@ public class BandwidthManager { // FIXME initially get those values } + public static final synchronized BandwidthManager getInstance() { + if (instance == null) instance = new BandwidthManager(); + return instance; + } public void updateWithProfileSettings(Core lc, CallParams callParams) { if (callParams != null) { // in call diff --git a/app/src/main/java/org/linphone/call/CallActivity.java b/app/src/main/java/org/linphone/call/CallActivity.java index 4f569a441..7ee085003 100644 --- a/app/src/main/java/org/linphone/call/CallActivity.java +++ b/app/src/main/java/org/linphone/call/CallActivity.java @@ -36,9 +36,6 @@ import android.os.Bundle; import android.os.CountDownTimer; import android.os.Handler; import android.os.SystemClock; -import androidx.core.app.ActivityCompat; -import androidx.core.content.ContextCompat; -import androidx.drawerlayout.widget.DrawerLayout; import android.text.Html; import android.view.Gravity; import android.view.KeyEvent; @@ -57,14 +54,18 @@ import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; - -import org.linphone.LinphoneManager; -import org.linphone.settings.LinphonePreferences; -import org.linphone.utils.ImageUtils; -import org.linphone.utils.LinphoneUtils; -import org.linphone.R; +import androidx.core.app.ActivityCompat; +import androidx.core.content.ContextCompat; +import androidx.drawerlayout.widget.DrawerLayout; +import java.text.DecimalFormat; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Timer; +import java.util.TimerTask; import org.linphone.LinphoneActivity; -import org.linphone.utils.LinphoneGenericActivity; +import org.linphone.LinphoneManager; +import org.linphone.R; import org.linphone.contacts.ContactsManager; import org.linphone.contacts.LinphoneContact; import org.linphone.core.Address; @@ -86,45 +87,59 @@ import org.linphone.fragments.StatusFragment; import org.linphone.mediastream.Log; import org.linphone.mediastream.video.capture.hwconf.AndroidCameraConfiguration; import org.linphone.receivers.BluetoothManager; +import org.linphone.settings.LinphonePreferences; +import org.linphone.utils.ImageUtils; +import org.linphone.utils.LinphoneGenericActivity; +import org.linphone.utils.LinphoneUtils; import org.linphone.views.Numpad; -import java.text.DecimalFormat; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Timer; -import java.util.TimerTask; - -public class CallActivity extends LinphoneGenericActivity implements OnClickListener, ActivityCompat.OnRequestPermissionsResultCallback { - private final static int SECONDS_BEFORE_HIDING_CONTROLS = 4000; - private final static int SECONDS_BEFORE_DENYING_CALL_UPDATE = 30000; +public class CallActivity extends LinphoneGenericActivity + implements OnClickListener, ActivityCompat.OnRequestPermissionsResultCallback { + private static final int SECONDS_BEFORE_HIDING_CONTROLS = 4000; + private static final int SECONDS_BEFORE_DENYING_CALL_UPDATE = 30000; private static final int PERMISSIONS_REQUEST_CAMERA = 202; private static final int PERMISSIONS_ENABLED_CAMERA = 203; private static final int PERMISSIONS_ENABLED_MIC = 204; private static final int PERMISSIONS_EXTERNAL_STORAGE = 205; private static CallActivity instance; - + private static long TimeRemind = 0; private Handler mControlsHandler = new Handler(); private Runnable mControls; private ImageView switchCamera; private TextView missedChats; private RelativeLayout mActiveCallHeader, sideMenuContent, avatar_layout; - private ImageView pause, hangUp, dialer, video, micro, speaker, options, addCall, transfer, conference, conferenceStatus, contactPicture, recordCall, recording; + private ImageView pause, + hangUp, + dialer, + video, + micro, + speaker, + options, + addCall, + transfer, + conference, + conferenceStatus, + contactPicture, + recordCall, + recording; private ImageView audioRoute, routeSpeaker, routeEarpiece, routeBluetooth, menu, chat; private LinearLayout mNoCurrentCall, callInfo, mCallPaused; private ProgressBar videoProgress; private StatusFragment status; private CallAudioFragment audioCallFragment; private CallVideoFragment videoCallFragment; - private boolean isSpeakerEnabled = false, isMicMuted = false, isTransferAllowed, isVideoAsk, isRecording = false; + private boolean isSpeakerEnabled = false, + isMicMuted = false, + isTransferAllowed, + isVideoAsk, + isRecording = false; private LinearLayout mControlsLayout; private Numpad numpad; private int cameraNumber; private CountDownTimer timer; private boolean isVideoCallPaused = false; private Dialog dialog = null; - private static long TimeRemind = 0; private HeadsetReceiver headsetReceiver; private LinearLayout callsList, conferenceList; @@ -161,94 +176,113 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } - getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); + getWindow() + .addFlags( + WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON + | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); setContentView(R.layout.call); - //Earset Connectivity Broadcast Processing + // Earset Connectivity Broadcast Processing IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("android.intent.action.HEADSET_PLUG"); headsetReceiver = new HeadsetReceiver(); registerReceiver(headsetReceiver, intentFilter); - isTransferAllowed = getApplicationContext().getResources().getBoolean(R.bool.allow_transfers); + isTransferAllowed = + getApplicationContext().getResources().getBoolean(R.bool.allow_transfers); cameraNumber = AndroidCameraConfiguration.retrieveCameras().length; mEncoderTexts = new HashMap<>(); mDecoderTexts = new HashMap<>(); - mListener = new CoreListenerStub() { - @Override - public void onMessageReceived(Core lc, ChatRoom cr, ChatMessage message) { - displayMissedChats(); - } - - @Override - public void onCallStateChanged(Core lc, final Call call, Call.State state, String message) { - if (LinphoneManager.getLc().getCallsNb() == 0) { - finish(); - return; - } - - if (state == State.IncomingReceived) { - startIncomingCallActivity(); - return; - } else if (state == State.Paused || state == State.PausedByRemote || state == State.Pausing) { - if (LinphoneManager.getLc().getCurrentCall() != null) { - video.setEnabled(false); + mListener = + new CoreListenerStub() { + @Override + public void onMessageReceived(Core lc, ChatRoom cr, ChatMessage message) { + displayMissedChats(); } - if (isVideoEnabled(call)) { - showAudioView(); + + @Override + public void onCallStateChanged( + Core lc, final Call call, Call.State state, String message) { + if (LinphoneManager.getLc().getCallsNb() == 0) { + finish(); + return; + } + + if (state == State.IncomingReceived) { + startIncomingCallActivity(); + return; + } else if (state == State.Paused + || state == State.PausedByRemote + || state == State.Pausing) { + if (LinphoneManager.getLc().getCurrentCall() != null) { + video.setEnabled(false); + } + if (isVideoEnabled(call)) { + showAudioView(); + } + } else if (state == State.Resuming) { + if (LinphonePreferences.instance().isVideoEnabled()) { + status.refreshStatusItems(call, isVideoEnabled(call)); + if (call.getCurrentParams().videoEnabled()) { + showVideoView(); + } + } + if (LinphoneManager.getLc().getCurrentCall() != null) { + video.setEnabled(true); + } + } else if (state == State.StreamsRunning) { + switchVideo(isVideoEnabled(call)); + enableAndRefreshInCallActions(); + + if (status != null) { + videoProgress.setVisibility(View.GONE); + status.refreshStatusItems(call, isVideoEnabled(call)); + } + } else if (state == State.UpdatedByRemote) { + // If the correspondent proposes video while audio call + boolean videoEnabled = LinphonePreferences.instance().isVideoEnabled(); + if (!videoEnabled) { + acceptCallUpdate(false); + } + + boolean remoteVideo = call.getRemoteParams().videoEnabled(); + boolean localVideo = call.getCurrentParams().videoEnabled(); + boolean autoAcceptCameraPolicy = + LinphonePreferences.instance() + .shouldAutomaticallyAcceptVideoRequests(); + if (remoteVideo + && !localVideo + && !autoAcceptCameraPolicy + && !LinphoneManager.getLc().isInConference()) { + showAcceptCallUpdateDialog(); + createTimerForDialog(SECONDS_BEFORE_DENYING_CALL_UPDATE); + } + } + + refreshIncallUi(); + transfer.setEnabled(LinphoneManager.getLc().getCurrentCall() != null); } - } else if (state == State.Resuming) { - if (LinphonePreferences.instance().isVideoEnabled()) { - status.refreshStatusItems(call, isVideoEnabled(call)); - if (call.getCurrentParams().videoEnabled()) { - showVideoView(); + + @Override + public void onCallEncryptionChanged( + Core lc, + final Call call, + boolean encrypted, + String authenticationToken) { + if (status != null) { + if (call.getCurrentParams() + .getMediaEncryption() + .equals(MediaEncryption.ZRTP) + && !call.getAuthenticationTokenVerified()) { + status.showZRTPDialog(call); + } + status.refreshStatusItems(call, call.getCurrentParams().videoEnabled()); } } - if (LinphoneManager.getLc().getCurrentCall() != null) { - video.setEnabled(true); - } - } else if (state == State.StreamsRunning) { - switchVideo(isVideoEnabled(call)); - enableAndRefreshInCallActions(); - - if (status != null) { - videoProgress.setVisibility(View.GONE); - status.refreshStatusItems(call, isVideoEnabled(call)); - } - } else if (state == State.UpdatedByRemote) { - // If the correspondent proposes video while audio call - boolean videoEnabled = LinphonePreferences.instance().isVideoEnabled(); - if (!videoEnabled) { - acceptCallUpdate(false); - } - - boolean remoteVideo = call.getRemoteParams().videoEnabled(); - boolean localVideo = call.getCurrentParams().videoEnabled(); - boolean autoAcceptCameraPolicy = LinphonePreferences.instance().shouldAutomaticallyAcceptVideoRequests(); - if (remoteVideo && !localVideo && !autoAcceptCameraPolicy && !LinphoneManager.getLc().isInConference()) { - showAcceptCallUpdateDialog(); - createTimerForDialog(SECONDS_BEFORE_DENYING_CALL_UPDATE); - } - } - - refreshIncallUi(); - transfer.setEnabled(LinphoneManager.getLc().getCurrentCall() != null); - } - - @Override - public void onCallEncryptionChanged(Core lc, final Call call, boolean encrypted, String authenticationToken) { - if (status != null) { - if (call.getCurrentParams().getMediaEncryption().equals(MediaEncryption.ZRTP) && !call.getAuthenticationTokenVerified()) { - status.showZRTPDialog(call); - } - status.refreshStatusItems(call, call.getCurrentParams().videoEnabled()); - } - } - - }; + }; if (findViewById(R.id.fragmentContainer) != null) { initUI(); @@ -261,7 +295,8 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList } } if (savedInstanceState != null) { - // Fragment already created, no need to create it again (else it will generate a memory leak with duplicated fragments) + // Fragment already created, no need to create it again (else it will generate a + // memory leak with duplicated fragments) isSpeakerEnabled = savedInstanceState.getBoolean("Speaker"); isMicMuted = savedInstanceState.getBoolean("Mic"); isVideoCallPaused = savedInstanceState.getBoolean("VideoCallPaused"); @@ -294,24 +329,28 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList } callFragment.setArguments(getIntent().getExtras()); - getFragmentManager().beginTransaction().add(R.id.fragmentContainer, callFragment).commitAllowingStateLoss(); + getFragmentManager() + .beginTransaction() + .add(R.id.fragmentContainer, callFragment) + .commitAllowingStateLoss(); } } public void createTimerForDialog(long time) { - timer = new CountDownTimer(time, 1000) { - public void onTick(long millisUntilFinished) { - TimeRemind = millisUntilFinished; - } + timer = + new CountDownTimer(time, 1000) { + public void onTick(long millisUntilFinished) { + TimeRemind = millisUntilFinished; + } - public void onFinish() { - if (dialog != null) { - dialog.dismiss(); - dialog = null; - } - acceptCallUpdate(false); - } - }.start(); + public void onFinish() { + if (dialog != null) { + dialog.dismiss(); + dialog = null; + } + acceptCallUpdate(false); + } + }.start(); } private boolean isVideoEnabled(Call call) { @@ -342,7 +381,7 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList callsList = findViewById(R.id.calls_list); conferenceList = findViewById(R.id.conference_list); - //TopBar + // TopBar video = findViewById(R.id.video); video.setOnClickListener(this); video.setEnabled(false); @@ -360,7 +399,7 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList options.setOnClickListener(this); options.setEnabled(false); - //BottonBar + // BottonBar hangUp = findViewById(R.id.hang_up); hangUp.setOnClickListener(this); @@ -374,9 +413,9 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList chat.setOnClickListener(this); missedChats = findViewById(R.id.missed_chats); - //Others + // Others - //Active Call + // Active Call callInfo = findViewById(R.id.active_call_info); pause = findViewById(R.id.pause); @@ -390,7 +429,7 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList contactPicture = findViewById(R.id.contact_picture); avatar_layout = findViewById(R.id.avatar_layout); - //Options + // Options addCall = findViewById(R.id.add_call); addCall.setOnClickListener(this); addCall.setEnabled(false); @@ -456,58 +495,77 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList public void checkAndRequestPermission(String permission, int result) { int permissionGranted = getPackageManager().checkPermission(permission, getPackageName()); - Log.i("[Permission] " + permission + " is " + (permissionGranted == PackageManager.PERMISSION_GRANTED ? "granted" : "denied")); + Log.i( + "[Permission] " + + permission + + " is " + + (permissionGranted == PackageManager.PERMISSION_GRANTED + ? "granted" + : "denied")); if (permissionGranted != PackageManager.PERMISSION_GRANTED) { - if (LinphonePreferences.instance().firstTimeAskingForPermission(permission) || ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) { + if (LinphonePreferences.instance().firstTimeAskingForPermission(permission) + || ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) { Log.i("[Permission] Asking for " + permission); - ActivityCompat.requestPermissions(this, new String[]{permission}, result); + ActivityCompat.requestPermissions(this, new String[] {permission}, result); } } } @Override - public void onRequestPermissionsResult(int requestCode, String[] permissions, final int[] grantResults) { + public void onRequestPermissionsResult( + int requestCode, String[] permissions, final int[] grantResults) { for (int i = 0; i < permissions.length; i++) { - Log.i("[Permission] " + permissions[i] + " is " + (grantResults[i] == PackageManager.PERMISSION_GRANTED ? "granted" : "denied")); + Log.i( + "[Permission] " + + permissions[i] + + " is " + + (grantResults[i] == PackageManager.PERMISSION_GRANTED + ? "granted" + : "denied")); } switch (requestCode) { case PERMISSIONS_REQUEST_CAMERA: - LinphoneUtils.dispatchOnUIThread(new Runnable() { - @Override - public void run() { - acceptCallUpdate(grantResults[0] == PackageManager.PERMISSION_GRANTED); - } - }); + LinphoneUtils.dispatchOnUIThread( + new Runnable() { + @Override + public void run() { + acceptCallUpdate( + grantResults[0] == PackageManager.PERMISSION_GRANTED); + } + }); break; case PERMISSIONS_ENABLED_CAMERA: - LinphoneUtils.dispatchOnUIThread(new Runnable() { - @Override - public void run() { - disableVideo(grantResults[0] != PackageManager.PERMISSION_GRANTED); - } - }); + LinphoneUtils.dispatchOnUIThread( + new Runnable() { + @Override + public void run() { + disableVideo(grantResults[0] != PackageManager.PERMISSION_GRANTED); + } + }); break; case PERMISSIONS_ENABLED_MIC: - LinphoneUtils.dispatchOnUIThread(new Runnable() { - @Override - public void run() { - if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { - toggleMicro(); - } - } - }); + LinphoneUtils.dispatchOnUIThread( + new Runnable() { + @Override + public void run() { + if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { + toggleMicro(); + } + } + }); break; case PERMISSIONS_EXTERNAL_STORAGE: - LinphoneUtils.dispatchOnUIThread(new Runnable() { - @Override - public void run() { - if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { - toggleCallRecording(!isRecording); - } - } - }); + LinphoneUtils.dispatchOnUIThread( + new Runnable() { + @Override + public void run() { + if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { + toggleCallRecording(!isRecording); + } + } + }); } } @@ -517,16 +575,17 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList sideMenuContent = findViewById(R.id.side_menu_content); - menu.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View view) { - if (sideMenu.isDrawerVisible(Gravity.LEFT)) { - sideMenu.closeDrawer(sideMenuContent); - } else { - sideMenu.openDrawer(sideMenuContent); - } - } - }); + menu.setOnClickListener( + new OnClickListener() { + @Override + public void onClick(View view) { + if (sideMenu.isDrawerVisible(Gravity.LEFT)) { + sideMenu.closeDrawer(sideMenuContent); + } else { + sideMenu.openDrawer(sideMenuContent); + } + } + }); Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull(); if (lc != null) { @@ -560,13 +619,15 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList video.setSelected(false); } } - if (getPackageManager().checkPermission(Manifest.permission.CAMERA, getPackageName()) != PackageManager.PERMISSION_GRANTED) { + if (getPackageManager().checkPermission(Manifest.permission.CAMERA, getPackageName()) + != PackageManager.PERMISSION_GRANTED) { video.setSelected(false); } speaker.setSelected(isSpeakerEnabled); - if (getPackageManager().checkPermission(Manifest.permission.RECORD_AUDIO, getPackageName()) != PackageManager.PERMISSION_GRANTED) { + if (getPackageManager().checkPermission(Manifest.permission.RECORD_AUDIO, getPackageName()) + != PackageManager.PERMISSION_GRANTED) { isMicMuted = true; } micro.setSelected(isMicMuted); @@ -597,28 +658,42 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList int confsize = 0; if (LinphoneManager.getLc().isInConference()) { - confsize = LinphoneManager.getLc().getConferenceSize() - (LinphoneManager.getLc().getConference() != null ? 1 : 0); + confsize = + LinphoneManager.getLc().getConferenceSize() + - (LinphoneManager.getLc().getConference() != null ? 1 : 0); } - //Enabled transfer button + // Enabled transfer button transfer.setEnabled(isTransferAllowed && !LinphoneManager.getLc().soundResourcesLocked()); - //Enable conference button - conference.setEnabled(LinphoneManager.getLc().getCallsNb() > 1 && LinphoneManager.getLc().getCallsNb() > confsize && !LinphoneManager.getLc().soundResourcesLocked()); + // Enable conference button + conference.setEnabled( + LinphoneManager.getLc().getCallsNb() > 1 + && LinphoneManager.getLc().getCallsNb() > confsize + && !LinphoneManager.getLc().soundResourcesLocked()); - addCall.setEnabled(LinphoneManager.getLc().getCallsNb() < LinphoneManager.getLc().getMaxCalls() && !LinphoneManager.getLc().soundResourcesLocked()); - options.setEnabled(!getResources().getBoolean(R.bool.disable_options_in_call) && (addCall.isEnabled() || transfer.isEnabled())); + addCall.setEnabled( + LinphoneManager.getLc().getCallsNb() < LinphoneManager.getLc().getMaxCalls() + && !LinphoneManager.getLc().soundResourcesLocked()); + options.setEnabled( + !getResources().getBoolean(R.bool.disable_options_in_call) + && (addCall.isEnabled() || transfer.isEnabled())); recordCall.setEnabled(!LinphoneManager.getLc().soundResourcesLocked()); - recordCall.setImageResource(isRecording ? R.drawable.options_rec_selected : R.drawable.options_rec_default); + recordCall.setImageResource( + isRecording ? R.drawable.options_rec_selected : R.drawable.options_rec_default); recording.setEnabled(isRecording); recording.setVisibility(isRecording ? View.VISIBLE : View.GONE); + video.setEnabled( + LinphoneManager.getLc().getCurrentCall() != null + && LinphonePreferences.instance().isVideoEnabled() + && !LinphoneManager.getLc().getCurrentCall().mediaInProgress()); - video.setEnabled(LinphoneManager.getLc().getCurrentCall() != null && LinphonePreferences.instance().isVideoEnabled() && !LinphoneManager.getLc().getCurrentCall().mediaInProgress()); - - pause.setEnabled(LinphoneManager.getLc().getCurrentCall() != null && !LinphoneManager.getLc().getCurrentCall().mediaInProgress()); + pause.setEnabled( + LinphoneManager.getLc().getCurrentCall() != null + && !LinphoneManager.getLc().getCurrentCall().mediaInProgress()); micro.setEnabled(true); speaker.setEnabled(!isTablet()); @@ -636,40 +711,58 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList int id = v.getId(); if (isVideoEnabled(LinphoneManager.getLc().getCurrentCall())) { - //displayVideoCallControlsIfHidden(); + // displayVideoCallControlsIfHidden(); } if (id == R.id.video) { - int camera = getPackageManager().checkPermission(Manifest.permission.CAMERA, getPackageName()); - Log.i("[Permission] Camera permission is " + (camera == PackageManager.PERMISSION_GRANTED ? "granted" : "denied")); + int camera = + getPackageManager() + .checkPermission(Manifest.permission.CAMERA, getPackageName()); + Log.i( + "[Permission] Camera permission is " + + (camera == PackageManager.PERMISSION_GRANTED ? "granted" : "denied")); if (camera == PackageManager.PERMISSION_GRANTED) { disableVideo(isVideoEnabled(LinphoneManager.getLc().getCurrentCall())); } else { checkAndRequestPermission(Manifest.permission.CAMERA, PERMISSIONS_ENABLED_CAMERA); - } } else if (id == R.id.micro) { - int recordAudio = getPackageManager().checkPermission(Manifest.permission.RECORD_AUDIO, getPackageName()); - Log.i("[Permission] Record audio permission is " + (recordAudio == PackageManager.PERMISSION_GRANTED ? "granted" : "denied")); + int recordAudio = + getPackageManager() + .checkPermission(Manifest.permission.RECORD_AUDIO, getPackageName()); + Log.i( + "[Permission] Record audio permission is " + + (recordAudio == PackageManager.PERMISSION_GRANTED + ? "granted" + : "denied")); if (recordAudio == PackageManager.PERMISSION_GRANTED) { toggleMicro(); } else { - checkAndRequestPermission(Manifest.permission.RECORD_AUDIO, PERMISSIONS_ENABLED_MIC); + checkAndRequestPermission( + Manifest.permission.RECORD_AUDIO, PERMISSIONS_ENABLED_MIC); } } else if (id == R.id.speaker) { toggleSpeaker(); } else if (id == R.id.add_call) { goBackToDialer(); } else if (id == R.id.record_call) { - int externalStorage = getPackageManager().checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, getPackageName()); - Log.i("[Permission] External storage permission is " + (externalStorage == PackageManager.PERMISSION_GRANTED ? "granted" : "denied")); + int externalStorage = + getPackageManager() + .checkPermission( + Manifest.permission.WRITE_EXTERNAL_STORAGE, getPackageName()); + Log.i( + "[Permission] External storage permission is " + + (externalStorage == PackageManager.PERMISSION_GRANTED + ? "granted" + : "denied")); if (externalStorage == PackageManager.PERMISSION_GRANTED) { toggleCallRecording(!isRecording); } else { - checkAndRequestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, PERMISSIONS_EXTERNAL_STORAGE); + checkAndRequestPermission( + Manifest.permission.WRITE_EXTERNAL_STORAGE, PERMISSIONS_EXTERNAL_STORAGE); } } else if (id == R.id.recording) { toggleCallRecording(false); @@ -792,7 +885,7 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList return; } - //Check if the call is not terminated + // Check if the call is not terminated if (call.getState() == State.End || call.getState() == State.Released) return; if (!displayVideo) { @@ -800,8 +893,7 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList } else { if (!call.getRemoteParams().lowBandwidthEnabled()) { LinphoneManager.getInstance().addVideo(); - if (videoCallFragment == null || !videoCallFragment.isVisible()) - showVideoView(); + if (videoCallFragment == null || !videoCallFragment.isVisible()) showVideoView(); } else { displayCustomToast(getString(R.string.error_low_bandwidth), Toast.LENGTH_LONG); } @@ -871,7 +963,7 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList } private void replaceFragmentAudioByVideo() { -// Hiding controls to let displayVideoCallControlsIfHidden add them plus the callback + // Hiding controls to let displayVideoCallControlsIfHidden add them plus the callback videoCallFragment = new CallVideoFragment(); FragmentTransaction transaction = getFragmentManager().beginTransaction(); @@ -894,8 +986,7 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList if (LinphoneManager.getLc().getCurrentCall() != null) { if (isVideoEnabled(LinphoneManager.getLc().getCurrentCall())) LinphoneManager.getInstance().enableProximitySensing(false); - else - LinphoneManager.getInstance().enableProximitySensing(!isSpeakerEnabled); + else LinphoneManager.getInstance().enableProximitySensing(!isSpeakerEnabled); } speaker.setSelected(isSpeakerEnabled); if (isSpeakerEnabled) { @@ -963,7 +1054,6 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList } } - public void displayVideoCallControlsIfHidden() { if (mControlsLayout != null) { if (mControlsLayout.getVisibility() != View.VISIBLE) { @@ -980,19 +1070,22 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList mControls = null; if (isVideoEnabled(LinphoneManager.getLc().getCurrentCall()) && mControlsHandler != null) { - mControlsHandler.postDelayed(mControls = new Runnable() { - public void run() { - hideNumpad(); - video.setEnabled(true); - transfer.setVisibility(View.INVISIBLE); - addCall.setVisibility(View.INVISIBLE); - conference.setVisibility(View.INVISIBLE); - recordCall.setVisibility(View.INVISIBLE); - displayVideoCall(false); - numpad.setVisibility(View.GONE); - options.setSelected(false); - } - }, SECONDS_BEFORE_HIDING_CONTROLS); + mControlsHandler.postDelayed( + mControls = + new Runnable() { + public void run() { + hideNumpad(); + video.setEnabled(true); + transfer.setVisibility(View.INVISIBLE); + addCall.setVisibility(View.INVISIBLE); + conference.setVisibility(View.INVISIBLE); + recordCall.setVisibility(View.INVISIBLE); + displayVideoCall(false); + numpad.setVisibility(View.GONE); + options.setSelected(false); + } + }, + SECONDS_BEFORE_HIDING_CONTROLS); } } @@ -1040,7 +1133,7 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList } private void hideOrDisplayCallOptions() { - //Hide options + // Hide options if (addCall.getVisibility() == View.VISIBLE) { options.setSelected(false); if (isTransferAllowed) { @@ -1049,7 +1142,7 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList addCall.setVisibility(View.INVISIBLE); conference.setVisibility(View.INVISIBLE); recordCall.setVisibility(View.INVISIBLE); - } else { //Display options + } else { // Display options if (isTransferAllowed) { transfer.setVisibility(View.VISIBLE); } @@ -1126,10 +1219,10 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList status.getView().setVisibility(View.VISIBLE); } findViewById(R.id.status).setVisibility(View.VISIBLE); - //findViewById(R.id.fragmentContainer).setPadding(0, LinphoneUtils.pixelsToDpi(getResources(), 40), 0, 0); + // findViewById(R.id.fragmentContainer).setPadding(0, + // LinphoneUtils.pixelsToDpi(getResources(), 40), 0, 0); } - private void showAcceptCallUpdateDialog() { dialog = new Dialog(this); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); @@ -1139,7 +1232,10 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList Drawable d = new ColorDrawable(ContextCompat.getColor(this, R.color.colorC)); d.setAlpha(200); dialog.setContentView(R.layout.dialog); - dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT); + dialog.getWindow() + .setLayout( + WindowManager.LayoutParams.MATCH_PARENT, + WindowManager.LayoutParams.MATCH_PARENT); dialog.getWindow().setBackgroundDrawable(d); TextView customText = dialog.findViewById(R.id.customText); @@ -1152,34 +1248,44 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList cancel.setText(R.string.decline); isVideoAsk = true; - accept.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View view) { - int camera = getPackageManager().checkPermission(Manifest.permission.CAMERA, getPackageName()); - Log.i("[Permission] Camera permission is " + (camera == PackageManager.PERMISSION_GRANTED ? "granted" : "denied")); + accept.setOnClickListener( + new OnClickListener() { + @Override + public void onClick(View view) { + int camera = + getPackageManager() + .checkPermission( + Manifest.permission.CAMERA, getPackageName()); + Log.i( + "[Permission] Camera permission is " + + (camera == PackageManager.PERMISSION_GRANTED + ? "granted" + : "denied")); - if (camera == PackageManager.PERMISSION_GRANTED) { - CallActivity.instance().acceptCallUpdate(true); - } else { - checkAndRequestPermission(Manifest.permission.CAMERA, PERMISSIONS_REQUEST_CAMERA); - } - isVideoAsk = false; - dialog.dismiss(); - dialog = null; - } - }); + if (camera == PackageManager.PERMISSION_GRANTED) { + CallActivity.instance().acceptCallUpdate(true); + } else { + checkAndRequestPermission( + Manifest.permission.CAMERA, PERMISSIONS_REQUEST_CAMERA); + } + isVideoAsk = false; + dialog.dismiss(); + dialog = null; + } + }); - cancel.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View view) { - if (CallActivity.isInstanciated()) { - CallActivity.instance().acceptCallUpdate(false); - } - isVideoAsk = false; - dialog.dismiss(); - dialog = null; - } - }); + cancel.setOnClickListener( + new OnClickListener() { + @Override + public void onClick(View view) { + if (CallActivity.isInstanciated()) { + CallActivity.instance().acceptCallUpdate(false); + } + isVideoAsk = false; + dialog.dismiss(); + dialog = null; + } + }); dialog.show(); } @@ -1221,22 +1327,21 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList Player player = call.getPlayer(); String path = intent.getData().getPath(); Log.i("Openning " + path); - /*int openRes = */ - player.open(path); - /*if(openRes == -1) { - String message = "Could not open " + path; - Log.e(message); - Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show(); - return; - }*/ + /*int openRes = */ player.open(path); + /*if(openRes == -1) { + String message = "Could not open " + path; + Log.e(message); + Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show(); + return; + }*/ Log.i("Start playing"); /*if(*/ - player.start()/* == -1) {*/; - /*player.close(); - String message = "Could not start playing " + path; - Log.e(message); - Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show(); - }*/ + player.start() /* == -1) {*/; + /*player.close(); + String message = "Could not start playing " + path; + Log.e(message); + Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show(); + }*/ } } } @@ -1318,8 +1423,7 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList videoCallFragment = fragment; } - - //CALL INFORMATION + // CALL INFORMATION private void displayCurrentCall(Call call) { Address lAddress = call.getRemoteAddress(); TextView contactName = findViewById(R.id.current_contact_name); @@ -1332,16 +1436,20 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList LinearLayout callView; if (call == null) { - callView = (LinearLayout) inflater.inflate(R.layout.conference_paused_row, container, false); + callView = + (LinearLayout) + inflater.inflate(R.layout.conference_paused_row, container, false); callView.setId(index + 1); - callView.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View view) { - pauseOrResumeConference(); - } - }); + callView.setOnClickListener( + new OnClickListener() { + @Override + public void onClick(View view) { + pauseOrResumeConference(); + } + }); } else { - callView = (LinearLayout) inflater.inflate(R.layout.call_inactive_row, container, false); + callView = + (LinearLayout) inflater.inflate(R.layout.call_inactive_row, container, false); callView.setId(index + 1); TextView contactName = callView.findViewById(R.id.contact_name); @@ -1355,14 +1463,19 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList callsList.addView(callView); } - private void setContactInformation(TextView contactName, ImageView contactPicture, Address lAddress) { + private void setContactInformation( + TextView contactName, ImageView contactPicture, Address lAddress) { LinphoneContact lContact = ContactsManager.getInstance().findContactFromAddress(lAddress); if (lContact == null) { contactName.setText(LinphoneUtils.getAddressDisplayName(lAddress)); contactPicture.setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap()); } else { contactName.setText(lContact.getFullName()); - ImageUtils.setImagePictureFromUri(contactPicture.getContext(), contactPicture, lContact.getPhotoUri(), lContact.getThumbnailUri()); + ImageUtils.setImagePictureFromUri( + contactPicture.getContext(), + contactPicture, + lContact.getPhotoUri(), + lContact.getThumbnailUri()); } } @@ -1372,11 +1485,15 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList onCallStateChanged.setTag(call); onCallStateChanged.setOnClickListener(this); - if (call.getState() == State.Paused || call.getState() == State.PausedByRemote || call.getState() == State.Pausing) { + if (call.getState() == State.Paused + || call.getState() == State.PausedByRemote + || call.getState() == State.Pausing) { onCallStateChanged.setSelected(false); isCallPaused = true; isInConference = false; - } else if (call.getState() == State.OutgoingInit || call.getState() == State.OutgoingProgress || call.getState() == State.OutgoingRinging) { + } else if (call.getState() == State.OutgoingInit + || call.getState() == State.OutgoingProgress + || call.getState() == State.OutgoingRinging) { isCallPaused = false; isInConference = false; } else { @@ -1410,17 +1527,21 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList public void refreshCallList(Resources resources) { isConferenceRunning = LinphoneManager.getLc().isInConference(); - List pausedCalls = LinphoneUtils.getCallsInState(LinphoneManager.getLc(), Arrays.asList(State.PausedByRemote)); + List pausedCalls = + LinphoneUtils.getCallsInState( + LinphoneManager.getLc(), Arrays.asList(State.PausedByRemote)); - //MultiCalls + // MultiCalls if (LinphoneManager.getLc().getCallsNb() > 1) { callsList.setVisibility(View.VISIBLE); } - //Active call + // Active call if (LinphoneManager.getLc().getCurrentCall() != null) { displayNoCurrentCall(false); - if (isVideoEnabled(LinphoneManager.getLc().getCurrentCall()) && !isConferenceRunning && pausedCalls.size() == 0) { + if (isVideoEnabled(LinphoneManager.getLc().getCurrentCall()) + && !isConferenceRunning + && pausedCalls.size() == 0) { displayVideoCall(false); } else { displayAudioCall(); @@ -1433,7 +1554,7 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList } } - //Conference + // Conference if (isConferenceRunning) { displayConference(true); } else { @@ -1455,7 +1576,8 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList isConfPaused = true; index++; } else { - if (call != LinphoneManager.getLc().getCurrentCall() && !(call.getConference() != null)) { + if (call != LinphoneManager.getLc().getCurrentCall() + && !(call.getConference() != null)) { displayPausedCalls(resources, call, index); index++; } else { @@ -1469,12 +1591,10 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList callsList.setVisibility(View.VISIBLE); displayPausedCalls(resources, null, index); } - } - } - //Paused by remote + // Paused by remote if (pausedCalls.size() == 1) { displayCallPaused(true); } else { @@ -1482,7 +1602,7 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList } } - //Conference + // Conference private void exitConference(final Call call) { Core lc = LinphoneManager.getLc(); @@ -1515,11 +1635,13 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList } private void displayConferenceParticipant(int index, final Call call) { - LinearLayout confView = (LinearLayout) inflater.inflate(R.layout.conf_call_control_row, container, false); + LinearLayout confView = + (LinearLayout) inflater.inflate(R.layout.conf_call_control_row, container, false); conferenceList.setId(index + 1); TextView contact = confView.findViewById(R.id.contactNameOrNumber); - LinphoneContact lContact = ContactsManager.getInstance().findContactFromAddress(call.getRemoteAddress()); + LinphoneContact lContact = + ContactsManager.getInstance().findContactFromAddress(call.getRemoteAddress()); if (lContact == null) { contact.setText(call.getRemoteAddress().getUsername()); } else { @@ -1529,23 +1651,23 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList registerCallDurationTimer(confView, call); ImageView quitConference = confView.findViewById(R.id.quitConference); - quitConference.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View view) { - exitConference(call); - } - }); + quitConference.setOnClickListener( + new OnClickListener() { + @Override + public void onClick(View view) { + exitConference(call); + } + }); conferenceList.addView(confView); - } private void displayConferenceHeader() { conferenceList.setVisibility(View.VISIBLE); - RelativeLayout headerConference = (RelativeLayout) inflater.inflate(R.layout.conference_header, container, false); + RelativeLayout headerConference = + (RelativeLayout) inflater.inflate(R.layout.conference_header, container, false); conferenceStatus = headerConference.findViewById(R.id.conference_pause); conferenceStatus.setOnClickListener(this); conferenceList.addView(headerConference); - } private void displayConference(boolean isInConf) { @@ -1555,10 +1677,10 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList mNoCurrentCall.setVisibility(View.GONE); conferenceList.removeAllViews(); - //Conference Header + // Conference Header displayConferenceHeader(); - //Conference participant + // Conference participant int index = 1; for (Call call : LinphoneManager.getLc().getCalls()) { if (call.getConference() != null) { @@ -1592,7 +1714,8 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList private String getEncoderText(String mime) { String ret = mEncoderTexts.get(mime); if (ret == null) { - org.linphone.mediastream.Factory msfactory = LinphoneManager.getLc().getMediastreamerFactory(); + org.linphone.mediastream.Factory msfactory = + LinphoneManager.getLc().getMediastreamerFactory(); ret = msfactory.getEncoderText(mime); mEncoderTexts.put(mime, ret); } @@ -1602,19 +1725,36 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList private String getDecoderText(String mime) { String ret = mDecoderTexts.get(mime); if (ret == null) { - org.linphone.mediastream.Factory msfactory = LinphoneManager.getLc().getMediastreamerFactory(); + org.linphone.mediastream.Factory msfactory = + LinphoneManager.getLc().getMediastreamerFactory(); ret = msfactory.getDecoderText(mime); mDecoderTexts.put(mime, ret); } return ret; } - private void displayMediaStats(CallParams params, CallStats stats - , PayloadType media, View layout, TextView title, TextView codec, TextView dl - , TextView ul, TextView edl, TextView ice, TextView ip, TextView senderLossRate - , TextView receiverLossRate, TextView enc, TextView dec, TextView videoResolutionSent - , TextView videoResolutionReceived, TextView videoFpsSent, TextView videoFpsReceived - , boolean isVideo, TextView jitterBuffer) { + private void displayMediaStats( + CallParams params, + CallStats stats, + PayloadType media, + View layout, + TextView title, + TextView codec, + TextView dl, + TextView ul, + TextView edl, + TextView ice, + TextView ip, + TextView senderLossRate, + TextView receiverLossRate, + TextView enc, + TextView dec, + TextView videoResolutionSent, + TextView videoResolutionReceived, + TextView videoFpsSent, + TextView videoFpsReceived, + boolean isVideo, + TextView jitterBuffer) { if (stats != null) { String mime = null; @@ -1622,46 +1762,71 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList title.setVisibility(TextView.VISIBLE); if (media != null) { mime = media.getMimeType(); - formatText(codec, getString(R.string.call_stats_codec), + formatText( + codec, + getString(R.string.call_stats_codec), mime + " / " + (media.getClockRate() / 1000) + "kHz"); } if (mime != null) { formatText(enc, getString(R.string.call_stats_encoder_name), getEncoderText(mime)); formatText(dec, getString(R.string.call_stats_decoder_name), getDecoderText(mime)); } - formatText(dl, getString(R.string.call_stats_download), + formatText( + dl, + getString(R.string.call_stats_download), String.valueOf((int) stats.getDownloadBandwidth()) + " kbits/s"); - formatText(ul, getString(R.string.call_stats_upload), + formatText( + ul, + getString(R.string.call_stats_upload), String.valueOf((int) stats.getUploadBandwidth()) + " kbits/s"); if (isVideo) { - formatText(edl, getString(R.string.call_stats_estimated_download), + formatText( + edl, + getString(R.string.call_stats_estimated_download), String.valueOf(stats.getEstimatedDownloadBandwidth()) + " kbits/s"); } - formatText(ice, getString(R.string.call_stats_ice), - stats.getIceState().toString()); - formatText(ip, getString(R.string.call_stats_ip), - (stats.getIpFamilyOfRemote() == AddressFamily.Inet6) ? - "IpV6" : (stats.getIpFamilyOfRemote() == AddressFamily.Inet) ? - "IpV4" : "Unknown"); - formatText(senderLossRate, getString(R.string.call_stats_sender_loss_rate), + formatText(ice, getString(R.string.call_stats_ice), stats.getIceState().toString()); + formatText( + ip, + getString(R.string.call_stats_ip), + (stats.getIpFamilyOfRemote() == AddressFamily.Inet6) + ? "IpV6" + : (stats.getIpFamilyOfRemote() == AddressFamily.Inet) + ? "IpV4" + : "Unknown"); + formatText( + senderLossRate, + getString(R.string.call_stats_sender_loss_rate), new DecimalFormat("##.##").format(stats.getSenderLossRate()) + "%"); - formatText(receiverLossRate, getString(R.string.call_stats_receiver_loss_rate), + formatText( + receiverLossRate, + getString(R.string.call_stats_receiver_loss_rate), new DecimalFormat("##.##").format(stats.getReceiverLossRate()) + "%"); if (isVideo) { - formatText(videoResolutionSent, + formatText( + videoResolutionSent, getString(R.string.call_stats_video_resolution_sent), - "\u2191 " + params.getSentVideoDefinition() != null ? params.getSentVideoDefinition().getName() : ""); - formatText(videoResolutionReceived, + "\u2191 " + params.getSentVideoDefinition() != null + ? params.getSentVideoDefinition().getName() + : ""); + formatText( + videoResolutionReceived, getString(R.string.call_stats_video_resolution_received), - "\u2193 " + params.getReceivedVideoDefinition() != null ? params.getReceivedVideoDefinition().getName() : ""); - formatText(videoFpsSent, + "\u2193 " + params.getReceivedVideoDefinition() != null + ? params.getReceivedVideoDefinition().getName() + : ""); + formatText( + videoFpsSent, getString(R.string.call_stats_video_fps_sent), "\u2191 " + params.getSentFramerate()); - formatText(videoFpsReceived, + formatText( + videoFpsReceived, getString(R.string.call_stats_video_fps_received), "\u2193 " + params.getReceivedFramerate()); } else { - formatText(jitterBuffer, getString(R.string.call_stats_jitter_buffer), + formatText( + jitterBuffer, + getString(R.string.call_stats_jitter_buffer), new DecimalFormat("##.##").format(stats.getJitterBufferSizeMs()) + " ms"); } } else { @@ -1712,79 +1877,137 @@ public class CallActivity extends LinphoneGenericActivity implements OnClickList final View videoLayout = view.findViewById(R.id.callStatsVideo); final View audioLayout = view.findViewById(R.id.callStatsAudio); - mCallListener = new CallListenerStub() { - public void onStateChanged(Call call, Call.State cstate, String message) { - if (cstate == Call.State.End || cstate == Call.State.Error) { - if (mTimer != null) { - Log.i("Call is terminated, stopping timer in charge of stats refreshing."); - mTimer.cancel(); - } - } - } - }; - - mTimer = new Timer(); - mTask = new TimerTask() { - @Override - public void run() { - if (call == null) { - mTimer.cancel(); - return; - } - - if (titleAudio == null || codecAudio == null || dlVideo == null || edlVideo == null || iceAudio == null - || videoResolutionSent == null || videoLayout == null || titleVideo == null - || ipVideo == null || ipAudio == null || codecVideo == null - || dlAudio == null || ulAudio == null || ulVideo == null || iceVideo == null - || videoResolutionReceived == null) { - mTimer.cancel(); - return; - } - - mHandler.post(new Runnable() { - @Override - public void run() { - if (LinphoneManager.getLcIfManagerNotDestroyedOrNull() == null) return; - synchronized (LinphoneManager.getLc()) { - if (LinphoneActivity.isInstanciated() && call.getState() != Call.State.Released) { - CallParams params = call.getCurrentParams(); - if (params != null) { - CallStats audioStats = call.getStats(StreamType.Audio); - CallStats videoStats = null; - - if (params.videoEnabled()) - videoStats = call.getStats(StreamType.Video); - - PayloadType payloadAudio = params.getUsedAudioPayloadType(); - PayloadType payloadVideo = params.getUsedVideoPayloadType(); - - formatText(displayFilter, getString(R.string.call_stats_display_filter), call.getCore().getVideoDisplayFilter()); - - displayMediaStats(params, audioStats, payloadAudio, audioLayout - , titleAudio, codecAudio, dlAudio, ulAudio, null, iceAudio - , ipAudio, senderLossRateAudio, receiverLossRateAudio - , encoderAudio, decoderAudio, null, null, null, null - , false, jitterBufferAudio); - - displayMediaStats(params, videoStats, payloadVideo, videoLayout - , titleVideo, codecVideo, dlVideo, ulVideo, edlVideo, iceVideo - , ipVideo, senderLossRateVideo, receiverLossRateVideo - , encoderVideo, decoderVideo - , videoResolutionSent, videoResolutionReceived - , videoFpsSent, videoFpsReceived - , true, null); - } + mCallListener = + new CallListenerStub() { + public void onStateChanged(Call call, Call.State cstate, String message) { + if (cstate == Call.State.End || cstate == Call.State.Error) { + if (mTimer != null) { + Log.i( + "Call is terminated, stopping timer in charge of stats refreshing."); + mTimer.cancel(); } } } - }); - } - }; + }; + + mTimer = new Timer(); + mTask = + new TimerTask() { + @Override + public void run() { + if (call == null) { + mTimer.cancel(); + return; + } + + if (titleAudio == null + || codecAudio == null + || dlVideo == null + || edlVideo == null + || iceAudio == null + || videoResolutionSent == null + || videoLayout == null + || titleVideo == null + || ipVideo == null + || ipAudio == null + || codecVideo == null + || dlAudio == null + || ulAudio == null + || ulVideo == null + || iceVideo == null + || videoResolutionReceived == null) { + mTimer.cancel(); + return; + } + + mHandler.post( + new Runnable() { + @Override + public void run() { + if (LinphoneManager.getLcIfManagerNotDestroyedOrNull() + == null) return; + synchronized (LinphoneManager.getLc()) { + if (LinphoneActivity.isInstanciated() + && call.getState() != Call.State.Released) { + CallParams params = call.getCurrentParams(); + if (params != null) { + CallStats audioStats = + call.getStats(StreamType.Audio); + CallStats videoStats = null; + + if (params.videoEnabled()) + videoStats = + call.getStats(StreamType.Video); + + PayloadType payloadAudio = + params.getUsedAudioPayloadType(); + PayloadType payloadVideo = + params.getUsedVideoPayloadType(); + + formatText( + displayFilter, + getString( + R.string + .call_stats_display_filter), + call.getCore().getVideoDisplayFilter()); + + displayMediaStats( + params, + audioStats, + payloadAudio, + audioLayout, + titleAudio, + codecAudio, + dlAudio, + ulAudio, + null, + iceAudio, + ipAudio, + senderLossRateAudio, + receiverLossRateAudio, + encoderAudio, + decoderAudio, + null, + null, + null, + null, + false, + jitterBufferAudio); + + displayMediaStats( + params, + videoStats, + payloadVideo, + videoLayout, + titleVideo, + codecVideo, + dlVideo, + ulVideo, + edlVideo, + iceVideo, + ipVideo, + senderLossRateVideo, + receiverLossRateVideo, + encoderVideo, + decoderVideo, + videoResolutionSent, + videoResolutionReceived, + videoFpsSent, + videoFpsReceived, + true, + null); + } + } + } + } + }); + } + }; call.addListener(mCallListener); mTimer.scheduleAtFixedRate(mTask, 0, 1000); } - ////Earset Connectivity Broadcast innerClass + //// Earset Connectivity Broadcast innerClass public class HeadsetReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { diff --git a/app/src/main/java/org/linphone/call/CallAudioFragment.java b/app/src/main/java/org/linphone/call/CallAudioFragment.java index eca7df897..af90776c5 100644 --- a/app/src/main/java/org/linphone/call/CallAudioFragment.java +++ b/app/src/main/java/org/linphone/call/CallAudioFragment.java @@ -24,15 +24,14 @@ import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; - import org.linphone.R; public class CallAudioFragment extends Fragment { private CallActivity incallActvityInstance; @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.audio, container, false); return view; } diff --git a/app/src/main/java/org/linphone/call/CallIncomingActivity.java b/app/src/main/java/org/linphone/call/CallIncomingActivity.java index 80235380e..3a98c81dc 100644 --- a/app/src/main/java/org/linphone/call/CallIncomingActivity.java +++ b/app/src/main/java/org/linphone/call/CallIncomingActivity.java @@ -26,37 +26,33 @@ import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.os.Bundle; -import androidx.core.app.ActivityCompat; import android.view.KeyEvent; import android.view.WindowManager; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; - -import org.linphone.LinphoneManager; -import org.linphone.settings.LinphonePreferences; -import org.linphone.LinphoneService; -import org.linphone.utils.ImageUtils; -import org.linphone.utils.LinphoneUtils; -import org.linphone.R; +import androidx.core.app.ActivityCompat; +import java.util.ArrayList; import org.linphone.LinphoneActivity; -import org.linphone.utils.LinphoneGenericActivity; +import org.linphone.LinphoneManager; +import org.linphone.R; import org.linphone.contacts.ContactsManager; import org.linphone.contacts.LinphoneContact; import org.linphone.core.Address; import org.linphone.core.Call; import org.linphone.core.Call.State; -import org.linphone.core.CallParams; import org.linphone.core.Core; import org.linphone.core.CoreListenerStub; import org.linphone.mediastream.Log; +import org.linphone.settings.LinphonePreferences; +import org.linphone.utils.ImageUtils; +import org.linphone.utils.LinphoneGenericActivity; +import org.linphone.utils.LinphoneUtils; import org.linphone.views.CallIncomingAnswerButton; import org.linphone.views.CallIncomingButtonListener; import org.linphone.views.CallIncomingDeclineButton; -import java.util.ArrayList; - public class CallIncomingActivity extends LinphoneGenericActivity { private static CallIncomingActivity instance; @@ -95,7 +91,10 @@ public class CallIncomingActivity extends LinphoneGenericActivity { contactPicture = findViewById(R.id.contact_picture); // set this flag so this activity will stay in front of the keyguard - int flags = WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON; + int flags = + WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED + | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD + | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON; getWindow().addFlags(flags); acceptUnlock = findViewById(R.id.acceptUnlock); @@ -106,14 +105,19 @@ public class CallIncomingActivity extends LinphoneGenericActivity { acceptIcon = findViewById(R.id.acceptIcon); lookupCurrentCall(); - if (LinphonePreferences.instance() != null && mCall != null && mCall.getRemoteParams() != null && - LinphonePreferences.instance().shouldAutomaticallyAcceptVideoRequests() && - mCall.getRemoteParams().videoEnabled()) { + if (LinphonePreferences.instance() != null + && mCall != null + && mCall.getRemoteParams() != null + && LinphonePreferences.instance().shouldAutomaticallyAcceptVideoRequests() + && mCall.getRemoteParams().videoEnabled()) { acceptIcon.setImageResource(R.drawable.call_video_start); } mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); - boolean doNotUseSliders = getResources().getBoolean(R.bool.do_not_use_sliders_to_answer_hangup_call_if_phone_unlocked); + boolean doNotUseSliders = + getResources() + .getBoolean( + R.bool.do_not_use_sliders_to_answer_hangup_call_if_phone_unlocked); if (doNotUseSliders && !mKeyguardManager.inKeyguardRestrictedInputMode()) { accept.setSliderMode(false); decline.setSliderMode(false); @@ -123,33 +127,43 @@ public class CallIncomingActivity extends LinphoneGenericActivity { accept.setDeclineButton(decline); decline.setAnswerButton(accept); } - accept.setListener(new CallIncomingButtonListener() { - @Override - public void onAction() { - answer(); - } - }); - decline.setListener(new CallIncomingButtonListener() { - @Override - public void onAction() { - decline(); - } - }); + accept.setListener( + new CallIncomingButtonListener() { + @Override + public void onAction() { + answer(); + } + }); + decline.setListener( + new CallIncomingButtonListener() { + @Override + public void onAction() { + decline(); + } + }); - mListener = new CoreListenerStub() { - @Override - public void onCallStateChanged(Core lc, Call call, State state, String message) { - if (call == mCall && State.End == state) { - finish(); - } else if (state == State.Connected) { - startActivity(new Intent(CallIncomingActivity.this, CallActivity.class)); - } else if (state == State.StreamsRunning) { - Log.e("CallIncommingActivity - onCreate - State.StreamsRunning - speaker = " + LinphoneManager.getInstance().isSpeakerEnabled()); - // The following should not be needed except some devices need it (e.g. Galaxy S). - LinphoneManager.getInstance().enableSpeaker(LinphoneManager.getInstance().isSpeakerEnabled()); - } - } - }; + mListener = + new CoreListenerStub() { + @Override + public void onCallStateChanged( + Core lc, Call call, State state, String message) { + if (call == mCall && State.End == state) { + finish(); + } else if (state == State.Connected) { + startActivity( + new Intent(CallIncomingActivity.this, CallActivity.class)); + } else if (state == State.StreamsRunning) { + Log.e( + "CallIncommingActivity - onCreate - State.StreamsRunning - speaker = " + + LinphoneManager.getInstance().isSpeakerEnabled()); + // The following should not be needed except some devices need it (e.g. + // Galaxy S). + LinphoneManager.getInstance() + .enableSpeaker( + LinphoneManager.getInstance().isSpeakerEnabled()); + } + } + }; super.onCreate(savedInstanceState); instance = this; @@ -170,17 +184,17 @@ public class CallIncomingActivity extends LinphoneGenericActivity { // Only one call ringing at a time is allowed lookupCurrentCall(); if (mCall == null) { - //The incoming call no longer exists. + // The incoming call no longer exists. Log.d("Couldn't find incoming call"); finish(); return; } - Address address = mCall.getRemoteAddress(); LinphoneContact contact = ContactsManager.getInstance().findContactFromAddress(address); if (contact != null) { - ImageUtils.setImagePictureFromUri(this, contactPicture, contact.getPhotoUri(), contact.getThumbnailUri()); + ImageUtils.setImagePictureFromUri( + this, contactPicture, contact.getPhotoUri(), contact.getThumbnailUri()); name.setText(contact.getFullName()); } else { name.setText(LinphoneUtils.getAddressDisplayName(address)); @@ -211,7 +225,8 @@ public class CallIncomingActivity extends LinphoneGenericActivity { @Override public boolean onKeyDown(int keyCode, KeyEvent event) { - if (LinphoneManager.isInstanciated() && (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME)) { + if (LinphoneManager.isInstanciated() + && (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME)) { LinphoneManager.getLc().terminateCall(mCall); finish(); } @@ -260,20 +275,36 @@ public class CallIncomingActivity extends LinphoneGenericActivity { private void checkAndRequestCallPermissions() { ArrayList permissionsList = new ArrayList(); - int recordAudio = getPackageManager().checkPermission(Manifest.permission.RECORD_AUDIO, getPackageName()); - Log.i("[Permission] Record audio permission is " + (recordAudio == PackageManager.PERMISSION_GRANTED ? "granted" : "denied")); - int camera = getPackageManager().checkPermission(Manifest.permission.CAMERA, getPackageName()); - Log.i("[Permission] Camera permission is " + (camera == PackageManager.PERMISSION_GRANTED ? "granted" : "denied")); + int recordAudio = + getPackageManager() + .checkPermission(Manifest.permission.RECORD_AUDIO, getPackageName()); + Log.i( + "[Permission] Record audio permission is " + + (recordAudio == PackageManager.PERMISSION_GRANTED + ? "granted" + : "denied")); + int camera = + getPackageManager().checkPermission(Manifest.permission.CAMERA, getPackageName()); + Log.i( + "[Permission] Camera permission is " + + (camera == PackageManager.PERMISSION_GRANTED ? "granted" : "denied")); if (recordAudio != PackageManager.PERMISSION_GRANTED) { - if (LinphonePreferences.instance().firstTimeAskingForPermission(Manifest.permission.RECORD_AUDIO) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO)) { + if (LinphonePreferences.instance() + .firstTimeAskingForPermission(Manifest.permission.RECORD_AUDIO) + || ActivityCompat.shouldShowRequestPermissionRationale( + this, Manifest.permission.RECORD_AUDIO)) { Log.i("[Permission] Asking for record audio"); permissionsList.add(Manifest.permission.RECORD_AUDIO); } } - if (LinphonePreferences.instance().shouldInitiateVideoCall() || LinphonePreferences.instance().shouldAutomaticallyAcceptVideoRequests()) { + if (LinphonePreferences.instance().shouldInitiateVideoCall() + || LinphonePreferences.instance().shouldAutomaticallyAcceptVideoRequests()) { if (camera != PackageManager.PERMISSION_GRANTED) { - if (LinphonePreferences.instance().firstTimeAskingForPermission(Manifest.permission.CAMERA) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) { + if (LinphonePreferences.instance() + .firstTimeAskingForPermission(Manifest.permission.CAMERA) + || ActivityCompat.shouldShowRequestPermissionRationale( + this, Manifest.permission.CAMERA)) { Log.i("[Permission] Asking for camera"); permissionsList.add(Manifest.permission.CAMERA); } @@ -288,9 +319,16 @@ public class CallIncomingActivity extends LinphoneGenericActivity { } @Override - public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { + public void onRequestPermissionsResult( + int requestCode, String[] permissions, int[] grantResults) { for (int i = 0; i < permissions.length; i++) { - Log.i("[Permission] " + permissions[i] + " is " + (grantResults[i] == PackageManager.PERMISSION_GRANTED ? "granted" : "denied")); + Log.i( + "[Permission] " + + permissions[i] + + " is " + + (grantResults[i] == PackageManager.PERMISSION_GRANTED + ? "granted" + : "denied")); } } -} \ No newline at end of file +} diff --git a/app/src/main/java/org/linphone/call/CallManager.java b/app/src/main/java/org/linphone/call/CallManager.java index 47b087e15..fd1cd2786 100644 --- a/app/src/main/java/org/linphone/call/CallManager.java +++ b/app/src/main/java/org/linphone/call/CallManager.java @@ -20,23 +20,20 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import org.linphone.LinphoneManager; -import org.linphone.utils.FileUtils; import org.linphone.core.Address; import org.linphone.core.Call; import org.linphone.core.CallParams; import org.linphone.core.Core; import org.linphone.core.CoreException; import org.linphone.mediastream.Log; +import org.linphone.utils.FileUtils; -/** - * Handle call updating, reinvites. - */ +/** Handle call updating, reinvites. */ public class CallManager { private static CallManager instance; - private CallManager() { - } + private CallManager() {} public static final synchronized CallManager getInstance() { if (instance == null) instance = new CallManager(); @@ -47,7 +44,8 @@ public class CallManager { return BandwidthManager.getInstance(); } - public void inviteAddress(Address lAddress, boolean videoEnabled, boolean lowBandwidth) throws CoreException { + public void inviteAddress(Address lAddress, boolean videoEnabled, boolean lowBandwidth) + throws CoreException { Core lc = LinphoneManager.getLc(); CallParams params = lc.createCallParams(null); @@ -64,16 +62,17 @@ public class CallManager { Log.d("Low bandwidth enabled in call params"); } - String recordFile = FileUtils.getCallRecordingFilename(LinphoneManager.getInstance().getContext(), lAddress); + String recordFile = + FileUtils.getCallRecordingFilename( + LinphoneManager.getInstance().getContext(), lAddress); params.setRecordFile(recordFile); lc.inviteAddressWithParams(lAddress, params); } /** - * Add video to a currently running voice only call. - * No re-invite is sent if the current call is already video - * or if the bandwidth settings are too low. + * Add video to a currently running voice only call. No re-invite is sent if the current call is + * already video or if the bandwidth settings are too low. * * @return if updateCall called */ @@ -88,7 +87,6 @@ public class CallManager { if (params.videoEnabled()) return false; - // Check if video possible regarding bandwidth limitations bm().updateWithProfileSettings(lc, params); @@ -104,8 +102,8 @@ public class CallManager { /** * Change the preferred video size used by linphone core. (impact landscape/portrait buffer). - * Update current call, without reinvite. - * The camera will be restarted when mediastreamer chain is recreated and setParameters is called. + * Update current call, without reinvite. The camera will be restarted when mediastreamer chain + * is recreated and setParameters is called. */ public void updateCall() { Core lc = LinphoneManager.getLc(); @@ -118,5 +116,4 @@ public class CallManager { bm().updateWithProfileSettings(lc, params); lc.updateCall(lCall, null); } - } diff --git a/app/src/main/java/org/linphone/call/CallOutgoingActivity.java b/app/src/main/java/org/linphone/call/CallOutgoingActivity.java index 81e3e39d4..e2e46d082 100644 --- a/app/src/main/java/org/linphone/call/CallOutgoingActivity.java +++ b/app/src/main/java/org/linphone/call/CallOutgoingActivity.java @@ -23,7 +23,6 @@ import android.Manifest; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.os.Bundle; -import androidx.core.app.ActivityCompat; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; @@ -34,14 +33,11 @@ import android.view.WindowManager; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; - -import org.linphone.LinphoneManager; -import org.linphone.settings.LinphonePreferences; -import org.linphone.utils.ImageUtils; -import org.linphone.utils.LinphoneUtils; -import org.linphone.R; +import androidx.core.app.ActivityCompat; +import java.util.ArrayList; import org.linphone.LinphoneActivity; -import org.linphone.utils.LinphoneGenericActivity; +import org.linphone.LinphoneManager; +import org.linphone.R; import org.linphone.contacts.ContactsManager; import org.linphone.contacts.LinphoneContact; import org.linphone.core.Address; @@ -51,8 +47,10 @@ import org.linphone.core.Core; import org.linphone.core.CoreListenerStub; import org.linphone.core.Reason; import org.linphone.mediastream.Log; - -import java.util.ArrayList; +import org.linphone.settings.LinphonePreferences; +import org.linphone.utils.ImageUtils; +import org.linphone.utils.LinphoneGenericActivity; +import org.linphone.utils.LinphoneUtils; public class CallOutgoingActivity extends LinphoneGenericActivity implements OnClickListener { private static CallOutgoingActivity instance; @@ -95,53 +93,69 @@ public class CallOutgoingActivity extends LinphoneGenericActivity implements OnC speaker.setOnClickListener(this); // set this flag so this activity will stay in front of the keyguard - int flags = WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON; + int flags = + WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED + | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD + | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON; getWindow().addFlags(flags); hangUp = findViewById(R.id.outgoing_hang_up); hangUp.setOnClickListener(this); - mListener = new CoreListenerStub() { - @Override - public void onCallStateChanged(Core lc, Call call, Call.State state, String message) { - if (call == mCall && State.Connected == state) { - if (!LinphoneActivity.isInstanciated()) { - return; - } - LinphoneActivity.instance().startIncallActivity(); - return; - } else if (state == State.Error) { - // Convert Core message for internalization - if (call.getErrorInfo().getReason() == Reason.Declined) { - displayCustomToast(getString(R.string.error_call_declined), Toast.LENGTH_SHORT); - decline(); - } else if (call.getErrorInfo().getReason() == Reason.NotFound) { - displayCustomToast(getString(R.string.error_user_not_found), Toast.LENGTH_SHORT); - decline(); - } else if (call.getErrorInfo().getReason() == Reason.NotAcceptable) { - displayCustomToast(getString(R.string.error_incompatible_media), Toast.LENGTH_SHORT); - decline(); - } else if (call.getErrorInfo().getReason() == Reason.Busy) { - displayCustomToast(getString(R.string.error_user_busy), Toast.LENGTH_SHORT); - decline(); - } else if (message != null) { - displayCustomToast(getString(R.string.error_unknown) + " - " + message, Toast.LENGTH_SHORT); - decline(); - } - } else if (state == State.End) { - // Convert Core message for internalization - if (call.getErrorInfo().getReason() == Reason.Declined) { - displayCustomToast(getString(R.string.error_call_declined), Toast.LENGTH_SHORT); - decline(); - } - } + mListener = + new CoreListenerStub() { + @Override + public void onCallStateChanged( + Core lc, Call call, Call.State state, String message) { + if (call == mCall && State.Connected == state) { + if (!LinphoneActivity.isInstanciated()) { + return; + } + LinphoneActivity.instance().startIncallActivity(); + return; + } else if (state == State.Error) { + // Convert Core message for internalization + if (call.getErrorInfo().getReason() == Reason.Declined) { + displayCustomToast( + getString(R.string.error_call_declined), + Toast.LENGTH_SHORT); + decline(); + } else if (call.getErrorInfo().getReason() == Reason.NotFound) { + displayCustomToast( + getString(R.string.error_user_not_found), + Toast.LENGTH_SHORT); + decline(); + } else if (call.getErrorInfo().getReason() == Reason.NotAcceptable) { + displayCustomToast( + getString(R.string.error_incompatible_media), + Toast.LENGTH_SHORT); + decline(); + } else if (call.getErrorInfo().getReason() == Reason.Busy) { + displayCustomToast( + getString(R.string.error_user_busy), Toast.LENGTH_SHORT); + decline(); + } else if (message != null) { + displayCustomToast( + getString(R.string.error_unknown) + " - " + message, + Toast.LENGTH_SHORT); + decline(); + } + } else if (state == State.End) { + // Convert Core message for internalization + if (call.getErrorInfo().getReason() == Reason.Declined) { + displayCustomToast( + getString(R.string.error_call_declined), + Toast.LENGTH_SHORT); + decline(); + } + } - if (LinphoneManager.getLc().getCallsNb() == 0) { - finish(); - return; - } - } - }; + if (LinphoneManager.getLc().getCallsNb() == 0) { + finish(); + return; + } + } + }; instance = this; } @@ -160,8 +174,10 @@ public class CallOutgoingActivity extends LinphoneGenericActivity implements OnC if (LinphoneManager.getLcIfManagerNotDestroyedOrNull() != null) { for (Call call : LinphoneManager.getLc().getCalls()) { State cstate = call.getState(); - if (State.OutgoingInit == cstate || State.OutgoingProgress == cstate - || State.OutgoingRinging == cstate || State.OutgoingEarlyMedia == cstate) { + if (State.OutgoingInit == cstate + || State.OutgoingProgress == cstate + || State.OutgoingRinging == cstate + || State.OutgoingEarlyMedia == cstate) { mCall = call; break; } @@ -183,7 +199,8 @@ public class CallOutgoingActivity extends LinphoneGenericActivity implements OnC Address address = mCall.getRemoteAddress(); LinphoneContact contact = ContactsManager.getInstance().findContactFromAddress(address); if (contact != null) { - ImageUtils.setImagePictureFromUri(this, contactPicture, contact.getPhotoUri(), contact.getThumbnailUri()); + ImageUtils.setImagePictureFromUri( + this, contactPicture, contact.getPhotoUri(), contact.getThumbnailUri()); name.setText(contact.getFullName()); } else { name.setText(LinphoneUtils.getAddressDisplayName(address)); @@ -241,7 +258,8 @@ public class CallOutgoingActivity extends LinphoneGenericActivity implements OnC @Override public boolean onKeyDown(int keyCode, KeyEvent event) { - if (LinphoneManager.isInstanciated() && (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME)) { + if (LinphoneManager.isInstanciated() + && (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME)) { LinphoneManager.getLc().terminateCall(mCall); finish(); } @@ -270,20 +288,36 @@ public class CallOutgoingActivity extends LinphoneGenericActivity implements OnC private void checkAndRequestCallPermissions() { ArrayList permissionsList = new ArrayList(); - int recordAudio = getPackageManager().checkPermission(Manifest.permission.RECORD_AUDIO, getPackageName()); - Log.i("[Permission] Record audio permission is " + (recordAudio == PackageManager.PERMISSION_GRANTED ? "granted" : "denied")); - int camera = getPackageManager().checkPermission(Manifest.permission.CAMERA, getPackageName()); - Log.i("[Permission] Camera permission is " + (camera == PackageManager.PERMISSION_GRANTED ? "granted" : "denied")); + int recordAudio = + getPackageManager() + .checkPermission(Manifest.permission.RECORD_AUDIO, getPackageName()); + Log.i( + "[Permission] Record audio permission is " + + (recordAudio == PackageManager.PERMISSION_GRANTED + ? "granted" + : "denied")); + int camera = + getPackageManager().checkPermission(Manifest.permission.CAMERA, getPackageName()); + Log.i( + "[Permission] Camera permission is " + + (camera == PackageManager.PERMISSION_GRANTED ? "granted" : "denied")); if (recordAudio != PackageManager.PERMISSION_GRANTED) { - if (LinphonePreferences.instance().firstTimeAskingForPermission(Manifest.permission.RECORD_AUDIO) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO)) { + if (LinphonePreferences.instance() + .firstTimeAskingForPermission(Manifest.permission.RECORD_AUDIO) + || ActivityCompat.shouldShowRequestPermissionRationale( + this, Manifest.permission.RECORD_AUDIO)) { Log.i("[Permission] Asking for record audio"); permissionsList.add(Manifest.permission.RECORD_AUDIO); } } - if (LinphonePreferences.instance().shouldInitiateVideoCall() || LinphonePreferences.instance().shouldAutomaticallyAcceptVideoRequests()) { + if (LinphonePreferences.instance().shouldInitiateVideoCall() + || LinphonePreferences.instance().shouldAutomaticallyAcceptVideoRequests()) { if (camera != PackageManager.PERMISSION_GRANTED) { - if (LinphonePreferences.instance().firstTimeAskingForPermission(Manifest.permission.CAMERA) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) { + if (LinphonePreferences.instance() + .firstTimeAskingForPermission(Manifest.permission.CAMERA) + || ActivityCompat.shouldShowRequestPermissionRationale( + this, Manifest.permission.CAMERA)) { Log.i("[Permission] Asking for camera"); permissionsList.add(Manifest.permission.CAMERA); } @@ -298,9 +332,16 @@ public class CallOutgoingActivity extends LinphoneGenericActivity implements OnC } @Override - public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { + public void onRequestPermissionsResult( + int requestCode, String[] permissions, int[] grantResults) { for (int i = 0; i < permissions.length; i++) { - Log.i("[Permission] " + permissions[i] + " is " + (grantResults[i] == PackageManager.PERMISSION_GRANTED ? "granted" : "denied")); + Log.i( + "[Permission] " + + permissions[i] + + " is " + + (grantResults[i] == PackageManager.PERMISSION_GRANTED + ? "granted" + : "denied")); } } } diff --git a/app/src/main/java/org/linphone/call/CallVideoFragment.java b/app/src/main/java/org/linphone/call/CallVideoFragment.java index 72254bb10..19ee9267f 100644 --- a/app/src/main/java/org/linphone/call/CallVideoFragment.java +++ b/app/src/main/java/org/linphone/call/CallVideoFragment.java @@ -32,11 +32,8 @@ import android.view.View; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.widget.RelativeLayout; - import org.linphone.LinphoneManager; -import org.linphone.settings.LinphonePreferences; import org.linphone.LinphoneService; -import org.linphone.utils.LinphoneUtils; import org.linphone.R; import org.linphone.compatibility.CompatibilityScaleGestureDetector; import org.linphone.compatibility.CompatibilityScaleGestureListener; @@ -44,8 +41,11 @@ import org.linphone.core.Call; import org.linphone.core.Core; import org.linphone.core.VideoDefinition; import org.linphone.mediastream.Log; +import org.linphone.settings.LinphonePreferences; +import org.linphone.utils.LinphoneUtils; -public class CallVideoFragment extends Fragment implements OnGestureListener, OnDoubleTapListener, CompatibilityScaleGestureListener { +public class CallVideoFragment extends Fragment + implements OnGestureListener, OnDoubleTapListener, CompatibilityScaleGestureListener { private TextureView mVideoView; private TextureView mCaptureView; private GestureDetector mGestureDetector; @@ -58,8 +58,8 @@ public class CallVideoFragment extends Fragment implements OnGestureListener, On @SuppressWarnings("deprecation") // Warning useless because value is ignored and automatically set by new APIs. @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view; if (LinphoneManager.getLc().hasCrappyOpengl()) { view = inflater.inflate(R.layout.video_no_opengl, container, false); @@ -69,48 +69,55 @@ public class CallVideoFragment extends Fragment implements OnGestureListener, On mVideoView = view.findViewById(R.id.videoSurface); mCaptureView = view.findViewById(R.id.videoCaptureSurface); - + LinphoneManager.getLc().setNativeVideoWindowId(mVideoView); LinphoneManager.getLc().setNativePreviewWindowId(mCaptureView); - mVideoView.setOnTouchListener(new OnTouchListener() { - public boolean onTouch(View v, MotionEvent event) { - if (mScaleDetector != null) { - mScaleDetector.onTouchEvent(event); - } + mVideoView.setOnTouchListener( + new OnTouchListener() { + public boolean onTouch(View v, MotionEvent event) { + if (mScaleDetector != null) { + mScaleDetector.onTouchEvent(event); + } - mGestureDetector.onTouchEvent(event); - if (inCallActivity != null) { - inCallActivity.displayVideoCallControlsIfHidden(); - } - return true; - } - }); + mGestureDetector.onTouchEvent(event); + if (inCallActivity != null) { + inCallActivity.displayVideoCallControlsIfHidden(); + } + return true; + } + }); - mCaptureView.setOnTouchListener(new OnTouchListener() { - @Override - public boolean onTouch(View view, MotionEvent motionEvent) { - switch (motionEvent.getAction()) { - case MotionEvent.ACTION_DOWN: - previewX = (int) motionEvent.getX(); - previewY = (int) motionEvent.getY(); - break; - case MotionEvent.ACTION_MOVE: - int x = (int) motionEvent.getX(); - int y = (int) motionEvent.getY(); - RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mCaptureView.getLayoutParams(); - lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 0); // Clears the rule, as there is no removeRule until API 17. - lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 0); - int left = lp.leftMargin + (x - previewX); - int top = lp.topMargin + (y - previewY); - lp.leftMargin = left; - lp.topMargin = top; - view.setLayoutParams(lp); - break; - } - return true; - } - }); + mCaptureView.setOnTouchListener( + new OnTouchListener() { + @Override + public boolean onTouch(View view, MotionEvent motionEvent) { + switch (motionEvent.getAction()) { + case MotionEvent.ACTION_DOWN: + previewX = (int) motionEvent.getX(); + previewY = (int) motionEvent.getY(); + break; + case MotionEvent.ACTION_MOVE: + int x = (int) motionEvent.getX(); + int y = (int) motionEvent.getY(); + RelativeLayout.LayoutParams lp = + (RelativeLayout.LayoutParams) + mCaptureView.getLayoutParams(); + lp.addRule( + RelativeLayout.ALIGN_PARENT_BOTTOM, + 0); // Clears the rule, as there is no removeRule until API + // 17. + lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 0); + int left = lp.leftMargin + (x - previewX); + int top = lp.topMargin + (y - previewY); + lp.leftMargin = left; + lp.topMargin = top; + view.setLayoutParams(lp); + break; + } + return true; + } + }); return view; } @@ -135,9 +142,12 @@ public class CallVideoFragment extends Fragment implements OnGestureListener, On DisplayMetrics metrics = new DisplayMetrics(); getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics); int screenHeight = metrics.heightPixels; - int maxHeight = screenHeight / 4; // Let's take at most 1/4 of the screen for the camera preview + int maxHeight = + screenHeight / 4; // Let's take at most 1/4 of the screen for the camera preview - VideoDefinition videoSize = call.getCurrentParams().getSentVideoDefinition(); // It already takes care of rotation + VideoDefinition videoSize = + call.getCurrentParams() + .getSentVideoDefinition(); // It already takes care of rotation if (videoSize.getWidth() == 0 || videoSize.getHeight() == 0) { Log.w("Couldn't get sent video definition, using default video definition"); videoSize = lc.getPreferredVideoDefinition(); @@ -155,7 +165,9 @@ public class CallVideoFragment extends Fragment implements OnGestureListener, On } RelativeLayout.LayoutParams newLp = new RelativeLayout.LayoutParams(width, height); - newLp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 1); // Clears the rule, as there is no removeRule until API 17. + newLp.addRule( + RelativeLayout.ALIGN_PARENT_BOTTOM, + 1); // Clears the rule, as there is no removeRule until API 17. newLp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 1); mCaptureView.setLayoutParams(newLp); Log.d("Video preview size set to " + width + "x" + height); @@ -175,12 +187,9 @@ public class CallVideoFragment extends Fragment implements OnGestureListener, On } String newDevice; - if (index == 1) - newDevice = devices[0]; - else if (devices.length > 1) - newDevice = devices[1]; - else - newDevice = devices[index]; + if (index == 1) newDevice = devices[0]; + else if (devices.length > 1) newDevice = devices[1]; + else newDevice = devices[index]; LinphoneManager.getLc().setVideoDevice(newDevice); CallManager.getInstance().updateCall(); @@ -217,10 +226,15 @@ public class CallVideoFragment extends Fragment implements OnGestureListener, On mZoomFactor *= detector.getScaleFactor(); // Don't let the object get too small or too large. // Zoom to make the video fill the screen vertically - float portraitZoomFactor = ((float) mVideoView.getHeight()) / (float) ((3 * mVideoView.getWidth()) / 4); + float portraitZoomFactor = + ((float) mVideoView.getHeight()) / (float) ((3 * mVideoView.getWidth()) / 4); // Zoom to make the video fill the screen horizontally - float landscapeZoomFactor = ((float) mVideoView.getWidth()) / (float) ((3 * mVideoView.getHeight()) / 4); - mZoomFactor = Math.max(0.1f, Math.min(mZoomFactor, Math.max(portraitZoomFactor, landscapeZoomFactor))); + float landscapeZoomFactor = + ((float) mVideoView.getWidth()) / (float) ((3 * mVideoView.getHeight()) / 4); + mZoomFactor = + Math.max( + 0.1f, + Math.min(mZoomFactor, Math.max(portraitZoomFactor, landscapeZoomFactor))); Call currentCall = LinphoneManager.getLc().getCurrentCall(); if (currentCall != null) { @@ -246,16 +260,14 @@ public class CallVideoFragment extends Fragment implements OnGestureListener, On mZoomCenterY -= 0.01; } - if (mZoomCenterX > 1) - mZoomCenterX = 1; - if (mZoomCenterX < 0) - mZoomCenterX = 0; - if (mZoomCenterY > 1) - mZoomCenterY = 1; - if (mZoomCenterY < 0) - mZoomCenterY = 0; + if (mZoomCenterX > 1) mZoomCenterX = 1; + if (mZoomCenterX < 0) mZoomCenterX = 0; + if (mZoomCenterY > 1) mZoomCenterY = 1; + if (mZoomCenterY < 0) mZoomCenterY = 0; - LinphoneManager.getLc().getCurrentCall().zoom(mZoomFactor, mZoomCenterX, mZoomCenterY); + LinphoneManager.getLc() + .getCurrentCall() + .zoom(mZoomFactor, mZoomCenterX, mZoomCenterY); return true; } } @@ -268,9 +280,13 @@ public class CallVideoFragment extends Fragment implements OnGestureListener, On if (LinphoneUtils.isCallEstablished(LinphoneManager.getLc().getCurrentCall())) { if (mZoomFactor == 1.f) { // Zoom to make the video fill the screen vertically - float portraitZoomFactor = ((float) mVideoView.getHeight()) / (float) ((3 * mVideoView.getWidth()) / 4); + float portraitZoomFactor = + ((float) mVideoView.getHeight()) + / (float) ((3 * mVideoView.getWidth()) / 4); // Zoom to make the video fill the screen horizontally - float landscapeZoomFactor = ((float) mVideoView.getWidth()) / (float) ((3 * mVideoView.getHeight()) / 4); + float landscapeZoomFactor = + ((float) mVideoView.getWidth()) + / (float) ((3 * mVideoView.getHeight()) / 4); mZoomFactor = Math.max(portraitZoomFactor, landscapeZoomFactor); } else { @@ -326,20 +342,15 @@ public class CallVideoFragment extends Fragment implements OnGestureListener, On } @Override - public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, - float velocityY) { + public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { return false; } @Override - public void onLongPress(MotionEvent e) { - - } + public void onLongPress(MotionEvent e) {} @Override - public void onShowPress(MotionEvent e) { - - } + public void onShowPress(MotionEvent e) {} @Override public boolean onSingleTapUp(MotionEvent e) { diff --git a/app/src/main/java/org/linphone/chat/ChatMessageOldViewHolder.java b/app/src/main/java/org/linphone/chat/ChatMessageOldViewHolder.java index 6e346a6a5..0987be957 100644 --- a/app/src/main/java/org/linphone/chat/ChatMessageOldViewHolder.java +++ b/app/src/main/java/org/linphone/chat/ChatMessageOldViewHolder.java @@ -20,8 +20,6 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import android.content.Context; - -import androidx.recyclerview.widget.RecyclerView; import android.view.View; import android.widget.Button; import android.widget.CheckBox; @@ -30,11 +28,12 @@ import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; - +import androidx.recyclerview.widget.RecyclerView; import org.linphone.R; import org.linphone.core.ChatMessage; -public class ChatMessageOldViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { +public class ChatMessageOldViewHolder extends RecyclerView.ViewHolder + implements View.OnClickListener { public String messageId; public Context mContext; public ChatMessage message; @@ -66,7 +65,8 @@ public class ChatMessageOldViewHolder extends RecyclerView.ViewHolder implements public CheckBox delete; private ChatMessageViewHolderClickListener mListener; - public ChatMessageOldViewHolder(Context context, View view, ChatMessageViewHolderClickListener listener) { + public ChatMessageOldViewHolder( + Context context, View view, ChatMessageViewHolderClickListener listener) { this(view); mContext = context; mListener = listener; @@ -76,7 +76,7 @@ public class ChatMessageOldViewHolder extends RecyclerView.ViewHolder implements public ChatMessageOldViewHolder(View view) { super(view); eventLayout = view.findViewById(R.id.event); - //eventTime = view.findViewById(R.id.event_date); + // eventTime = view.findViewById(R.id.event_date); eventMessage = view.findViewById(R.id.event_text); bubbleLayout = view.findViewById(R.id.bubble); @@ -110,4 +110,4 @@ public class ChatMessageOldViewHolder extends RecyclerView.ViewHolder implements mListener.onItemClicked(getAdapterPosition()); } } -} \ No newline at end of file +} diff --git a/app/src/main/java/org/linphone/chat/ChatMessageViewHolder.java b/app/src/main/java/org/linphone/chat/ChatMessageViewHolder.java index b345b7ccd..fb875129e 100644 --- a/app/src/main/java/org/linphone/chat/ChatMessageViewHolder.java +++ b/app/src/main/java/org/linphone/chat/ChatMessageViewHolder.java @@ -19,12 +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. */ +import static android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION; + import android.Manifest; import android.content.Context; - -import androidx.core.content.FileProvider; -import androidx.recyclerview.widget.RecyclerView; - import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; @@ -42,16 +40,18 @@ import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; - +import androidx.core.content.FileProvider; +import androidx.recyclerview.widget.RecyclerView; import com.google.android.flexbox.FlexboxLayout; - +import java.io.File; +import java.util.ArrayList; +import java.util.List; import org.linphone.LinphoneActivity; import org.linphone.R; import org.linphone.contacts.ContactsManager; import org.linphone.contacts.LinphoneContact; import org.linphone.core.Address; import org.linphone.core.ChatMessage; -import org.linphone.core.ChatMessageListenerStub; import org.linphone.core.Content; import org.linphone.mediastream.Log; import org.linphone.utils.FileUtils; @@ -60,12 +60,6 @@ import org.linphone.views.AsyncBitmap; import org.linphone.views.BitmapWorkerTask; import org.linphone.views.ContactAvatar; -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import static android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION; - public class ChatMessageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { private Context mContext; @@ -93,7 +87,8 @@ public class ChatMessageViewHolder extends RecyclerView.ViewHolder implements Vi public CheckBox deleteMessage; private ChatMessageViewHolderClickListener mListener; - public ChatMessageViewHolder(Context context, View view, ChatMessageViewHolderClickListener listener) { + public ChatMessageViewHolder( + Context context, View view, ChatMessageViewHolderClickListener listener) { this(view); mContext = context; mListener = listener; @@ -147,7 +142,9 @@ public class ChatMessageViewHolder extends RecyclerView.ViewHolder implements Vi ChatMessage.State status = message.getState(); Address remoteSender = message.getFromAddress(); String displayName; - String time = LinphoneUtils.timestampToHumanDate(mContext, message.getTime(), R.string.messages_date_format); + String time = + LinphoneUtils.timestampToHumanDate( + mContext, message.getTime(), R.string.messages_date_format); if (message.isOutgoing()) { outgoingImdn.setVisibility(View.INVISIBLE); // For anchoring purposes @@ -215,14 +212,24 @@ public class ChatMessageViewHolder extends RecyclerView.ViewHolder implements Vi if (fileContents.size() > 0) { pictures.setVisibility(View.VISIBLE); for (Content c : fileContents) { - View content = LayoutInflater.from(mContext).inflate(R.layout.chat_bubble_content, null, false); + View content = + LayoutInflater.from(mContext) + .inflate(R.layout.chat_bubble_content, null, false); - if (c.isFile() || (c.isFileTransfer() && message.isOutgoing())) { // If message is outgoing, even if content is file transfer we have the file available + if (c.isFile() + || (c.isFileTransfer() + && message + .isOutgoing())) { // If message is outgoing, even if content + // is file transfer we have the file + // available String filePath = c.getFilePath(); View v; if (FileUtils.isExtensionImage(filePath)) { - if (fileContents.size() == 1 && mContext.getResources().getBoolean(R.bool.use_big_pictures_to_preview_images_file_transfers)) { + if (fileContents.size() == 1 + && mContext.getResources() + .getBoolean( + R.bool.use_big_pictures_to_preview_images_file_transfers)) { v = content.findViewById(R.id.bigImage); loadBitmap(c.getFilePath(), ((ImageView) v)); } else { @@ -231,42 +238,56 @@ public class ChatMessageViewHolder extends RecyclerView.ViewHolder implements Vi } } else { v = content.findViewById(R.id.file); - ((TextView)v).setText(FileUtils.getNameFromFilePath(filePath)); + ((TextView) v).setText(FileUtils.getNameFromFilePath(filePath)); } v.setVisibility(View.VISIBLE); v.setTag(c.getFilePath()); - v.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - openFile((String) v.getTag()); - } - }); + v.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View v) { + openFile((String) v.getTag()); + } + }); } else { Button download = content.findViewById(R.id.download); download.setVisibility(View.VISIBLE); - if (mContext.getPackageManager().checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, mContext.getPackageName()) == PackageManager.PERMISSION_GRANTED) { + if (mContext.getPackageManager() + .checkPermission( + Manifest.permission.WRITE_EXTERNAL_STORAGE, + mContext.getPackageName()) + == PackageManager.PERMISSION_GRANTED) { String filename = c.getName(); File file = new File(FileUtils.getStorageDirectory(mContext), filename); int prefix = 1; while (file.exists()) { - file = new File(FileUtils.getStorageDirectory(mContext), prefix + "_" + filename); - Log.w("File with that name already exists, renamed to " + prefix + "_" + filename); + file = + new File( + FileUtils.getStorageDirectory(mContext), + prefix + "_" + filename); + Log.w( + "File with that name already exists, renamed to " + + prefix + + "_" + + filename); prefix += 1; } download.setTag(c); c.setFilePath(file.getPath()); - download.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - Content c = (Content) v.getTag(); - message.downloadContent(c); - } - }); + download.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View v) { + Content c = (Content) v.getTag(); + message.downloadContent(c); + } + }); } else { - Log.w("WRITE_EXTERNAL_STORAGE permission not granted, won't be able to store the downloaded file"); + Log.w( + "WRITE_EXTERNAL_STORAGE permission not granted, won't be able to store the downloaded file"); LinphoneActivity.instance().checkAndRequestExternalStoragePermission(); } } @@ -283,13 +304,21 @@ public class ChatMessageViewHolder extends RecyclerView.ViewHolder implements Vi if (path.startsWith("file://")) { path = path.substring("file://".length()); file = new File(path); - contentUri = FileProvider.getUriForFile(mContext, mContext.getResources().getString(R.string.file_provider), file); + contentUri = + FileProvider.getUriForFile( + mContext, + mContext.getResources().getString(R.string.file_provider), + file); } else if (path.startsWith("content://")) { contentUri = Uri.parse(path); } else { file = new File(path); try { - contentUri = FileProvider.getUriForFile(mContext, mContext.getResources().getString(R.string.file_provider), file); + contentUri = + FileProvider.getUriForFile( + mContext, + mContext.getResources().getString(R.string.file_provider), + file); } catch (Exception e) { contentUri = Uri.parse(path); } @@ -311,9 +340,11 @@ public class ChatMessageViewHolder extends RecyclerView.ViewHolder implements Vi private void loadBitmap(String path, ImageView imageView) { if (cancelPotentialWork(path, imageView)) { - Bitmap defaultBitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.chat_file); + Bitmap defaultBitmap = + BitmapFactory.decodeResource(mContext.getResources(), R.drawable.chat_file); BitmapWorkerTask task = new BitmapWorkerTask(mContext, imageView, defaultBitmap); - final AsyncBitmap asyncBitmap = new AsyncBitmap(mContext.getResources(), defaultBitmap, task); + final AsyncBitmap asyncBitmap = + new AsyncBitmap(mContext.getResources(), defaultBitmap, task); imageView.setImageDrawable(asyncBitmap); task.execute(path); } @@ -336,5 +367,4 @@ public class ChatMessageViewHolder extends RecyclerView.ViewHolder implements Vi // No task associated with the ImageView, or an existing task was cancelled return true; } - -} \ No newline at end of file +} diff --git a/app/src/main/java/org/linphone/chat/ChatMessagesAdapter.java b/app/src/main/java/org/linphone/chat/ChatMessagesAdapter.java index b62a8a297..16548ac21 100644 --- a/app/src/main/java/org/linphone/chat/ChatMessagesAdapter.java +++ b/app/src/main/java/org/linphone/chat/ChatMessagesAdapter.java @@ -20,13 +20,14 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import android.content.Context; -import androidx.annotation.NonNull; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; - -import org.linphone.mediastream.Log; -import org.linphone.utils.LinphoneUtils; +import androidx.annotation.NonNull; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; import org.linphone.R; import org.linphone.contacts.ContactsManager; import org.linphone.contacts.LinphoneContact; @@ -34,15 +35,12 @@ import org.linphone.core.Address; import org.linphone.core.ChatMessage; import org.linphone.core.ChatMessageListenerStub; import org.linphone.core.EventLog; +import org.linphone.utils.LinphoneUtils; import org.linphone.utils.SelectableAdapter; import org.linphone.utils.SelectableHelper; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -public class ChatMessagesAdapter extends SelectableAdapter implements ChatMessagesGenericAdapter { +public class ChatMessagesAdapter extends SelectableAdapter + implements ChatMessagesGenericAdapter { public static int MAX_TIME_TO_GROUP_MESSAGES = 60; private Context mContext; @@ -55,7 +53,13 @@ public class ChatMessagesAdapter extends SelectableAdapter participants, ChatMessageViewHolderClickListener clickListener) { + public ChatMessagesAdapter( + ChatMessagesFragment fragment, + SelectableHelper helper, + int itemResource, + EventLog[] history, + ArrayList participants, + ChatMessageViewHolderClickListener clickListener) { super(helper); mFragment = fragment; mContext = mFragment.getActivity(); @@ -69,11 +73,10 @@ public class ChatMessagesAdapter extends SelectableAdapter 0 && mContext.getResources().getBoolean(R.bool.lower_space_between_chat_bubbles_if_same_person)) { + // Do not forget history is reversed, so previous in order is next in list display and + // chronology ! + if (position > 0 + && mContext.getResources() + .getBoolean(R.bool.lower_space_between_chat_bubbles_if_same_person)) { EventLog previousEvent = (EventLog) getItem(position - 1); if (previousEvent.getType() == EventLog.Type.ConferenceChatMessage) { ChatMessage previousMessage = previousEvent.getChatMessage(); if (previousMessage.getFromAddress().weakEqual(message.getFromAddress())) { - if (previousMessage.getTime() - message.getTime() < MAX_TIME_TO_GROUP_MESSAGES) { + if (previousMessage.getTime() - message.getTime() + < MAX_TIME_TO_GROUP_MESSAGES) { hasPrevious = true; } } } } - if (position < mHistory.size() - 1 && mContext.getResources().getBoolean(R.bool.lower_space_between_chat_bubbles_if_same_person)) { + if (position < mHistory.size() - 1 + && mContext.getResources() + .getBoolean(R.bool.lower_space_between_chat_bubbles_if_same_person)) { EventLog nextEvent = (EventLog) getItem(position + 1); if (nextEvent.getType() == EventLog.Type.ConferenceChatMessage) { ChatMessage nextMessage = nextEvent.getChatMessage(); diff --git a/app/src/main/java/org/linphone/chat/ChatMessagesFragment.java b/app/src/main/java/org/linphone/chat/ChatMessagesFragment.java index fbbc09429..c050aab8c 100644 --- a/app/src/main/java/org/linphone/chat/ChatMessagesFragment.java +++ b/app/src/main/java/org/linphone/chat/ChatMessagesFragment.java @@ -19,6 +19,9 @@ along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ +import static android.content.Context.INPUT_METHOD_SERVICE; +import static org.linphone.fragments.FragmentsAvailable.CHAT; + import android.app.Activity; import android.app.Dialog; import android.app.Fragment; @@ -35,11 +38,8 @@ import android.os.Handler; import android.os.Looper; import android.os.Parcelable; import android.provider.MediaStore; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; import android.text.Editable; import android.text.TextWatcher; -import android.util.AttributeSet; import android.view.ContextMenu; import android.view.LayoutInflater; import android.view.MenuInflater; @@ -55,15 +55,16 @@ import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; - -import org.linphone.LinphoneManager; -import org.linphone.settings.LinphonePreferences; -import org.linphone.LinphoneService; -import org.linphone.utils.FileUtils; -import org.linphone.utils.ImageUtils; -import org.linphone.utils.LinphoneUtils; -import org.linphone.R; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import org.linphone.LinphoneActivity; +import org.linphone.LinphoneManager; +import org.linphone.LinphoneService; +import org.linphone.R; import org.linphone.contacts.ContactAddress; import org.linphone.contacts.ContactsManager; import org.linphone.contacts.ContactsUpdatedListener; @@ -83,17 +84,17 @@ import org.linphone.core.Participant; import org.linphone.core.ParticipantDevice; import org.linphone.core.Reason; import org.linphone.mediastream.Log; +import org.linphone.settings.LinphonePreferences; +import org.linphone.utils.FileUtils; +import org.linphone.utils.ImageUtils; +import org.linphone.utils.LinphoneUtils; import org.linphone.utils.SelectableHelper; -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import static android.content.Context.INPUT_METHOD_SERVICE; -import static org.linphone.fragments.FragmentsAvailable.CHAT; - -public class ChatMessagesFragment extends Fragment implements ChatRoomListener, ContactsUpdatedListener, ChatMessageViewHolderClickListener, SelectableHelper.DeleteListener { +public class ChatMessagesFragment extends Fragment + implements ChatRoomListener, + ContactsUpdatedListener, + ChatMessageViewHolderClickListener, + SelectableHelper.DeleteListener { private static final int ADD_PHOTO = 1337; private static final int MESSAGES_PER_PAGE = 20; @@ -122,7 +123,8 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, private ImageView mChatRoomSecurityLevel; @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Retain the fragment across configuration changes setRetainInstance(true); @@ -141,80 +143,103 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, mTopBar = view.findViewById(R.id.top_bar); mChatRoomSecurityLevel = view.findViewById(R.id.room_security_level); - mChatRoomSecurityLevel.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - boolean oneParticipantOneDevice = false; - if (mChatRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt())) { - ParticipantDevice[] devices = mChatRoom.getParticipants()[0].getDevices(); - if (devices.length == 1) { - oneParticipantOneDevice = true; - } - } + mChatRoomSecurityLevel.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View view) { + boolean oneParticipantOneDevice = false; + if (mChatRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt())) { + ParticipantDevice[] devices = + mChatRoom.getParticipants()[0].getDevices(); + if (devices.length == 1) { + oneParticipantOneDevice = true; + } + } - if (LinphonePreferences.instance().isLimeSecurityPopupEnabled()) { - showSecurityDialog(oneParticipantOneDevice); - } else { - if (oneParticipantOneDevice) { - ParticipantDevice device = mChatRoom.getParticipants()[0].getDevices()[0]; - LinphoneManager.getLc().inviteAddress(device.getAddress()); - } else { - LinphoneActivity.instance().goToContactDevicesInfos(getRemoteSipUri()); + if (LinphonePreferences.instance().isLimeSecurityPopupEnabled()) { + showSecurityDialog(oneParticipantOneDevice); + } else { + if (oneParticipantOneDevice) { + ParticipantDevice device = + mChatRoom.getParticipants()[0].getDevices()[0]; + LinphoneManager.getLc().inviteAddress(device.getAddress()); + } else { + LinphoneActivity.instance() + .goToContactDevicesInfos(getRemoteSipUri()); + } + } } - } - } - }); + }); mBackButton = view.findViewById(R.id.back); if (getResources().getBoolean(R.bool.isTablet)) { mBackButton.setVisibility(View.INVISIBLE); } else { - mBackButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - LinphoneActivity.instance().goToChatList(); - } - }); + mBackButton.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View view) { + LinphoneActivity.instance().goToChatList(); + } + }); } mCallButton = view.findViewById(R.id.start_call); - mCallButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - LinphoneActivity.instance().setAddresGoToDialerAndCall(mRemoteParticipantAddress.asString(), null, null); - } - }); + mCallButton.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View view) { + LinphoneActivity.instance() + .setAddresGoToDialerAndCall( + mRemoteParticipantAddress.asString(), null, null); + } + }); mBackToCallButton = view.findViewById(R.id.back_to_call); - mBackToCallButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - LinphoneActivity.instance().resetClassicMenuLayoutAndGoBackToCallIfStillRunning(); - } - }); + mBackToCallButton.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View view) { + LinphoneActivity.instance() + .resetClassicMenuLayoutAndGoBackToCallIfStillRunning(); + } + }); mGroupInfosButton = view.findViewById(R.id.group_infos); - mGroupInfosButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - if (mChatRoom == null) return; - ArrayList participants = new ArrayList<>(); - for (Participant p : mChatRoom.getParticipants()) { - Address a = p.getAddress(); - LinphoneContact c = ContactsManager.getInstance().findContactFromAddress(a); - if (c == null) { - c = new LinphoneContact(); - String displayName = LinphoneUtils.getAddressDisplayName(a); - c.setFullName(displayName); + mGroupInfosButton.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View view) { + if (mChatRoom == null) return; + ArrayList participants = new ArrayList<>(); + for (Participant p : mChatRoom.getParticipants()) { + Address a = p.getAddress(); + LinphoneContact c = + ContactsManager.getInstance().findContactFromAddress(a); + if (c == null) { + c = new LinphoneContact(); + String displayName = LinphoneUtils.getAddressDisplayName(a); + c.setFullName(displayName); + } + ContactAddress ca = + new ContactAddress( + c, a.asString(), "", c.isFriend(), p.isAdmin()); + participants.add(ca); + } + LinphoneActivity.instance() + .goToChatGroupInfos( + mRemoteSipAddress.asString(), + participants, + mChatRoom.getSubject(), + mChatRoom.getMe() != null + ? mChatRoom.getMe().isAdmin() + : false, + false, + null, + mChatRoom.hasCapability( + ChatRoomCapabilities.Encrypted.toInt())); } - ContactAddress ca = new ContactAddress(c, a.asString(), "", c.isFriend(), p.isAdmin()); - participants.add(ca); - } - LinphoneActivity.instance().goToChatGroupInfos(mRemoteSipAddress.asString(), participants, mChatRoom.getSubject(), - mChatRoom.getMe() != null ? mChatRoom.getMe().isAdmin() : false, false, null, - mChatRoom.hasCapability(ChatRoomCapabilities.Encrypted.toInt())); - } - }); + }); mRoomLabel = view.findViewById(R.id.subject); mParticipantsLabel = view.findViewById(R.id.participants); @@ -222,61 +247,67 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, mFilesUploadLayout = view.findViewById(R.id.file_upload_layout); mAttachImageButton = view.findViewById(R.id.send_picture); - mAttachImageButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - LinphoneActivity.instance().checkAndRequestPermissionsToSendImage(); - pickFile(); - } - }); + mAttachImageButton.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View view) { + LinphoneActivity.instance().checkAndRequestPermissionsToSendImage(); + pickFile(); + } + }); mSendMessageButton = view.findViewById(R.id.send_message); mSendMessageButton.setEnabled(false); - mSendMessageButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - sendMessage(); - } - }); + mSendMessageButton.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View view) { + sendMessage(); + } + }); mMessageTextToSend = view.findViewById(R.id.message); - mMessageTextToSend.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { - } + mMessageTextToSend.addTextChangedListener( + new TextWatcher() { + @Override + public void beforeTextChanged( + CharSequence charSequence, int i, int i1, int i2) {} - @Override - public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { - mSendMessageButton.setEnabled(mMessageTextToSend.getText().length() > 0 || mFilesUploadLayout.getChildCount() > 0); - if (mChatRoom != null && mMessageTextToSend.getText().length() > 0) { - if (!getResources().getBoolean(R.bool.allow_multiple_images_and_text)) { - mAttachImageButton.setEnabled(false); + @Override + public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { + mSendMessageButton.setEnabled( + mMessageTextToSend.getText().length() > 0 + || mFilesUploadLayout.getChildCount() > 0); + if (mChatRoom != null && mMessageTextToSend.getText().length() > 0) { + if (!getResources().getBoolean(R.bool.allow_multiple_images_and_text)) { + mAttachImageButton.setEnabled(false); + } + mChatRoom.compose(); + } else { + mAttachImageButton.setEnabled(true); + } } - mChatRoom.compose(); - } else { - mAttachImageButton.setEnabled(true); - } - } - @Override - public void afterTextChanged(Editable editable) { - } - }); + @Override + public void afterTextChanged(Editable editable) {} + }); mMessageTextToSend.clearFocus(); mRemoteComposing = view.findViewById(R.id.remote_composing); mChatEventsList = view.findViewById(R.id.chat_message_list); mSelectionHelper = new SelectableHelper(view, this); - layoutManager = new LinphoneLinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, true); + layoutManager = + new LinphoneLinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, true); mChatEventsList.setLayoutManager(layoutManager); - mChatScrollListener = new ChatScrollListener(layoutManager) { - @Override - public void onLoadMore(int page, int totalItemsCount, RecyclerView view) { - loadMoreData(totalItemsCount); - } - }; + mChatScrollListener = + new ChatScrollListener(layoutManager) { + @Override + public void onLoadMore(int page, int totalItemsCount, RecyclerView view) { + loadMoreData(totalItemsCount); + } + }; mChatEventsList.addOnScrollListener(mChatScrollListener); if (getArguments() != null) { @@ -285,8 +316,12 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, if (FileUtils.isExtensionImage(fileSharedUri)) { addImageToPendingList(fileSharedUri); } else { - if (fileSharedUri.startsWith("content://") || fileSharedUri.startsWith("file://")) { - fileSharedUri = FileUtils.getFilePath(getActivity().getApplicationContext(), Uri.parse(fileSharedUri)); + if (fileSharedUri.startsWith("content://") + || fileSharedUri.startsWith("file://")) { + fileSharedUri = + FileUtils.getFilePath( + getActivity().getApplicationContext(), + Uri.parse(fileSharedUri)); } else if (fileSharedUri.contains("com.android.contacts/contacts/")) { fileSharedUri = FileUtils.getCVSPathFromLookupUri(fileSharedUri).toString(); } @@ -316,10 +351,16 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, addVirtualKeyboardVisiblityListener(); // Force hide keyboard - getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); - InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(INPUT_METHOD_SERVICE); + getActivity() + .getWindow() + .setSoftInputMode( + WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN + | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); + InputMethodManager inputMethodManager = + (InputMethodManager) getActivity().getSystemService(INPUT_METHOD_SERVICE); if (getActivity().getCurrentFocus() != null) { - inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0); + inputMethodManager.hideSoftInputFromWindow( + getActivity().getCurrentFocus().getWindowToken(), 0); } initChatRoom(); @@ -345,7 +386,8 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, removeVirtualKeyboardVisiblityListener(); LinphoneManager.getInstance().setCurrentChatRoomAddress(null); if (mChatRoom != null) mChatRoom.removeListener(this); - if (mChatEventsList.getAdapter() != null) ((ChatMessagesGenericAdapter)mChatEventsList.getAdapter()).clear(); + if (mChatEventsList.getAdapter() != null) + ((ChatMessagesGenericAdapter) mChatEventsList.getAdapter()).clear(); super.onPause(); } @@ -357,13 +399,16 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, if (data != null && data.getData() != null) { if (data.getData().toString().contains("com.android.contacts/contacts/")) { if (FileUtils.getCVSPathFromLookupUri(data.getData().toString()) != null) { - fileToUploadPath = FileUtils.getCVSPathFromLookupUri(data.getData().toString()).toString(); + fileToUploadPath = + FileUtils.getCVSPathFromLookupUri(data.getData().toString()) + .toString(); } else { - //TODO Error + // TODO Error return; } } else { - fileToUploadPath = FileUtils.getRealPathFromURI(getActivity(), data.getData()); + fileToUploadPath = + FileUtils.getRealPathFromURI(getActivity(), data.getData()); } if (fileToUploadPath == null) { fileToUploadPath = data.getData().toString(); @@ -372,10 +417,15 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, fileToUploadPath = mImageToUploadUri.getPath(); } - if (fileToUploadPath.startsWith("content://") || fileToUploadPath.startsWith("file://")) { - fileToUploadPath = FileUtils.getFilePath(getActivity().getApplicationContext(), Uri.parse(fileToUploadPath)); + if (fileToUploadPath.startsWith("content://") + || fileToUploadPath.startsWith("file://")) { + fileToUploadPath = + FileUtils.getFilePath( + getActivity().getApplicationContext(), + Uri.parse(fileToUploadPath)); } else if (fileToUploadPath.contains("com.android.contacts/contacts/")) { - fileToUploadPath = FileUtils.getCVSPathFromLookupUri(fileToUploadPath).toString(); + fileToUploadPath = + FileUtils.getCVSPathFromLookupUri(fileToUploadPath).toString(); } if (FileUtils.isExtensionImage(fileToUploadPath)) { @@ -402,22 +452,25 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, if (message.getAppdata() != null && !message.isOutgoing()) { File file = new File(message.getAppdata()); if (file.exists()) { - file.delete(); // Delete downloaded file from incoming message that will be deleted + file.delete(); // Delete downloaded file from incoming message that will + // be deleted } } } eventLog.deleteFromDatabase(); } if (mChatRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt())) { - ((ChatMessagesGenericAdapter)mChatEventsList.getAdapter()).refresh(mChatRoom.getHistoryMessageEvents(MESSAGES_PER_PAGE)); + ((ChatMessagesGenericAdapter) mChatEventsList.getAdapter()) + .refresh(mChatRoom.getHistoryMessageEvents(MESSAGES_PER_PAGE)); } else { - ((ChatMessagesGenericAdapter)mChatEventsList.getAdapter()).refresh(mChatRoom.getHistoryEvents(MESSAGES_PER_PAGE)); + ((ChatMessagesGenericAdapter) mChatEventsList.getAdapter()) + .refresh(mChatRoom.getHistoryEvents(MESSAGES_PER_PAGE)); } } - @Override - public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { + public void onCreateContextMenu( + ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); if (mContext.getResources().getBoolean(R.bool.use_new_chat_bubbles_layout)) { @@ -428,7 +481,10 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, mContextMenuMessagePosition = holder.getAdapterPosition(); } - EventLog event = (EventLog) ((ChatMessagesGenericAdapter)mChatEventsList.getAdapter()).getItem(mContextMenuMessagePosition); + EventLog event = + (EventLog) + ((ChatMessagesGenericAdapter) mChatEventsList.getAdapter()) + .getItem(mContextMenuMessagePosition); if (event.getType() != EventLog.Type.ConferenceChatMessage) { return; } @@ -441,8 +497,10 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, inflater.inflate(R.menu.chat_bubble_menu, menu); } - if (!message.isOutgoing() || mChatRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt())) { - // Do not show incoming messages IDMN state in 1 to 1 chat room as we don't receive IMDN for them + if (!message.isOutgoing() + || mChatRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt())) { + // Do not show incoming messages IDMN state in 1 to 1 chat room as we don't receive IMDN + // for them menu.removeItem(R.id.imdn_infos); } if (!message.hasTextContent()) { @@ -463,7 +521,10 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, @Override public boolean onContextItemSelected(MenuItem item) { - EventLog event = (EventLog) ((ChatMessagesGenericAdapter)mChatEventsList.getAdapter()).getItem(mContextMenuMessagePosition); + EventLog event = + (EventLog) + ((ChatMessagesGenericAdapter) mChatEventsList.getAdapter()) + .getItem(mContextMenuMessagePosition); if (event.getType() != EventLog.Type.ConferenceChatMessage) { return super.onContextItemSelected(item); @@ -473,7 +534,8 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, String messageId = message.getMessageId(); if (item.getItemId() == R.id.resend) { - ((ChatMessagesGenericAdapter)mChatEventsList.getAdapter()).removeItem(mContextMenuMessagePosition); + ((ChatMessagesGenericAdapter) mChatEventsList.getAdapter()) + .removeItem(mContextMenuMessagePosition); message.resend(); return true; } @@ -483,7 +545,9 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, } if (item.getItemId() == R.id.copy_text) { if (message.hasTextContent()) { - ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE); + ClipboardManager clipboard = + (ClipboardManager) + getActivity().getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("Message", message.getTextContent()); clipboard.setPrimaryClip(clip); } @@ -491,73 +555,92 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, } if (item.getItemId() == R.id.delete_message) { mChatRoom.deleteMessage(message); - ((ChatMessagesGenericAdapter)mChatEventsList.getAdapter()).removeItem(mContextMenuMessagePosition); + ((ChatMessagesGenericAdapter) mChatEventsList.getAdapter()) + .removeItem(mContextMenuMessagePosition); return true; } if (item.getItemId() == R.id.add_to_contacts) { Address address = message.getFromAddress(); String uri = address.asStringUriOnly(); if (address != null && address.getDisplayName() != null) - LinphoneActivity.instance().displayContactsForEdition(address.asStringUriOnly(), address.getDisplayName()); - else - LinphoneActivity.instance().displayContactsForEdition(uri); + LinphoneActivity.instance() + .displayContactsForEdition( + address.asStringUriOnly(), address.getDisplayName()); + else LinphoneActivity.instance().displayContactsForEdition(uri); return true; } return super.onContextItemSelected(item); } private void loadMoreData(final int totalItemsCount) { - mHandler.post(new Runnable() { - @Override - public void run() { - int maxSize; - if (mChatRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt())) { - maxSize = mChatRoom.getHistorySize(); - } else { - maxSize = mChatRoom.getHistoryEventsSize(); - } - if (totalItemsCount < maxSize) { - int upperBound = totalItemsCount + MESSAGES_PER_PAGE; - if (upperBound > maxSize) { - upperBound = maxSize; + mHandler.post( + new Runnable() { + @Override + public void run() { + int maxSize; + if (mChatRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt())) { + maxSize = mChatRoom.getHistorySize(); + } else { + maxSize = mChatRoom.getHistoryEventsSize(); + } + if (totalItemsCount < maxSize) { + int upperBound = totalItemsCount + MESSAGES_PER_PAGE; + if (upperBound > maxSize) { + upperBound = maxSize; + } + EventLog[] newLogs; + if (mChatRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt())) { + newLogs = + mChatRoom.getHistoryRangeMessageEvents( + totalItemsCount, upperBound); + } else { + newLogs = + mChatRoom.getHistoryRangeEvents( + totalItemsCount, upperBound); + } + ArrayList logsList = new ArrayList<>(Arrays.asList(newLogs)); + ((ChatMessagesGenericAdapter) mChatEventsList.getAdapter()) + .addAllToHistory(logsList); + } } - EventLog[] newLogs; - if (mChatRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt())) { - newLogs = mChatRoom.getHistoryRangeMessageEvents(totalItemsCount, upperBound); - } else { - newLogs = mChatRoom.getHistoryRangeEvents(totalItemsCount, upperBound); - } - ArrayList logsList = new ArrayList<>(Arrays.asList(newLogs)); - ((ChatMessagesGenericAdapter) mChatEventsList.getAdapter()).addAllToHistory(logsList); - } - } - }); + }); } - /** - * Keyboard management - */ - + /** Keyboard management */ private void addVirtualKeyboardVisiblityListener() { - mKeyboardListener = new ViewTreeObserver.OnGlobalLayoutListener() { - @Override - public void onGlobalLayout() { - Rect visibleArea = new Rect(); - getActivity().getWindow().getDecorView().getWindowVisibleDisplayFrame(visibleArea); + mKeyboardListener = + new ViewTreeObserver.OnGlobalLayoutListener() { + @Override + public void onGlobalLayout() { + Rect visibleArea = new Rect(); + getActivity() + .getWindow() + .getDecorView() + .getWindowVisibleDisplayFrame(visibleArea); - int heightDiff = getActivity().getWindow().getDecorView().getRootView().getHeight() - (visibleArea.bottom - visibleArea.top); - if (heightDiff > 200) { - showKeyboardVisibleMode(); - } else { - hideKeyboardVisibleMode(); - } - } - }; - getActivity().getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(mKeyboardListener); + int heightDiff = + getActivity().getWindow().getDecorView().getRootView().getHeight() + - (visibleArea.bottom - visibleArea.top); + if (heightDiff > 200) { + showKeyboardVisibleMode(); + } else { + hideKeyboardVisibleMode(); + } + } + }; + getActivity() + .getWindow() + .getDecorView() + .getViewTreeObserver() + .addOnGlobalLayoutListener(mKeyboardListener); } private void removeVirtualKeyboardVisiblityListener() { - getActivity().getWindow().getDecorView().getViewTreeObserver().removeOnGlobalLayoutListener(mKeyboardListener); + getActivity() + .getWindow() + .getDecorView() + .getViewTreeObserver() + .removeOnGlobalLayoutListener(mKeyboardListener); } public void showKeyboardVisibleMode() { @@ -567,15 +650,14 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, } public void hideKeyboardVisibleMode() { - LinphoneActivity.instance().hideTabBar(getResources().getBoolean(R.bool.hide_bottom_bar_on_second_level_views)); + LinphoneActivity.instance() + .hideTabBar( + getResources().getBoolean(R.bool.hide_bottom_bar_on_second_level_views)); LinphoneActivity.instance().showStatusBar(); mTopBar.setVisibility(View.VISIBLE); } - /** - * View initialization - */ - + /** View initialization */ private void setReadOnly() { mMessageTextToSend.setEnabled(false); mAttachImageButton.setEnabled(false); @@ -585,7 +667,8 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, private void getContactsForParticipants() { mParticipants = new ArrayList<>(); if (mChatRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt())) { - LinphoneContact c = ContactsManager.getInstance().findContactFromAddress(mRemoteParticipantAddress); + LinphoneContact c = + ContactsManager.getInstance().findContactFromAddress(mRemoteParticipantAddress); if (c != null) { mParticipants.add(c); } @@ -593,7 +676,8 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, int index = 0; StringBuilder participantsLabel = new StringBuilder(); for (Participant p : mChatRoom.getParticipants()) { - LinphoneContact c = ContactsManager.getInstance().findContactFromAddress(p.getAddress()); + LinphoneContact c = + ContactsManager.getInstance().findContactFromAddress(p.getAddress()); if (c != null) { mParticipants.add(c); participantsLabel.append(c.getFullName()); @@ -608,14 +692,17 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, } if (mChatEventsList.getAdapter() != null) { - ((ChatMessagesGenericAdapter)mChatEventsList.getAdapter()).setContacts(mParticipants); + ((ChatMessagesGenericAdapter) mChatEventsList.getAdapter()).setContacts(mParticipants); } } private void initChatRoom() { Core core = LinphoneManager.getLcIfManagerNotDestroyedOrNull(); - if (mRemoteSipAddress == null || mRemoteSipUri == null || mRemoteSipUri.length() == 0 || core == null) { - //TODO error + if (mRemoteSipAddress == null + || mRemoteSipUri == null + || mRemoteSipUri.length() == 0 + || core == null) { + // TODO error return; } @@ -626,7 +713,8 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, LinphoneActivity.instance().refreshMissedChatCountDisplay(); mRemoteParticipantAddress = mRemoteSipAddress; - if (mChatRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt()) && mChatRoom.getParticipants().length > 0) { + if (mChatRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt()) + && mChatRoom.getParticipants().length > 0) { mRemoteParticipantAddress = mChatRoom.getParticipants()[0].getAddress(); } @@ -686,7 +774,6 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, case Unsafe: mChatRoomSecurityLevel.setImageResource(R.drawable.security_alert_indicator); break; - } } } @@ -694,11 +781,39 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, private void displayChatRoomHistory() { if (mChatRoom == null) return; if (mChatRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt())) { - mEventsAdapter = new ChatMessagesAdapter(this, mSelectionHelper, R.layout.chat_bubble, mChatRoom.getHistoryMessageEvents(MESSAGES_PER_PAGE), mParticipants, this); - mOldEventsAdapter = new ChatMessagesOldAdapter(this, mSelectionHelper, R.layout.chat_bubble_old, mChatRoom.getHistoryMessageEvents(MESSAGES_PER_PAGE), mParticipants, this); + mEventsAdapter = + new ChatMessagesAdapter( + this, + mSelectionHelper, + R.layout.chat_bubble, + mChatRoom.getHistoryMessageEvents(MESSAGES_PER_PAGE), + mParticipants, + this); + mOldEventsAdapter = + new ChatMessagesOldAdapter( + this, + mSelectionHelper, + R.layout.chat_bubble_old, + mChatRoom.getHistoryMessageEvents(MESSAGES_PER_PAGE), + mParticipants, + this); } else { - mEventsAdapter = new ChatMessagesAdapter(this, mSelectionHelper, R.layout.chat_bubble, mChatRoom.getHistoryEvents(MESSAGES_PER_PAGE), mParticipants, this); - mOldEventsAdapter = new ChatMessagesOldAdapter(this, mSelectionHelper, R.layout.chat_bubble_old, mChatRoom.getHistoryEvents(MESSAGES_PER_PAGE), mParticipants, this); + mEventsAdapter = + new ChatMessagesAdapter( + this, + mSelectionHelper, + R.layout.chat_bubble, + mChatRoom.getHistoryEvents(MESSAGES_PER_PAGE), + mParticipants, + this); + mOldEventsAdapter = + new ChatMessagesOldAdapter( + this, + mSelectionHelper, + R.layout.chat_bubble_old, + mChatRoom.getHistoryEvents(MESSAGES_PER_PAGE), + mParticipants, + this); } if (mContext.getResources().getBoolean(R.bool.use_new_chat_bubbles_layout)) { mSelectionHelper.setAdapter(mEventsAdapter); @@ -711,7 +826,8 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, } private void showSecurityDialog(boolean oneParticipantOneDevice) { - final Dialog dialog = LinphoneActivity.instance().displayDialog(getString(R.string.lime_security_popup)); + final Dialog dialog = + LinphoneActivity.instance().displayDialog(getString(R.string.lime_security_popup)); Button delete = dialog.findViewById(R.id.dialog_delete_button); delete.setVisibility(View.GONE); Button ok = dialog.findViewById(R.id.dialog_ok_button); @@ -722,42 +838,47 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, dialog.findViewById(R.id.dialog_do_not_ask_again_layout).setVisibility(View.VISIBLE); final CheckBox doNotAskAgain = dialog.findViewById(R.id.doNotAskAgain); - dialog.findViewById(R.id.doNotAskAgainLabel).setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - doNotAskAgain.setChecked(!doNotAskAgain.isChecked()); - } - }); + dialog.findViewById(R.id.doNotAskAgainLabel) + .setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View v) { + doNotAskAgain.setChecked(!doNotAskAgain.isChecked()); + } + }); ok.setTag(oneParticipantOneDevice); - ok.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - boolean oneParticipantOneDevice = (boolean) view.getTag(); - if (doNotAskAgain.isChecked()) { - LinphonePreferences.instance().enableLimeSecurityPopup(false); - } + ok.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View view) { + boolean oneParticipantOneDevice = (boolean) view.getTag(); + if (doNotAskAgain.isChecked()) { + LinphonePreferences.instance().enableLimeSecurityPopup(false); + } - if (oneParticipantOneDevice) { - ParticipantDevice device = mChatRoom.getParticipants()[0].getDevices()[0]; - LinphoneManager.getLc().inviteAddress(device.getAddress()); - } else { - LinphoneActivity.instance().goToContactDevicesInfos(getRemoteSipUri()); - } + if (oneParticipantOneDevice) { + ParticipantDevice device = + mChatRoom.getParticipants()[0].getDevices()[0]; + LinphoneManager.getLc().inviteAddress(device.getAddress()); + } else { + LinphoneActivity.instance().goToContactDevicesInfos(getRemoteSipUri()); + } - dialog.dismiss(); - } - }); + dialog.dismiss(); + } + }); - cancel.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - if (doNotAskAgain.isChecked()) { - LinphonePreferences.instance().enableLimeSecurityPopup(false); - } - dialog.dismiss(); - } - }); + cancel.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View view) { + if (doNotAskAgain.isChecked()) { + LinphonePreferences.instance().enableLimeSecurityPopup(false); + } + dialog.dismiss(); + } + }); dialog.show(); } @@ -776,10 +897,7 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, } } - /** - * File transfer related - */ - + /** File transfer related */ @Override public void onSaveInstanceState(Bundle outState) { String files[] = new String[mFilesUploadLayout.getChildCount()]; @@ -808,7 +926,13 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, private void pickFile() { List cameraIntents = new ArrayList<>(); Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); - File file = new File(FileUtils.getStorageDirectory(mContext), getString(R.string.temp_photo_name_with_date).replace("%s", String.valueOf(System.currentTimeMillis()) + ".jpeg")); + File file = + new File( + FileUtils.getStorageDirectory(mContext), + getString(R.string.temp_photo_name_with_date) + .replace( + "%s", + String.valueOf(System.currentTimeMillis()) + ".jpeg")); mImageToUploadUri = Uri.fromFile(file); captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageToUploadUri); cameraIntents.add(captureIntent); @@ -822,8 +946,10 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, fileIntent.setAction(Intent.ACTION_GET_CONTENT); cameraIntents.add(fileIntent); - Intent chooserIntent = Intent.createChooser(galleryIntent, getString(R.string.image_picker_title)); - chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{})); + Intent chooserIntent = + Intent.createChooser(galleryIntent, getString(R.string.image_picker_title)); + chooserIntent.putExtra( + Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[] {})); startActivityForResult(chooserIntent, ADD_PHOTO); } @@ -843,16 +969,19 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, ImageView remove = pendingFile.findViewById(R.id.remove); remove.setTag(pendingFile); - remove.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - View pendingImage = (View) view.getTag(); - mFilesUploadLayout.removeView(pendingImage); - mAttachImageButton.setEnabled(true); - mMessageTextToSend.setEnabled(true); - mSendMessageButton.setEnabled(mMessageTextToSend.getText().length() > 0 || mFilesUploadLayout.getChildCount() > 0); - } - }); + remove.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View view) { + View pendingImage = (View) view.getTag(); + mFilesUploadLayout.removeView(pendingImage); + mAttachImageButton.setEnabled(true); + mMessageTextToSend.setEnabled(true); + mSendMessageButton.setEnabled( + mMessageTextToSend.getText().length() > 0 + || mFilesUploadLayout.getChildCount() > 0); + } + }); mFilesUploadLayout.addView(pendingFile); @@ -874,7 +1003,8 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, return; } - View pendingImage = mInflater.inflate(R.layout.image_upload_cell, mFilesUploadLayout, false); + View pendingImage = + mInflater.inflate(R.layout.image_upload_cell, mFilesUploadLayout, false); pendingImage.setTag(path); ImageView image = pendingImage.findViewById(R.id.pendingImageForUpload); @@ -884,16 +1014,19 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, ImageView remove = pendingImage.findViewById(R.id.remove); remove.setTag(pendingImage); - remove.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - View pendingImage = (View) view.getTag(); - mFilesUploadLayout.removeView(pendingImage); - mAttachImageButton.setEnabled(true); - mMessageTextToSend.setEnabled(true); - mSendMessageButton.setEnabled(mMessageTextToSend.getText().length() > 0 || mFilesUploadLayout.getChildCount() > 0); - } - }); + remove.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View view) { + View pendingImage = (View) view.getTag(); + mFilesUploadLayout.removeView(pendingImage); + mAttachImageButton.setEnabled(true); + mMessageTextToSend.setEnabled(true); + mSendMessageButton.setEnabled( + mMessageTextToSend.getText().length() > 0 + || mFilesUploadLayout.getChildCount() > 0); + } + }); mFilesUploadLayout.addView(pendingImage); @@ -904,10 +1037,7 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, mSendMessageButton.setEnabled(true); } - /** - * Message sending - */ - + /** Message sending */ private void sendMessage() { ChatMessage msg = mChatRoom.createEmptyMessage(); @@ -941,7 +1071,8 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, msg.addTextContent(text); } - // Set listener not required here anymore, message will be added to messages list and adapter will set the listener + // Set listener not required here anymore, message will be added to messages list and + // adapter will set the listener if (msg.getContents().length > 0) { msg.send(); } @@ -958,27 +1089,23 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, @Override public void onChatMessageSent(ChatRoom cr, EventLog event) { - ((ChatMessagesGenericAdapter)mChatEventsList.getAdapter()).addToHistory(event); + ((ChatMessagesGenericAdapter) mChatEventsList.getAdapter()).addToHistory(event); scrollToBottom(); } @Override - public void onConferenceAddressGeneration(ChatRoom cr) { - - } + public void onConferenceAddressGeneration(ChatRoom cr) {} @Override - public void onParticipantDeviceFetchRequested(ChatRoom cr, Address addr) { - - } + public void onParticipantDeviceFetchRequested(ChatRoom cr, Address addr) {} @Override - public void onParticipantRegistrationSubscriptionRequested(ChatRoom cr, Address participantAddr) { - } + public void onParticipantRegistrationSubscriptionRequested( + ChatRoom cr, Address participantAddr) {} @Override - public void onParticipantRegistrationUnsubscriptionRequested(ChatRoom cr, Address participantAddr) { - } + public void onParticipantRegistrationUnsubscriptionRequested( + ChatRoom cr, Address participantAddr) {} @Override public void onUndecryptableMessageReceived(ChatRoom cr, ChatMessage msg) { @@ -988,36 +1115,66 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, if (LinphoneActivity.instance().isOnBackground()) { if (!getResources().getBoolean(R.bool.disable_chat_message_notification)) { if (contact != null) { - LinphoneService.instance().getNotificationManager().displayMessageNotification(from.asStringUriOnly(), - contact.getFullName(), contact.getThumbnailUri(), getString(R.string.message_cant_be_decrypted_notif), cr.getLocalAddress(), msg.getTime(), null, null); + LinphoneService.instance() + .getNotificationManager() + .displayMessageNotification( + from.asStringUriOnly(), + contact.getFullName(), + contact.getThumbnailUri(), + getString(R.string.message_cant_be_decrypted_notif), + cr.getLocalAddress(), + msg.getTime(), + null, + null); } else { - LinphoneService.instance().getNotificationManager().displayMessageNotification(from.asStringUriOnly(), - from.getUsername(), null, getString(R.string.message_cant_be_decrypted_notif), cr.getLocalAddress(), msg.getTime(), null, null); + LinphoneService.instance() + .getNotificationManager() + .displayMessageNotification( + from.asStringUriOnly(), + from.getUsername(), + null, + getString(R.string.message_cant_be_decrypted_notif), + cr.getLocalAddress(), + msg.getTime(), + null, + null); } } } else if (LinphoneManager.getLc().limeEnabled() == LimeState.Mandatory) { - final Dialog dialog = LinphoneActivity.instance().displayDialog( - getString(R.string.message_cant_be_decrypted) - .replace("%s", (contact != null) ? contact.getFullName() : from.getUsername())); + final Dialog dialog = + LinphoneActivity.instance() + .displayDialog( + getString(R.string.message_cant_be_decrypted) + .replace( + "%s", + (contact != null) + ? contact.getFullName() + : from.getUsername())); Button delete = dialog.findViewById(R.id.dialog_delete_button); delete.setText(getString(R.string.call)); Button cancel = dialog.findViewById(R.id.dialog_cancel_button); cancel.setText(getString(R.string.ok)); - delete.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - LinphoneManager.getInstance().newOutgoingCall(from.asStringUriOnly() - , (contact != null) ? contact.getFullName() : from.getUsername()); - dialog.dismiss(); - } - }); + delete.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View view) { + LinphoneManager.getInstance() + .newOutgoingCall( + from.asStringUriOnly(), + (contact != null) + ? contact.getFullName() + : from.getUsername()); + dialog.dismiss(); + } + }); - cancel.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - dialog.dismiss(); - } - }); + cancel.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View view) { + dialog.dismiss(); + } + }); dialog.show(); } } @@ -1029,7 +1186,8 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, LinphoneActivity.instance().refreshMissedChatCountDisplay(); ChatMessage msg = event.getChatMessage(); - if (msg.getErrorInfo() != null && msg.getErrorInfo().getReason() == Reason.UnsupportedContent) { + if (msg.getErrorInfo() != null + && msg.getErrorInfo().getReason() == Reason.UnsupportedContent) { Log.w("Message received but content is unsupported, do not display it"); return; } @@ -1045,7 +1203,7 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, LinphoneActivity.instance().checkAndRequestExternalStoragePermission(); } - ((ChatMessagesGenericAdapter)mChatEventsList.getAdapter()).addToHistory(event); + ((ChatMessagesGenericAdapter) mChatEventsList.getAdapter()).addToHistory(event); scrollToBottom(); } @@ -1062,7 +1220,8 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, } } if (!found) { - LinphoneContact contact = ContactsManager.getInstance().findContactFromAddress(remoteAddr); + LinphoneContact contact = + ContactsManager.getInstance().findContactFromAddress(remoteAddr); String displayName; if (contact != null) { if (contact.getFullName() != null) { @@ -1081,7 +1240,8 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, if (composing.size() == 0) { mRemoteComposing.setVisibility(View.GONE); } else if (composing.size() == 1) { - mRemoteComposing.setText(getString(R.string.remote_composing_single).replace("%s", composing.get(0))); + mRemoteComposing.setText( + getString(R.string.remote_composing_single).replace("%s", composing.get(0))); } else { StringBuilder remotes = new StringBuilder(); int i = 0; @@ -1092,14 +1252,14 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, remotes.append(", "); } } - mRemoteComposing.setText(getString(R.string.remote_composing_multiple).replace("%s", remotes.toString())); + mRemoteComposing.setText( + getString(R.string.remote_composing_multiple) + .replace("%s", remotes.toString())); } } @Override - public void onMessageReceived(ChatRoom cr, ChatMessage msg) { - - } + public void onMessageReceived(ChatRoom cr, ChatMessage msg) {} @Override public void onConferenceJoined(ChatRoom cr, EventLog event) { @@ -1107,63 +1267,57 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, // So we have to refresh the display when information is available // In the meantime header will be chatroom-xxxxxxx if (mChatRoom == null) mChatRoom = cr; - if (mChatRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt()) && mChatRoom.getParticipants().length > 0) { + if (mChatRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt()) + && mChatRoom.getParticipants().length > 0) { mRemoteParticipantAddress = mChatRoom.getParticipants()[0].getAddress(); } getContactsForParticipants(); displayChatRoomHeader(); if (mChatRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt())) return; - ((ChatMessagesGenericAdapter)mChatEventsList.getAdapter()).addToHistory(event); + ((ChatMessagesGenericAdapter) mChatEventsList.getAdapter()).addToHistory(event); scrollToBottom(); } @Override public void onConferenceLeft(ChatRoom cr, EventLog event) { if (mChatRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt())) return; - ((ChatMessagesGenericAdapter)mChatEventsList.getAdapter()).addToHistory(event); + ((ChatMessagesGenericAdapter) mChatEventsList.getAdapter()).addToHistory(event); scrollToBottom(); } @Override public void onParticipantAdminStatusChanged(ChatRoom cr, EventLog event) { if (mChatRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt())) return; - ((ChatMessagesGenericAdapter)mChatEventsList.getAdapter()).addToHistory(event); + ((ChatMessagesGenericAdapter) mChatEventsList.getAdapter()).addToHistory(event); scrollToBottom(); } @Override - public void onParticipantDeviceRemoved(ChatRoom cr, EventLog event) { - - } + public void onParticipantDeviceRemoved(ChatRoom cr, EventLog event) {} @Override public void onParticipantRemoved(ChatRoom cr, EventLog event) { if (mChatRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt())) return; getContactsForParticipants(); - ((ChatMessagesGenericAdapter)mChatEventsList.getAdapter()).addToHistory(event); + ((ChatMessagesGenericAdapter) mChatEventsList.getAdapter()).addToHistory(event); scrollToBottom(); } @Override - public void onChatMessageShouldBeStored(ChatRoom cr, ChatMessage msg) { - - } + public void onChatMessageShouldBeStored(ChatRoom cr, ChatMessage msg) {} @Override - public void onParticipantsCapabilitiesChecked(ChatRoom cr, Address deviceAddr, Address[] participantsAddr) { - - } + public void onParticipantsCapabilitiesChecked( + ChatRoom cr, Address deviceAddr, Address[] participantsAddr) {} @Override - public void onParticipantDeviceAdded(ChatRoom cr, EventLog event) { - - } + public void onParticipantDeviceAdded(ChatRoom cr, EventLog event) {} @Override public void onSecurityEvent(ChatRoom cr, EventLog eventLog) { updateSecurityLevelIcon(); - ((ChatMessagesGenericAdapter)mChatEventsList.getAdapter()).addToHistory(eventLog); + ((ChatMessagesGenericAdapter) mChatEventsList.getAdapter()).addToHistory(eventLog); scrollToBottom(); } @@ -1178,7 +1332,7 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, public void onParticipantAdded(ChatRoom cr, EventLog event) { if (mChatRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt())) return; getContactsForParticipants(); - ((ChatMessagesGenericAdapter)mChatEventsList.getAdapter()).addToHistory(event); + ((ChatMessagesGenericAdapter) mChatEventsList.getAdapter()).addToHistory(event); scrollToBottom(); } @@ -1186,7 +1340,7 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, public void onSubjectChanged(ChatRoom cr, EventLog event) { if (mChatRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt())) return; mRoomLabel.setText(event.getSubject()); - ((ChatMessagesGenericAdapter)mChatEventsList.getAdapter()).addToHistory(event); + ((ChatMessagesGenericAdapter) mChatEventsList.getAdapter()).addToHistory(event); scrollToBottom(); } @@ -1197,7 +1351,8 @@ public class ChatMessagesFragment extends Fragment implements ChatRoomListener, // This is a workaround to prevent a crash from happening while rotating the device private class LinphoneLinearLayoutManager extends LinearLayoutManager { - public LinphoneLinearLayoutManager(Context context, int orientation, boolean reverseLayout) { + public LinphoneLinearLayoutManager( + Context context, int orientation, boolean reverseLayout) { super(context, orientation, reverseLayout); } diff --git a/app/src/main/java/org/linphone/chat/ChatMessagesGenericAdapter.java b/app/src/main/java/org/linphone/chat/ChatMessagesGenericAdapter.java index 862fe2310..f4176bf08 100644 --- a/app/src/main/java/org/linphone/chat/ChatMessagesGenericAdapter.java +++ b/app/src/main/java/org/linphone/chat/ChatMessagesGenericAdapter.java @@ -1,28 +1,27 @@ package org.linphone.chat; /* - ChatMessagesGenericAdapter.java - Copyright (C) 2018 Belledonne Communications, Grenoble, France +ChatMessagesGenericAdapter.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 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. +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 org.linphone.contacts.LinphoneContact; -import org.linphone.core.EventLog; +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +*/ import java.util.ArrayList; +import org.linphone.contacts.LinphoneContact; +import org.linphone.core.EventLog; public interface ChatMessagesGenericAdapter { void addToHistory(EventLog log); diff --git a/app/src/main/java/org/linphone/chat/ChatMessagesOldAdapter.java b/app/src/main/java/org/linphone/chat/ChatMessagesOldAdapter.java index a23d69e95..31578916d 100644 --- a/app/src/main/java/org/linphone/chat/ChatMessagesOldAdapter.java +++ b/app/src/main/java/org/linphone/chat/ChatMessagesOldAdapter.java @@ -19,22 +19,15 @@ along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ +import static android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION; + import android.Manifest; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; -import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; -import android.graphics.Matrix; -import android.graphics.drawable.BitmapDrawable; -import android.graphics.drawable.Drawable; -import android.media.ExifInterface; import android.net.Uri; -import android.os.AsyncTask; -import android.provider.MediaStore; -import androidx.annotation.NonNull; -import androidx.core.content.FileProvider; import android.text.Spanned; import android.text.method.LinkMovementMethod; import android.view.LayoutInflater; @@ -43,7 +36,13 @@ import android.view.ViewGroup; import android.webkit.MimeTypeMap; import android.widget.ImageView; import android.widget.RelativeLayout; - +import androidx.annotation.NonNull; +import androidx.core.content.FileProvider; +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; import org.linphone.LinphoneActivity; import org.linphone.LinphoneManager; import org.linphone.R; @@ -65,18 +64,8 @@ import org.linphone.views.AsyncBitmap; import org.linphone.views.BitmapWorkerTask; import org.linphone.views.ContactAvatar; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.lang.ref.WeakReference; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import static android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION; - -public class ChatMessagesOldAdapter extends SelectableAdapter implements ChatMessagesGenericAdapter { +public class ChatMessagesOldAdapter extends SelectableAdapter + implements ChatMessagesGenericAdapter { private static int MARGIN_BETWEEN_MESSAGES = 10; private static int SIDE_MARGIN = 100; @@ -90,7 +79,13 @@ public class ChatMessagesOldAdapter extends SelectableAdapter participants, ChatMessageViewHolderClickListener clickListener) { + public ChatMessagesOldAdapter( + ChatMessagesFragment fragment, + SelectableHelper helper, + int itemResource, + EventLog[] history, + ArrayList participants, + ChatMessageViewHolderClickListener clickListener) { super(helper); mFragment = fragment; mContext = mFragment.getActivity(); @@ -99,51 +94,55 @@ public class ChatMessagesOldAdapter extends SelectableAdapter 0 && mContext.getResources().getBoolean(R.bool.lower_space_between_chat_bubbles_if_same_person)) { + if (position > 0 + && mContext.getResources() + .getBoolean(R.bool.lower_space_between_chat_bubbles_if_same_person)) { EventLog previousEvent = (EventLog) getItem(position - 1); if (previousEvent.getType() == EventLog.Type.ConferenceChatMessage) { ChatMessage previousMessage = previousEvent.getChatMessage(); @@ -192,7 +193,10 @@ public class ChatMessagesOldAdapter extends SelectableAdapter) getArguments().getSerializable("selectedContacts"); + mContactsSelected = + (ArrayList) + getArguments().getSerializable("selectedContacts"); } mChatRoomSubject = getArguments().getString("subject"); mChatRoomAddress = getArguments().getString("groupChatRoomAddress"); @@ -127,21 +131,24 @@ public class ChatRoomCreationFragment extends Fragment implements View.OnClickLi mContactsFetchInProgress = view.findViewById(R.id.contactsFetchInProgress); mContactsFetchInProgress.setVisibility(View.VISIBLE); - mSearchAdapter = new SearchContactsListAdapter(null, mContactsFetchInProgress, this, mCreateGroupChatRoom == false); + mSearchAdapter = + new SearchContactsListAdapter( + null, mContactsFetchInProgress, this, mCreateGroupChatRoom == false); mSearchField = view.findViewById(R.id.searchField); - mSearchField.setOnQueryTextListener(new SearchView.OnQueryTextListener() { - @Override - public boolean onQueryTextSubmit(String query) { - return true; - } + mSearchField.setOnQueryTextListener( + new SearchView.OnQueryTextListener() { + @Override + public boolean onQueryTextSubmit(String query) { + return true; + } - @Override - public boolean onQueryTextChange(String newText) { - mSearchAdapter.searchContacts(newText, mContactsList); - return true; - } - }); + @Override + public boolean onQueryTextChange(String newText) { + mSearchAdapter.searchContacts(newText, mContactsList); + return true; + } + }); mLinphoneContactsToggle = view.findViewById(R.id.layout_linphone_contacts); mAllContactsToggle = view.findViewById(R.id.layout_all_contacts); @@ -149,39 +156,49 @@ public class ChatRoomCreationFragment extends Fragment implements View.OnClickLi mSecurityToggle = view.findViewById(R.id.security_toogle); mSecurityToggleOn = view.findViewById(R.id.security_toogle_on); mSecurityToggleOff = view.findViewById(R.id.security_toogle_off); - mSecurityToggleOn.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - mSecurityToggle.setChecked(true); - } - }); - mSecurityToggleOff.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - mSecurityToggle.setChecked(false); - } - }); + mSecurityToggleOn.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View v) { + mSecurityToggle.setChecked(true); + } + }); + mSecurityToggleOff.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View v) { + mSecurityToggle.setChecked(false); + } + }); mSecurityToggle.setChecked(mChatRoomEncrypted); ProxyConfig lpc = LinphoneManager.getLc().getDefaultProxyConfig(); - if ((mChatRoomSubject != null && mChatRoomAddress != null) || (lpc == null || lpc.getConferenceFactoryUri() == null)) { + if ((mChatRoomSubject != null && mChatRoomAddress != null) + || (lpc == null || lpc.getConferenceFactoryUri() == null)) { mSecurityToggle.setVisibility(View.GONE); mSecurityToggleOn.setVisibility(View.GONE); mSecurityToggleOff.setVisibility(View.GONE); } - LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity().getApplicationContext()); + LinearLayoutManager layoutManager = + new LinearLayoutManager(getActivity().getApplicationContext()); mContactsList.setAdapter(mSearchAdapter); - DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(mContactsList.getContext(), - layoutManager.getOrientation()); - dividerItemDecoration.setDrawable(getActivity().getApplicationContext().getResources().getDrawable(R.drawable.divider)); + DividerItemDecoration dividerItemDecoration = + new DividerItemDecoration( + mContactsList.getContext(), layoutManager.getOrientation()); + dividerItemDecoration.setDrawable( + getActivity() + .getApplicationContext() + .getResources() + .getDrawable(R.drawable.divider)); mContactsList.addItemDecoration(dividerItemDecoration); mContactsList.setLayoutManager(layoutManager); - if (savedInstanceState != null && savedInstanceState.getStringArrayList("mContactsSelected") != null) { + if (savedInstanceState != null + && savedInstanceState.getStringArrayList("mContactsSelected") != null) { mContactsSelectedLayout.removeAllViews(); // We need to get all contacts not only sip for (String uri : savedInstanceState.getStringArrayList("mContactsSelected")) { @@ -197,7 +214,8 @@ public class ChatRoomCreationFragment extends Fragment implements View.OnClickLi updateListSelected(); } - mOnlyDisplayLinphoneContacts = ContactsManager.getInstance().getSIPContacts().size() > 0 ? true : false; + mOnlyDisplayLinphoneContacts = + ContactsManager.getInstance().getSIPContacts().size() > 0 ? true : false; if (savedInstanceState != null) { mOnlyDisplayLinphoneContacts = savedInstanceState.getBoolean("onlySipContact", true); } @@ -206,34 +224,37 @@ public class ChatRoomCreationFragment extends Fragment implements View.OnClickLi displayChatCreation(); - mChatRoomCreationListener = new ChatRoomListenerStub() { - @Override - public void onStateChanged(ChatRoom cr, ChatRoom.State newState) { - if (newState == ChatRoom.State.Created) { - mWaitLayout.setVisibility(View.GONE); - LinphoneActivity.instance().goToChat(cr.getPeerAddress().asStringUriOnly(), mShareInfos); - } else if (newState == ChatRoom.State.CreationFailed) { - mWaitLayout.setVisibility(View.GONE); - LinphoneActivity.instance().displayChatRoomError(); - Log.e("Group chat room for address " + cr.getPeerAddress() + " has failed !"); - } - } - }; + mChatRoomCreationListener = + new ChatRoomListenerStub() { + @Override + public void onStateChanged(ChatRoom cr, ChatRoom.State newState) { + if (newState == ChatRoom.State.Created) { + mWaitLayout.setVisibility(View.GONE); + LinphoneActivity.instance() + .goToChat(cr.getPeerAddress().asStringUriOnly(), mShareInfos); + } else if (newState == ChatRoom.State.CreationFailed) { + mWaitLayout.setVisibility(View.GONE); + LinphoneActivity.instance().displayChatRoomError(); + Log.e( + "Group chat room for address " + + cr.getPeerAddress() + + " has failed !"); + } + } + }; if (getArguments() != null) { String fileSharedUri = getArguments().getString("fileSharedUri"); String messageDraft = getArguments().getString("messageDraft"); - if (fileSharedUri != null || messageDraft != null) - mShareInfos = new Bundle(); + if (fileSharedUri != null || messageDraft != null) mShareInfos = new Bundle(); if (fileSharedUri != null) { LinphoneActivity.instance().checkAndRequestPermissionsToSendImage(); mShareInfos.putString("fileSharedUri", fileSharedUri); } - if (messageDraft != null) - mShareInfos.putString("messageDraft", messageDraft); + if (messageDraft != null) mShareInfos.putString("messageDraft", messageDraft); } return view; @@ -248,9 +269,11 @@ public class ChatRoomCreationFragment extends Fragment implements View.OnClickLi LinphoneActivity.instance().selectMenu(FragmentsAvailable.CREATE_CHAT); } - InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(INPUT_METHOD_SERVICE); + InputMethodManager inputMethodManager = + (InputMethodManager) getActivity().getSystemService(INPUT_METHOD_SERVICE); if (getActivity().getCurrentFocus() != null) { - inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0); + inputMethodManager.hideSoftInputFromWindow( + getActivity().getCurrentFocus().getWindowToken(), 0); } } @@ -337,11 +360,12 @@ public class ChatRoomCreationFragment extends Fragment implements View.OnClickLi private int getIndexOfCa(ContactAddress ca, List caList) { for (int i = 0; i < caList.size(); i++) { if (ca.getAddress() != null && ca.getAddress().getUsername() != null) { - if (caList.get(i).getAddressAsDisplayableString().compareTo(ca.getAddressAsDisplayableString()) == 0) - return i; + if (caList.get(i) + .getAddressAsDisplayableString() + .compareTo(ca.getAddressAsDisplayableString()) + == 0) return i; } else if (ca.getPhoneNumber() != null && caList.get(i).getPhoneNumber() != null) { - if (ca.getPhoneNumber().compareTo(caList.get(i).getPhoneNumber()) == 0) - return i; + if (ca.getPhoneNumber().compareTo(caList.get(i).getPhoneNumber()) == 0) return i; } } return -1; @@ -353,15 +377,21 @@ public class ChatRoomCreationFragment extends Fragment implements View.OnClickLi } private void addSelectedContactAddress(ContactAddress ca) { - View viewContact = LayoutInflater.from(LinphoneActivity.instance()).inflate(R.layout.contact_selected, null); + View viewContact = + LayoutInflater.from(LinphoneActivity.instance()) + .inflate(R.layout.contact_selected, null); if (ca.getContact() != null) { - String name = (ca.getContact().getFullName() != null && !ca.getContact().getFullName().isEmpty()) ? - ca.getContact().getFullName() : (ca.getDisplayName() != null) ? - ca.getDisplayName() : (ca.getUsername() != null) ? - ca.getUsername() : ""; + String name = + (ca.getContact().getFullName() != null + && !ca.getContact().getFullName().isEmpty()) + ? ca.getContact().getFullName() + : (ca.getDisplayName() != null) + ? ca.getDisplayName() + : (ca.getUsername() != null) ? ca.getUsername() : ""; ((TextView) viewContact.findViewById(R.id.sipUri)).setText(name); } else { - ((TextView) viewContact.findViewById(R.id.sipUri)).setText(ca.getAddressAsDisplayableString()); + ((TextView) viewContact.findViewById(R.id.sipUri)) + .setText(ca.getAddressAsDisplayableString()); } View removeContact = viewContact.findViewById(R.id.contactChatDelete); removeContact.setTag(ca); @@ -390,7 +420,6 @@ public class ChatRoomCreationFragment extends Fragment implements View.OnClickLi } mSearchAdapter.setContactsSelectedList(mContactsSelected); mContactsSelectedLayout.invalidate(); - } private void addOrRemoveContactFromSelection(ContactAddress ca) { @@ -443,9 +472,25 @@ public class ChatRoomCreationFragment extends Fragment implements View.OnClickLi } else if (id == R.id.next) { if (mChatRoomAddress == null && mChatRoomSubject == null) { mContactsSelectedLayout.removeAllViews(); - LinphoneActivity.instance().goToChatGroupInfos(null, mContactsSelected, null, true, false, mShareInfos, mSecurityToggle.isChecked()); + LinphoneActivity.instance() + .goToChatGroupInfos( + null, + mContactsSelected, + null, + true, + false, + mShareInfos, + mSecurityToggle.isChecked()); } else { - LinphoneActivity.instance().goToChatGroupInfos(mChatRoomAddress, mContactsSelected, mChatRoomSubject, true, true, mShareInfos, mSecurityToggle.isChecked()); + LinphoneActivity.instance() + .goToChatGroupInfos( + mChatRoomAddress, + mContactsSelected, + mChatRoomSubject, + true, + true, + mShareInfos, + mSecurityToggle.isChecked()); } } else if (id == R.id.clearSearchField) { mSearchField.setQuery("", false); @@ -464,32 +509,47 @@ public class ChatRoomCreationFragment extends Fragment implements View.OnClickLi boolean createEncryptedChatRoom = mSecurityToggle.isChecked(); if (lpc == null || lpc.getConferenceFactoryUri() == null || mCreateGroupChatRoom == false) { if (createEncryptedChatRoom && lpc != null && lpc.getConferenceFactoryUri() != null) { - mChatRoom = lc.findOneToOneChatRoom(lpc.getIdentityAddress(), ca.getAddress(), true); + mChatRoom = + lc.findOneToOneChatRoom(lpc.getIdentityAddress(), ca.getAddress(), true); if (mChatRoom != null) { - LinphoneActivity.instance().goToChat(mChatRoom.getPeerAddress().asStringUriOnly(), mShareInfos); + LinphoneActivity.instance() + .goToChat(mChatRoom.getPeerAddress().asStringUriOnly(), mShareInfos); } else { - mChatRoom = lc.createClientGroupChatRoom(getString(R.string.dummy_group_chat_subject), !createEncryptedChatRoom, createEncryptedChatRoom); + mChatRoom = + lc.createClientGroupChatRoom( + getString(R.string.dummy_group_chat_subject), + !createEncryptedChatRoom, + createEncryptedChatRoom); mChatRoom.addListener(mChatRoomCreationListener); Address participants[] = new Address[1]; participants[0] = ca.getAddress(); mChatRoom.addParticipants(participants); } } else { - if (lpc != null && lpc.getConferenceFactoryUri() != null && !LinphonePreferences.instance().useBasicChatRoomFor1To1()) { - mChatRoom = lc.findOneToOneChatRoom(lpc.getIdentityAddress(), ca.getAddress(), false); + if (lpc != null + && lpc.getConferenceFactoryUri() != null + && !LinphonePreferences.instance().useBasicChatRoomFor1To1()) { + mChatRoom = + lc.findOneToOneChatRoom( + lpc.getIdentityAddress(), ca.getAddress(), false); if (mChatRoom == null) { mWaitLayout.setVisibility(View.VISIBLE); - mChatRoom = lc.createClientGroupChatRoom(getString(R.string.dummy_group_chat_subject), true); + mChatRoom = + lc.createClientGroupChatRoom( + getString(R.string.dummy_group_chat_subject), true); mChatRoom.addListener(mChatRoomCreationListener); Address participants[] = new Address[1]; participants[0] = ca.getAddress(); mChatRoom.addParticipants(participants); } else { - LinphoneActivity.instance().goToChat(mChatRoom.getPeerAddress().asStringUriOnly(), mShareInfos); + LinphoneActivity.instance() + .goToChat( + mChatRoom.getPeerAddress().asStringUriOnly(), mShareInfos); } } else { ChatRoom chatRoom = lc.getChatRoom(ca.getAddress()); - LinphoneActivity.instance().goToChat(chatRoom.getPeerAddress().asStringUriOnly(), mShareInfos); + LinphoneActivity.instance() + .goToChat(chatRoom.getPeerAddress().asStringUriOnly(), mShareInfos); } } } else { diff --git a/app/src/main/java/org/linphone/chat/ChatRoomViewHolder.java b/app/src/main/java/org/linphone/chat/ChatRoomViewHolder.java index 78c1653fc..313497f67 100644 --- a/app/src/main/java/org/linphone/chat/ChatRoomViewHolder.java +++ b/app/src/main/java/org/linphone/chat/ChatRoomViewHolder.java @@ -20,16 +20,11 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. package org.linphone.chat; import android.content.Context; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import androidx.recyclerview.widget.RecyclerView; import android.view.View; import android.widget.CheckBox; -import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; - -import org.linphone.utils.LinphoneUtils; +import androidx.recyclerview.widget.RecyclerView; import org.linphone.R; import org.linphone.contacts.ContactsManager; import org.linphone.contacts.LinphoneContact; @@ -39,9 +34,11 @@ import org.linphone.core.ChatRoom; import org.linphone.core.ChatRoomCapabilities; import org.linphone.core.Content; import org.linphone.core.Participant; +import org.linphone.utils.LinphoneUtils; import org.linphone.views.ContactAvatar; -public class ChatRoomViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener { +public class ChatRoomViewHolder extends RecyclerView.ViewHolder + implements View.OnClickListener, View.OnLongClickListener { public TextView lastMessageView; public TextView date; public TextView displayName; @@ -82,7 +79,11 @@ public class ChatRoomViewHolder extends RecyclerView.ViewHolder implements View. } } lastMessageView.setText(getSender(mRoom) + messageContent); - date.setText(LinphoneUtils.timestampToHumanDate(mContext, mRoom.getLastUpdateTime(), R.string.messages_list_date_format)); + date.setText( + LinphoneUtils.timestampToHumanDate( + mContext, + mRoom.getLastUpdateTime(), + R.string.messages_list_date_format)); } else { date.setText(""); lastMessageView.setText(""); @@ -108,18 +109,24 @@ public class ChatRoomViewHolder extends RecyclerView.ViewHolder implements View. public String getSender(ChatRoom mRoom) { if (mRoom.getLastMessageInHistory() != null) { - LinphoneContact contact = ContactsManager.getInstance().findContactFromAddress(mRoom.getLastMessageInHistory().getFromAddress()); + LinphoneContact contact = + ContactsManager.getInstance() + .findContactFromAddress( + mRoom.getLastMessageInHistory().getFromAddress()); if (contact != null) { return (contact.getFullName() + mContext.getString(R.string.separator)); } - return (LinphoneUtils.getAddressDisplayName(mRoom.getLastMessageInHistory().getFromAddress()) + mContext.getString(R.string.separator)); + return (LinphoneUtils.getAddressDisplayName( + mRoom.getLastMessageInHistory().getFromAddress()) + + mContext.getString(R.string.separator)); } return null; } public String getContact(ChatRoom mRoom) { Address contactAddress = mRoom.getPeerAddress(); - if (mRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt()) && mRoom.getParticipants().length > 0) { + if (mRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt()) + && mRoom.getParticipants().length > 0) { contactAddress = mRoom.getParticipants()[0].getAddress(); } @@ -138,11 +145,15 @@ public class ChatRoomViewHolder extends RecyclerView.ViewHolder implements View. if (mRoom.hasCapability(ChatRoomCapabilities.OneToOne.toInt())) { LinphoneContact contact = null; if (mRoom.hasCapability(ChatRoomCapabilities.Basic.toInt())) { - contact = ContactsManager.getInstance().findContactFromAddress(mRoom.getPeerAddress()); + contact = + ContactsManager.getInstance() + .findContactFromAddress(mRoom.getPeerAddress()); } else { Participant[] participants = mRoom.getParticipants(); if (participants != null && participants.length > 0) { - contact = ContactsManager.getInstance().findContactFromAddress(participants[0].getAddress()); + contact = + ContactsManager.getInstance() + .findContactFromAddress(participants[0].getAddress()); } } if (contact != null) { @@ -156,9 +167,9 @@ public class ChatRoomViewHolder extends RecyclerView.ViewHolder implements View. if (mRoom.hasCapability(ChatRoomCapabilities.Encrypted.toInt())) { Participant[] participants = mRoom.getParticipants(); if (participants.length > 0) { - remoteAddr = participants[0].getAddress(); - } else { - //TODO: error + remoteAddr = participants[0].getAddress(); + } else { + // TODO: error } } else { remoteAddr = mRoom.getPeerAddress(); @@ -185,4 +196,4 @@ public class ChatRoomViewHolder extends RecyclerView.ViewHolder implements View. boolean onItemLongClicked(int position); } -} \ No newline at end of file +} diff --git a/app/src/main/java/org/linphone/chat/ChatRoomsAdapter.java b/app/src/main/java/org/linphone/chat/ChatRoomsAdapter.java index 02d218d2f..c17ccc590 100644 --- a/app/src/main/java/org/linphone/chat/ChatRoomsAdapter.java +++ b/app/src/main/java/org/linphone/chat/ChatRoomsAdapter.java @@ -23,17 +23,15 @@ import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; - -import org.linphone.LinphoneManager; -import org.linphone.core.ChatRoom; -import org.linphone.utils.SelectableAdapter; -import org.linphone.utils.SelectableHelper; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; +import org.linphone.LinphoneManager; +import org.linphone.core.ChatRoom; +import org.linphone.utils.SelectableAdapter; +import org.linphone.utils.SelectableHelper; public class ChatRoomsAdapter extends SelectableAdapter { private Context mContext; @@ -41,7 +39,12 @@ public class ChatRoomsAdapter extends SelectableAdapter { private int mItemResource; private ChatRoomViewHolder.ClickListener mClickListener; - public ChatRoomsAdapter(Context context, int itemResource, List rooms, ChatRoomViewHolder.ClickListener clickListener, SelectableHelper helper) { + public ChatRoomsAdapter( + Context context, + int itemResource, + List rooms, + ChatRoomViewHolder.ClickListener clickListener, + SelectableHelper helper) { super(helper); mClickListener = clickListener; mRooms = rooms; @@ -51,8 +54,7 @@ public class ChatRoomsAdapter extends SelectableAdapter { @Override public ChatRoomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - View view = LayoutInflater.from(parent.getContext()) - .inflate(mItemResource, parent, false); + View view = LayoutInflater.from(parent.getContext()).inflate(mItemResource, parent, false); return new ChatRoomViewHolder(mContext, view, mClickListener); } @@ -60,21 +62,26 @@ public class ChatRoomsAdapter extends SelectableAdapter { public void onBindViewHolder(ChatRoomViewHolder holder, int position) { ChatRoom room = mRooms.get(position); holder.delete.setVisibility(isEditionEnabled() ? View.VISIBLE : View.INVISIBLE); - holder.unreadMessages.setVisibility(isEditionEnabled() ? View.INVISIBLE : (room.getUnreadMessagesCount() > 0 ? View.VISIBLE : View.INVISIBLE)); + holder.unreadMessages.setVisibility( + isEditionEnabled() + ? View.INVISIBLE + : (room.getUnreadMessagesCount() > 0 ? View.VISIBLE : View.INVISIBLE)); holder.delete.setChecked(isSelected(position)); holder.bindChatRoom(room); } public void refresh() { mRooms = new ArrayList<>(Arrays.asList(LinphoneManager.getLc().getChatRooms())); - Collections.sort(mRooms, new Comparator() { - public int compare(ChatRoom cr1, ChatRoom cr2) { - long timeDiff = cr1.getLastUpdateTime() - cr2.getLastUpdateTime(); - if (timeDiff > 0) return -1; - else if (timeDiff == 0) return 0; - return 1; - } - }); + Collections.sort( + mRooms, + new Comparator() { + public int compare(ChatRoom cr1, ChatRoom cr2) { + long timeDiff = cr1.getLastUpdateTime() - cr2.getLastUpdateTime(); + if (timeDiff > 0) return -1; + else if (timeDiff == 0) return 0; + return 1; + } + }); notifyDataSetChanged(); } @@ -83,10 +90,7 @@ public class ChatRoomsAdapter extends SelectableAdapter { notifyDataSetChanged(); } - /** - * Adapter's methods - */ - + /** Adapter's methods */ @Override public int getItemCount() { return mRooms.size(); diff --git a/app/src/main/java/org/linphone/chat/ChatRoomsFragment.java b/app/src/main/java/org/linphone/chat/ChatRoomsFragment.java index e62ca95be..f033b9416 100644 --- a/app/src/main/java/org/linphone/chat/ChatRoomsFragment.java +++ b/app/src/main/java/org/linphone/chat/ChatRoomsFragment.java @@ -19,22 +19,27 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. package org.linphone.chat; +import static org.linphone.fragments.FragmentsAvailable.CHAT_LIST; + import android.app.Fragment; import android.content.Context; import android.os.Bundle; -import androidx.recyclerview.widget.DividerItemDecoration; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; - +import androidx.recyclerview.widget.DividerItemDecoration; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.linphone.LinphoneActivity; import org.linphone.LinphoneManager; import org.linphone.R; -import org.linphone.LinphoneActivity; import org.linphone.contacts.ContactsManager; import org.linphone.contacts.ContactsUpdatedListener; import org.linphone.core.ChatMessage; @@ -47,14 +52,10 @@ import org.linphone.core.ProxyConfig; import org.linphone.fragments.FragmentsAvailable; import org.linphone.utils.SelectableHelper; -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import static org.linphone.fragments.FragmentsAvailable.CHAT_LIST; - -public class ChatRoomsFragment extends Fragment implements ContactsUpdatedListener, ChatRoomViewHolder.ClickListener, SelectableHelper.DeleteListener { +public class ChatRoomsFragment extends Fragment + implements ContactsUpdatedListener, + ChatRoomViewHolder.ClickListener, + SelectableHelper.DeleteListener { private RecyclerView mChatRoomsList; private ImageView mNewDiscussionButton, mNewGroupDiscussionButton, mBackToCallButton; @@ -69,7 +70,8 @@ public class ChatRoomsFragment extends Fragment implements ContactsUpdatedListen private TextView mNoChatHistory; @Override - public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + public View onCreateView( + final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreate(savedInstanceState); mRooms = new ArrayList<>(Arrays.asList(LinphoneManager.getLc().getChatRooms())); @@ -85,7 +87,9 @@ public class ChatRoomsFragment extends Fragment implements ContactsUpdatedListen mNoChatHistory = view.findViewById(R.id.noChatHistory); mSelectionHelper = new SelectableHelper(view, this); - mChatRoomsAdapter = new ChatRoomsAdapter(mContext, R.layout.chatlist_cell, mRooms, this, mSelectionHelper); + mChatRoomsAdapter = + new ChatRoomsAdapter( + mContext, R.layout.chatlist_cell, mRooms, this, mSelectionHelper); mChatRoomsList.setAdapter(mChatRoomsAdapter); mSelectionHelper.setAdapter(mChatRoomsAdapter); @@ -94,66 +98,81 @@ public class ChatRoomsFragment extends Fragment implements ContactsUpdatedListen RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(mContext); mChatRoomsList.setLayoutManager(layoutManager); - DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(mChatRoomsList.getContext(), - ((LinearLayoutManager) layoutManager).getOrientation()); - dividerItemDecoration.setDrawable(getActivity().getApplicationContext().getResources().getDrawable(R.drawable.divider)); + DividerItemDecoration dividerItemDecoration = + new DividerItemDecoration( + mChatRoomsList.getContext(), + ((LinearLayoutManager) layoutManager).getOrientation()); + dividerItemDecoration.setDrawable( + getActivity() + .getApplicationContext() + .getResources() + .getDrawable(R.drawable.divider)); mChatRoomsList.addItemDecoration(dividerItemDecoration); mWaitLayout.setVisibility(View.GONE); - mNewDiscussionButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - LinphoneActivity.instance().goToChatCreator(null, null, null, false, null, false, false); - } - }); - - mNewGroupDiscussionButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - LinphoneActivity.instance().goToChatCreator(null, null, null, false, null, true, false); - } - }); - - mBackToCallButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - LinphoneActivity.instance().resetClassicMenuLayoutAndGoBackToCallIfStillRunning(); - } - }); - - mListener = new CoreListenerStub() { - @Override - public void onMessageReceived(Core lc, ChatRoom cr, ChatMessage message) { - refreshChatRoomsList(); - } - - @Override - public void onChatRoomStateChanged(Core lc, ChatRoom cr, ChatRoom.State state) { - if (state == ChatRoom.State.Created) { - refreshChatRoomsList(); - } - } - }; - - mChatRoomListener = new ChatRoomListenerStub() { - @Override - public void onStateChanged(ChatRoom room, ChatRoom.State state) { - super.onStateChanged(room, state); - if (state == ChatRoom.State.Deleted || state == ChatRoom.State.TerminationFailed) { - mChatRoomDeletionPendingCount -= 1; - - if (state == ChatRoom.State.TerminationFailed) { - //TODO error message + mNewDiscussionButton.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View v) { + LinphoneActivity.instance() + .goToChatCreator(null, null, null, false, null, false, false); } + }); - if (mChatRoomDeletionPendingCount == 0) { - mWaitLayout.setVisibility(View.GONE); + mNewGroupDiscussionButton.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View v) { + LinphoneActivity.instance() + .goToChatCreator(null, null, null, false, null, true, false); + } + }); + + mBackToCallButton.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View v) { + LinphoneActivity.instance() + .resetClassicMenuLayoutAndGoBackToCallIfStillRunning(); + } + }); + + mListener = + new CoreListenerStub() { + @Override + public void onMessageReceived(Core lc, ChatRoom cr, ChatMessage message) { refreshChatRoomsList(); } - } - } - }; + + @Override + public void onChatRoomStateChanged(Core lc, ChatRoom cr, ChatRoom.State state) { + if (state == ChatRoom.State.Created) { + refreshChatRoomsList(); + } + } + }; + + mChatRoomListener = + new ChatRoomListenerStub() { + @Override + public void onStateChanged(ChatRoom room, ChatRoom.State state) { + super.onStateChanged(room, state); + if (state == ChatRoom.State.Deleted + || state == ChatRoom.State.TerminationFailed) { + mChatRoomDeletionPendingCount -= 1; + + if (state == ChatRoom.State.TerminationFailed) { + // TODO error message + } + + if (mChatRoomDeletionPendingCount == 0) { + mWaitLayout.setVisibility(View.GONE); + refreshChatRoomsList(); + } + } + } + }; return view; } @@ -178,7 +197,8 @@ public class ChatRoomsFragment extends Fragment implements ContactsUpdatedListen private void refreshChatRoomsList() { mChatRoomsAdapter.refresh(); - mNoChatHistory.setVisibility(mChatRoomsAdapter.getItemCount() == 0 ? View.VISIBLE : View.GONE); + mNoChatHistory.setVisibility( + mChatRoomsAdapter.getItemCount() == 0 ? View.VISIBLE : View.GONE); } public void displayFirstChat() { @@ -220,7 +240,8 @@ public class ChatRoomsFragment extends Fragment implements ContactsUpdatedListen refreshChatRoomsList(); ProxyConfig lpc = lc.getDefaultProxyConfig(); - mNewGroupDiscussionButton.setVisibility((lpc != null && lpc.getConferenceFactoryUri() != null) ? View.VISIBLE : View.GONE); + mNewGroupDiscussionButton.setVisibility( + (lpc != null && lpc.getConferenceFactoryUri() != null) ? View.VISIBLE : View.GONE); } @Override @@ -247,7 +268,8 @@ public class ChatRoomsFragment extends Fragment implements ContactsUpdatedListen if (message.getAppdata() != null && !message.isOutgoing()) { File file = new File(message.getAppdata()); if (file.exists()) { - file.delete(); // Delete downloaded file from incoming message that will be deleted + file.delete(); // Delete downloaded file from incoming message that + // will be deleted } } } @@ -259,17 +281,18 @@ public class ChatRoomsFragment extends Fragment implements ContactsUpdatedListen if (mChatRoomDeletionPendingCount > 0) { mWaitLayout.setVisibility(View.VISIBLE); } - LinphoneActivity.instance().displayMissedChats(LinphoneManager.getInstance().getUnreadMessageCount()); + LinphoneActivity.instance() + .displayMissedChats(LinphoneManager.getInstance().getUnreadMessageCount()); } @Override public void onContactsUpdated() { - if (!LinphoneActivity.isInstanciated() || LinphoneActivity.instance().getCurrentFragment() != CHAT_LIST) - return; + if (!LinphoneActivity.isInstanciated() + || LinphoneActivity.instance().getCurrentFragment() != CHAT_LIST) return; ChatRoomsAdapter adapter = (ChatRoomsAdapter) mChatRoomsList.getAdapter(); if (adapter != null) { adapter.notifyDataSetChanged(); } } -} \ No newline at end of file +} diff --git a/app/src/main/java/org/linphone/chat/ChatScrollListener.java b/app/src/main/java/org/linphone/chat/ChatScrollListener.java index d65c7d949..d8b38bfdc 100644 --- a/app/src/main/java/org/linphone/chat/ChatScrollListener.java +++ b/app/src/main/java/org/linphone/chat/ChatScrollListener.java @@ -46,8 +46,7 @@ public abstract class ChatScrollListener extends RecyclerView.OnScrollListener { for (int i = 0; i < lastVisibleItemPositions.length; i++) { if (i == 0) { maxSize = lastVisibleItemPositions[i]; - } - else if (lastVisibleItemPositions[i] > maxSize) { + } else if (lastVisibleItemPositions[i] > maxSize) { maxSize = lastVisibleItemPositions[i]; } } diff --git a/app/src/main/java/org/linphone/chat/DeviceChildViewHolder.java b/app/src/main/java/org/linphone/chat/DeviceChildViewHolder.java index a0ebfb24d..43f4adf70 100644 --- a/app/src/main/java/org/linphone/chat/DeviceChildViewHolder.java +++ b/app/src/main/java/org/linphone/chat/DeviceChildViewHolder.java @@ -22,7 +22,6 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import android.view.View; import android.widget.ImageView; import android.widget.TextView; - import org.linphone.R; public class DeviceChildViewHolder { diff --git a/app/src/main/java/org/linphone/chat/DeviceGroupViewHolder.java b/app/src/main/java/org/linphone/chat/DeviceGroupViewHolder.java index 8b377b567..a928ca3cc 100644 --- a/app/src/main/java/org/linphone/chat/DeviceGroupViewHolder.java +++ b/app/src/main/java/org/linphone/chat/DeviceGroupViewHolder.java @@ -23,7 +23,6 @@ import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; - import org.linphone.R; public class DeviceGroupViewHolder { diff --git a/app/src/main/java/org/linphone/chat/DevicesAdapter.java b/app/src/main/java/org/linphone/chat/DevicesAdapter.java index f58fd4637..fcc690a37 100644 --- a/app/src/main/java/org/linphone/chat/DevicesAdapter.java +++ b/app/src/main/java/org/linphone/chat/DevicesAdapter.java @@ -24,8 +24,8 @@ import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; - -import org.linphone.utils.LinphoneUtils; +import java.util.ArrayList; +import java.util.List; import org.linphone.R; import org.linphone.contacts.ContactsManager; import org.linphone.contacts.LinphoneContact; @@ -33,11 +33,9 @@ import org.linphone.core.Address; import org.linphone.core.ChatRoomSecurityLevel; import org.linphone.core.Participant; import org.linphone.core.ParticipantDevice; +import org.linphone.utils.LinphoneUtils; import org.linphone.views.ContactAvatar; -import java.util.ArrayList; -import java.util.List; - public class DevicesAdapter extends BaseExpandableListAdapter { private Context mContext; private List mParticipants; @@ -56,7 +54,8 @@ public class DevicesAdapter extends BaseExpandableListAdapter { } @Override - public View getGroupView(int groupPosition, boolean isExpanded, View view, ViewGroup viewGroup) { + public View getGroupView( + int groupPosition, boolean isExpanded, View view, ViewGroup viewGroup) { if (mOnlyDisplayChildsAsGroups) { ParticipantDevice device = (ParticipantDevice) getGroup(groupPosition); @@ -76,7 +75,7 @@ public class DevicesAdapter extends BaseExpandableListAdapter { } Address deviceAddress = device.getAddress(); - holder.deviceName.setText(deviceAddress.getUriParam("gr")); //TODO + holder.deviceName.setText(deviceAddress.getUriParam("gr")); // TODO ChatRoomSecurityLevel level = device.getSecurityLevel(); switch (level) { @@ -111,24 +110,29 @@ public class DevicesAdapter extends BaseExpandableListAdapter { } Address participantAddress = participant.getAddress(); - LinphoneContact contact = ContactsManager.getInstance().findContactFromAddress(participantAddress); + LinphoneContact contact = + ContactsManager.getInstance().findContactFromAddress(participantAddress); if (contact != null) { - ContactAvatar.displayAvatar(contact, participant.getSecurityLevel(), holder.avatarLayout); + ContactAvatar.displayAvatar( + contact, participant.getSecurityLevel(), holder.avatarLayout); holder.participantName.setText(contact.getFullName()); } else { String displayName = LinphoneUtils.getAddressDisplayName(participantAddress); - ContactAvatar.displayAvatar(displayName, participant.getSecurityLevel(), holder.avatarLayout); + ContactAvatar.displayAvatar( + displayName, participant.getSecurityLevel(), holder.avatarLayout); holder.participantName.setText(displayName); } - holder.groupExpander.setImageResource(isExpanded ? R.drawable.chevron_list_open : R.drawable.chevron_list_close); + holder.groupExpander.setImageResource( + isExpanded ? R.drawable.chevron_list_open : R.drawable.chevron_list_close); } return view; } @Override - public View getChildView(int groupPosition, int childPosition, boolean b, View view, ViewGroup viewGroup) { + public View getChildView( + int groupPosition, int childPosition, boolean b, View view, ViewGroup viewGroup) { ParticipantDevice device = (ParticipantDevice) getChild(groupPosition, childPosition); DeviceChildViewHolder holder = null; @@ -147,7 +151,7 @@ public class DevicesAdapter extends BaseExpandableListAdapter { } Address deviceAddress = device.getAddress(); - holder.deviceName.setText(deviceAddress.getUriParam("gr")); //TODO + holder.deviceName.setText(deviceAddress.getUriParam("gr")); // TODO ChatRoomSecurityLevel level = device.getSecurityLevel(); switch (level) { @@ -170,19 +174,25 @@ public class DevicesAdapter extends BaseExpandableListAdapter { @Override public int getGroupCount() { if (mParticipants.size() == 0) return 0; - return mOnlyDisplayChildsAsGroups ? mParticipants.get(0).getDevices().length : mParticipants.size(); + return mOnlyDisplayChildsAsGroups + ? mParticipants.get(0).getDevices().length + : mParticipants.size(); } @Override public int getChildrenCount(int groupPosition) { if (mParticipants.size() == 0) return 0; - return mOnlyDisplayChildsAsGroups ? 0 : mParticipants.get(groupPosition).getDevices().length; + return mOnlyDisplayChildsAsGroups + ? 0 + : mParticipants.get(groupPosition).getDevices().length; } @Override public Object getGroup(int groupPosition) { if (mParticipants.size() == 0) return null; - return mOnlyDisplayChildsAsGroups ? mParticipants.get(0).getDevices()[groupPosition] : mParticipants.get(groupPosition); + return mOnlyDisplayChildsAsGroups + ? mParticipants.get(0).getDevices()[groupPosition] + : mParticipants.get(groupPosition); } @Override diff --git a/app/src/main/java/org/linphone/chat/DevicesFragment.java b/app/src/main/java/org/linphone/chat/DevicesFragment.java index 21ef9eb5b..495002890 100644 --- a/app/src/main/java/org/linphone/chat/DevicesFragment.java +++ b/app/src/main/java/org/linphone/chat/DevicesFragment.java @@ -21,18 +21,17 @@ package org.linphone.chat; import android.app.Fragment; import android.os.Bundle; -import androidx.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ExpandableListView; import android.widget.ImageView; import android.widget.TextView; - -import org.linphone.LinphoneManager; -import org.linphone.utils.LinphoneUtils; -import org.linphone.R; +import androidx.annotation.Nullable; +import java.util.Arrays; import org.linphone.LinphoneActivity; +import org.linphone.LinphoneManager; +import org.linphone.R; import org.linphone.contacts.ContactsManager; import org.linphone.contacts.LinphoneContact; import org.linphone.core.Address; @@ -41,8 +40,7 @@ import org.linphone.core.ChatRoomCapabilities; import org.linphone.core.Core; import org.linphone.core.ParticipantDevice; import org.linphone.fragments.FragmentsAvailable; - -import java.util.Arrays; +import org.linphone.utils.LinphoneUtils; public class DevicesFragment extends Fragment { private LayoutInflater mInflater; @@ -58,7 +56,8 @@ public class DevicesFragment extends Fragment { @Nullable @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { + public View onCreateView( + LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { @@ -72,26 +71,39 @@ public class DevicesFragment extends Fragment { mOnlyDisplayChilds = false; mExpandableList = view.findViewById(R.id.devices_list); - mExpandableList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() { - @Override - public boolean onChildClick(ExpandableListView expandableListView, View view, int groupPosition, int childPosition, long l) { - ParticipantDevice device = (ParticipantDevice) mAdapter.getChild(groupPosition, childPosition); - LinphoneManager.getLc().inviteAddress(device.getAddress()); - return false; - } - }); - mExpandableList.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() { - @Override - public boolean onGroupClick(ExpandableListView expandableListView, View view, int groupPosition, long l) { - if (mOnlyDisplayChilds) { - // in this case groups are childs, so call on click - ParticipantDevice device = (ParticipantDevice) mAdapter.getGroup(groupPosition); - LinphoneManager.getLc().inviteAddress(device.getAddress()); - return true; - } - return false; - } - }); + mExpandableList.setOnChildClickListener( + new ExpandableListView.OnChildClickListener() { + @Override + public boolean onChildClick( + ExpandableListView expandableListView, + View view, + int groupPosition, + int childPosition, + long l) { + ParticipantDevice device = + (ParticipantDevice) mAdapter.getChild(groupPosition, childPosition); + LinphoneManager.getLc().inviteAddress(device.getAddress()); + return false; + } + }); + mExpandableList.setOnGroupClickListener( + new ExpandableListView.OnGroupClickListener() { + @Override + public boolean onGroupClick( + ExpandableListView expandableListView, + View view, + int groupPosition, + long l) { + if (mOnlyDisplayChilds) { + // in this case groups are childs, so call on click + ParticipantDevice device = + (ParticipantDevice) mAdapter.getGroup(groupPosition); + LinphoneManager.getLc().inviteAddress(device.getAddress()); + return true; + } + return false; + } + }); initChatRoom(); @@ -99,16 +111,17 @@ public class DevicesFragment extends Fragment { initHeader(); mBackButton = view.findViewById(R.id.back); - mBackButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - if (LinphoneActivity.instance().isTablet()) { - LinphoneActivity.instance().goToChat(mRoomUri, null); - } else { - LinphoneActivity.instance().onBackPressed(); - } - } - }); + mBackButton.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View view) { + if (LinphoneActivity.instance().isTablet()) { + LinphoneActivity.instance().goToChat(mRoomUri, null); + } else { + LinphoneActivity.instance().onBackPressed(); + } + } + }); return view; } @@ -135,7 +148,8 @@ public class DevicesFragment extends Fragment { if (mRoom.getParticipants().length > 0) { remoteParticipantAddr = mRoom.getParticipants()[0].getAddress(); } - LinphoneContact c = ContactsManager.getInstance().findContactFromAddress(remoteParticipantAddr); + LinphoneContact c = + ContactsManager.getInstance().findContactFromAddress(remoteParticipantAddr); String displayName; if (c != null) { displayName = c.getFullName(); diff --git a/app/src/main/java/org/linphone/chat/GroupInfoAdapter.java b/app/src/main/java/org/linphone/chat/GroupInfoAdapter.java index 2050c9f36..a857143dd 100644 --- a/app/src/main/java/org/linphone/chat/GroupInfoAdapter.java +++ b/app/src/main/java/org/linphone/chat/GroupInfoAdapter.java @@ -19,8 +19,6 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. package org.linphone.chat; -import androidx.annotation.NonNull; -import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -28,7 +26,10 @@ import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; - +import androidx.annotation.NonNull; +import androidx.recyclerview.widget.RecyclerView; +import java.util.ArrayList; +import java.util.List; import org.linphone.R; import org.linphone.contacts.ContactAddress; import org.linphone.contacts.LinphoneContact; @@ -36,9 +37,6 @@ import org.linphone.core.ChatRoom; import org.linphone.core.Participant; import org.linphone.views.ContactAvatar; -import java.util.ArrayList; -import java.util.List; - public class GroupInfoAdapter extends RecyclerView.Adapter { public static class ViewHolder extends RecyclerView.ViewHolder { @@ -63,7 +61,8 @@ public class GroupInfoAdapter extends RecyclerView.Adapter items, boolean hideAdminFeatures, boolean isCreation) { + public GroupInfoAdapter( + List items, boolean hideAdminFeatures, boolean isCreation) { mItems = items; mHideAdminFeatures = hideAdminFeatures || isCreation; } @@ -71,7 +70,9 @@ public class GroupInfoAdapter extends RecyclerView.Adapter) getArguments().getSerializable("ContactAddress"); + mParticipants = + (ArrayList) getArguments().getSerializable("ContactAddress"); mGroupChatRoomAddress = null; mChatRoom = null; @@ -119,213 +119,271 @@ public class GroupInfoFragment extends Fragment implements ChatRoomListener { mParticipantsList = view.findViewById(R.id.chat_room_participants); mAdapter = new GroupInfoAdapter(mParticipants, !mIsEditionEnabled, !mIsAlreadyCreatedGroup); - mAdapter.setOnDeleteClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - ContactAddress ca = (ContactAddress) view.getTag(); - mParticipants.remove(ca); - mAdapter.updateDataSet(mParticipants); - mParticipantsList.setAdapter(mAdapter); - mConfirmButton.setEnabled(mSubjectField.getText().length() > 0 && mParticipants.size() > 0); - } - }); + mAdapter.setOnDeleteClickListener( + new View.OnClickListener() { + @Override + public void onClick(View view) { + ContactAddress ca = (ContactAddress) view.getTag(); + mParticipants.remove(ca); + mAdapter.updateDataSet(mParticipants); + mParticipantsList.setAdapter(mAdapter); + mConfirmButton.setEnabled( + mSubjectField.getText().length() > 0 && mParticipants.size() > 0); + } + }); mParticipantsList.setAdapter(mAdapter); mAdapter.setChatRoom(mChatRoom); layoutManager = new LinearLayoutManager(mContext); mParticipantsList.setLayoutManager(layoutManager); - //Divider between items - DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(mParticipantsList.getContext(), - layoutManager.getOrientation()); + // Divider between items + DividerItemDecoration dividerItemDecoration = + new DividerItemDecoration( + mParticipantsList.getContext(), layoutManager.getOrientation()); dividerItemDecoration.setDrawable(mContext.getResources().getDrawable(R.drawable.divider)); mParticipantsList.addItemDecoration(dividerItemDecoration); - String fileSharedUri = getArguments().getString("fileSharedUri"); String messageDraft = getArguments().getString("messageDraft"); - if (fileSharedUri != null || messageDraft != null) - mShareInfos = new Bundle(); + if (fileSharedUri != null || messageDraft != null) mShareInfos = new Bundle(); - if (fileSharedUri != null) - mShareInfos.putString("fileSharedUri", fileSharedUri); + if (fileSharedUri != null) mShareInfos.putString("fileSharedUri", fileSharedUri); - if (messageDraft != null) - mShareInfos.putString("messageDraft", messageDraft); + if (messageDraft != null) mShareInfos.putString("messageDraft", messageDraft); mBackButton = view.findViewById(R.id.back); - mBackButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - if (mIsAlreadyCreatedGroup) { - if (LinphoneActivity.instance().isTablet()) { - LinphoneActivity.instance().goToChat(mGroupChatRoomAddress.asStringUriOnly(), mShareInfos); - } else { - getFragmentManager().popBackStack(); + mBackButton.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View view) { + if (mIsAlreadyCreatedGroup) { + if (LinphoneActivity.instance().isTablet()) { + LinphoneActivity.instance() + .goToChat( + mGroupChatRoomAddress.asStringUriOnly(), + mShareInfos); + } else { + getFragmentManager().popBackStack(); + } + } else { + LinphoneActivity.instance() + .goToChatCreator( + null, + mParticipants, + null, + true, + mShareInfos, + true, + mIsEncryptionEnabled); + } } - } else { - LinphoneActivity.instance().goToChatCreator(null, mParticipants, null, true, mShareInfos, true, mIsEncryptionEnabled); - } - } - }); + }); mConfirmButton = view.findViewById(R.id.confirm); mLeaveGroupButton = view.findViewById(R.id.leaveGroupLayout); - mLeaveGroupButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - final Dialog dialog = LinphoneActivity.instance().displayDialog(getString(R.string.chat_room_leave_dialog)); - Button delete = dialog.findViewById(R.id.dialog_delete_button); - delete.setText(getString(R.string.chat_room_leave_button)); - Button cancel = dialog.findViewById(R.id.dialog_cancel_button); - - delete.setOnClickListener(new View.OnClickListener() { + mLeaveGroupButton.setOnClickListener( + new View.OnClickListener() { @Override public void onClick(View view) { - if (mChatRoom != null) { - mChatRoom.leave(); - LinphoneActivity.instance().goToChat(mGroupChatRoomAddress.asString(), null); - } else { - Log.e("Can't leave, chatRoom for address " + mGroupChatRoomAddress.asString() + " is null..."); - } - dialog.dismiss(); - } - }); + final Dialog dialog = + LinphoneActivity.instance() + .displayDialog(getString(R.string.chat_room_leave_dialog)); + Button delete = dialog.findViewById(R.id.dialog_delete_button); + delete.setText(getString(R.string.chat_room_leave_button)); + Button cancel = dialog.findViewById(R.id.dialog_cancel_button); - cancel.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - dialog.dismiss(); + delete.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View view) { + if (mChatRoom != null) { + mChatRoom.leave(); + LinphoneActivity.instance() + .goToChat( + mGroupChatRoomAddress.asString(), null); + } else { + Log.e( + "Can't leave, chatRoom for address " + + mGroupChatRoomAddress.asString() + + " is null..."); + } + dialog.dismiss(); + } + }); + + cancel.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View view) { + dialog.dismiss(); + } + }); + dialog.show(); } }); - dialog.show(); - } - }); - mLeaveGroupButton.setVisibility(mIsAlreadyCreatedGroup && mChatRoom.hasBeenLeft() ? View.GONE : mIsAlreadyCreatedGroup ? View.VISIBLE : View.GONE); + mLeaveGroupButton.setVisibility( + mIsAlreadyCreatedGroup && mChatRoom.hasBeenLeft() + ? View.GONE + : mIsAlreadyCreatedGroup ? View.VISIBLE : View.GONE); mAddParticipantsLayout = view.findViewById(R.id.addParticipantsLayout); - mAddParticipantsLayout.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - if (mIsEditionEnabled && mIsAlreadyCreatedGroup) { - LinphoneActivity.instance().goToChatCreator(mGroupChatRoomAddress != null ? mGroupChatRoomAddress.asString() : null, mParticipants, mSubject, !mIsAlreadyCreatedGroup, null, true, mIsEncryptionEnabled); - } - } - }); + mAddParticipantsLayout.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View view) { + if (mIsEditionEnabled && mIsAlreadyCreatedGroup) { + LinphoneActivity.instance() + .goToChatCreator( + mGroupChatRoomAddress != null + ? mGroupChatRoomAddress.asString() + : null, + mParticipants, + mSubject, + !mIsAlreadyCreatedGroup, + null, + true, + mIsEncryptionEnabled); + } + } + }); mAddParticipantsButton = view.findViewById(R.id.addParticipants); - mAddParticipantsButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - if (mIsEditionEnabled && mIsAlreadyCreatedGroup) { - LinphoneActivity.instance().goToChatCreator(mGroupChatRoomAddress != null ? mGroupChatRoomAddress.asString() : null, mParticipants, mSubject, !mIsAlreadyCreatedGroup, null, true, mIsEncryptionEnabled); - } - } - }); + mAddParticipantsButton.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View view) { + if (mIsEditionEnabled && mIsAlreadyCreatedGroup) { + LinphoneActivity.instance() + .goToChatCreator( + mGroupChatRoomAddress != null + ? mGroupChatRoomAddress.asString() + : null, + mParticipants, + mSubject, + !mIsAlreadyCreatedGroup, + null, + true, + mIsEncryptionEnabled); + } + } + }); mAddParticipantsButton.setVisibility(mIsAlreadyCreatedGroup ? View.VISIBLE : View.GONE); mSubjectField = view.findViewById(R.id.subjectField); - mSubjectField.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { + mSubjectField.addTextChangedListener( + new TextWatcher() { + @Override + public void beforeTextChanged( + CharSequence charSequence, int i, int i1, int i2) {} - } + @Override + public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {} - @Override - public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { - - } - - @Override - public void afterTextChanged(Editable editable) { - mConfirmButton.setEnabled(mSubjectField.getText().length() > 0 && mParticipants.size() > 0); - } - }); + @Override + public void afterTextChanged(Editable editable) { + mConfirmButton.setEnabled( + mSubjectField.getText().length() > 0 && mParticipants.size() > 0); + } + }); mSubjectField.setText(mSubject); - mChatRoomCreationListener = new ChatRoomListenerStub() { - @Override - public void onStateChanged(ChatRoom cr, ChatRoom.State newState) { - if (newState == ChatRoom.State.Created) { - mWaitLayout.setVisibility(View.GONE); - // This will remove both the creation fragment and the group info fragment from the back stack - getFragmentManager().popBackStack(); - getFragmentManager().popBackStack(); - LinphoneActivity.instance().goToChat(cr.getPeerAddress().asStringUriOnly(), mShareInfos); - } else if (newState == ChatRoom.State.CreationFailed) { - mWaitLayout.setVisibility(View.GONE); - LinphoneActivity.instance().displayChatRoomError(); - Log.e("Group chat room for address " + cr.getPeerAddress() + " has failed !"); - } - } - }; - - mConfirmButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - if (!mIsAlreadyCreatedGroup) { - mWaitLayout.setVisibility(View.VISIBLE); - mTempChatRoom = LinphoneManager.getLc().createClientGroupChatRoom(mSubjectField.getText().toString(), false, mIsEncryptionEnabled); - mTempChatRoom.addListener(mChatRoomCreationListener); - for (ContactAddress ca : mParticipants) { - mTempChatRoom.addParticipant(ca.getAddress()); - } - } else { - // Subject - String newSubject = mSubjectField.getText().toString(); - if (!newSubject.equals(mSubject)) { - mChatRoom.setSubject(newSubject); + mChatRoomCreationListener = + new ChatRoomListenerStub() { + @Override + public void onStateChanged(ChatRoom cr, ChatRoom.State newState) { + if (newState == ChatRoom.State.Created) { + mWaitLayout.setVisibility(View.GONE); + // This will remove both the creation fragment and the group info + // fragment from the back stack + getFragmentManager().popBackStack(); + getFragmentManager().popBackStack(); + LinphoneActivity.instance() + .goToChat(cr.getPeerAddress().asStringUriOnly(), mShareInfos); + } else if (newState == ChatRoom.State.CreationFailed) { + mWaitLayout.setVisibility(View.GONE); + LinphoneActivity.instance().displayChatRoomError(); + Log.e( + "Group chat room for address " + + cr.getPeerAddress() + + " has failed !"); + } } + }; - // Participants removed - ArrayList toRemove = new ArrayList<>(); - for (Participant p : mChatRoom.getParticipants()) { - boolean found = false; - for (ContactAddress c : mParticipants) { - if (c.getAddress().weakEqual(p.getAddress())) { - found = true; - break; + mConfirmButton.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View view) { + if (!mIsAlreadyCreatedGroup) { + mWaitLayout.setVisibility(View.VISIBLE); + mTempChatRoom = + LinphoneManager.getLc() + .createClientGroupChatRoom( + mSubjectField.getText().toString(), + false, + mIsEncryptionEnabled); + mTempChatRoom.addListener(mChatRoomCreationListener); + for (ContactAddress ca : mParticipants) { + mTempChatRoom.addParticipant(ca.getAddress()); + } + } else { + // Subject + String newSubject = mSubjectField.getText().toString(); + if (!newSubject.equals(mSubject)) { + mChatRoom.setSubject(newSubject); } - } - if (!found) { - toRemove.add(p); - } - } - Participant[] participantsToRemove = new Participant[toRemove.size()]; - toRemove.toArray(participantsToRemove); - mChatRoom.removeParticipants(participantsToRemove); - // Participants added - ArrayList
        toAdd = new ArrayList<>(); - for (ContactAddress c : mParticipants) { - boolean found = false; - for (Participant p : mChatRoom.getParticipants()) { - if (p.getAddress().weakEqual(c.getAddress())) { - // Admin rights - if (c.isAdmin() != p.isAdmin()) { - mChatRoom.setParticipantAdminStatus(p, c.isAdmin()); + // Participants removed + ArrayList toRemove = new ArrayList<>(); + for (Participant p : mChatRoom.getParticipants()) { + boolean found = false; + for (ContactAddress c : mParticipants) { + if (c.getAddress().weakEqual(p.getAddress())) { + found = true; + break; + } + } + if (!found) { + toRemove.add(p); } - found = true; - break; } - } - if (!found) { - Address addr = c.getAddress(); - if (addr != null) { - toAdd.add(addr); - } else { - //TODO error + Participant[] participantsToRemove = new Participant[toRemove.size()]; + toRemove.toArray(participantsToRemove); + mChatRoom.removeParticipants(participantsToRemove); + + // Participants added + ArrayList
        toAdd = new ArrayList<>(); + for (ContactAddress c : mParticipants) { + boolean found = false; + for (Participant p : mChatRoom.getParticipants()) { + if (p.getAddress().weakEqual(c.getAddress())) { + // Admin rights + if (c.isAdmin() != p.isAdmin()) { + mChatRoom.setParticipantAdminStatus(p, c.isAdmin()); + } + found = true; + break; + } + } + if (!found) { + Address addr = c.getAddress(); + if (addr != null) { + toAdd.add(addr); + } else { + // TODO error + } + } } + Address[] participantsToAdd = new Address[toAdd.size()]; + toAdd.toArray(participantsToAdd); + mChatRoom.addParticipants(participantsToAdd); + + LinphoneActivity.instance() + .goToChat(mGroupChatRoomAddress.asString(), null); } } - Address[] participantsToAdd = new Address[toAdd.size()]; - toAdd.toArray(participantsToAdd); - mChatRoom.addParticipants(participantsToAdd); - - LinphoneActivity.instance().goToChat(mGroupChatRoomAddress.asString(), null); - } - } - }); + }); mConfirmButton.setEnabled(mSubjectField.getText().length() > 0 && mParticipants.size() > 0); if (!mIsEditionEnabled) { @@ -352,9 +410,11 @@ public class GroupInfoFragment extends Fragment implements ChatRoomListener { LinphoneActivity.instance().selectMenu(FragmentsAvailable.INFO_GROUP_CHAT); } - InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(INPUT_METHOD_SERVICE); + InputMethodManager inputMethodManager = + (InputMethodManager) getActivity().getSystemService(INPUT_METHOD_SERVICE); if (getActivity().getCurrentFocus() != null) { - inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0); + inputMethodManager.hideSoftInputFromWindow( + getActivity().getCurrentFocus().getWindowToken(), 0); } } @@ -404,16 +464,23 @@ public class GroupInfoFragment extends Fragment implements ChatRoomListener { private void displayMeAdminStatusUpdated() { if (mAdminStateChangedDialog != null) mAdminStateChangedDialog.dismiss(); - mAdminStateChangedDialog = LinphoneActivity.instance().displayDialog(getString(mIsEditionEnabled ? R.string.chat_room_you_are_now_admin : R.string.chat_room_you_are_no_longer_admin)); + mAdminStateChangedDialog = + LinphoneActivity.instance() + .displayDialog( + getString( + mIsEditionEnabled + ? R.string.chat_room_you_are_now_admin + : R.string.chat_room_you_are_no_longer_admin)); Button cancel = mAdminStateChangedDialog.findViewById(R.id.dialog_cancel_button); mAdminStateChangedDialog.findViewById(R.id.dialog_delete_button).setVisibility(View.GONE); cancel.setText(getString(R.string.ok)); - cancel.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - mAdminStateChangedDialog.dismiss(); - } - }); + cancel.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View view) { + mAdminStateChangedDialog.dismiss(); + } + }); mAdminStateChangedDialog.show(); } @@ -435,12 +502,10 @@ public class GroupInfoFragment extends Fragment implements ChatRoomListener { } @Override - public void onConferenceJoined(ChatRoom cr, EventLog event_log) { - } + public void onConferenceJoined(ChatRoom cr, EventLog event_log) {} @Override - public void onConferenceLeft(ChatRoom cr, EventLog event_log) { - } + public void onConferenceLeft(ChatRoom cr, EventLog event_log) {} @Override public void onParticipantAdded(ChatRoom cr, EventLog event_log) { @@ -453,49 +518,32 @@ public class GroupInfoFragment extends Fragment implements ChatRoomListener { } @Override - public void onChatMessageShouldBeStored(ChatRoom cr, ChatMessage msg) { - - } + public void onChatMessageShouldBeStored(ChatRoom cr, ChatMessage msg) {} @Override - public void onParticipantsCapabilitiesChecked(ChatRoom cr, Address deviceAddr, Address[] participantsAddr) { - - } + public void onParticipantsCapabilitiesChecked( + ChatRoom cr, Address deviceAddr, Address[] participantsAddr) {} @Override - public void onIsComposingReceived(ChatRoom cr, Address remoteAddr, boolean isComposing) { - - } + public void onIsComposingReceived(ChatRoom cr, Address remoteAddr, boolean isComposing) {} @Override - public void onChatMessageSent(ChatRoom cr, EventLog event_log) { - - } + public void onChatMessageSent(ChatRoom cr, EventLog event_log) {} @Override - public void onConferenceAddressGeneration(ChatRoom cr) { - - } + public void onConferenceAddressGeneration(ChatRoom cr) {} @Override - public void onChatMessageReceived(ChatRoom cr, EventLog event_log) { - - } + public void onChatMessageReceived(ChatRoom cr, EventLog event_log) {} @Override - public void onMessageReceived(ChatRoom cr, ChatMessage msg) { - - } + public void onMessageReceived(ChatRoom cr, ChatMessage msg) {} @Override - public void onParticipantDeviceRemoved(ChatRoom cr, EventLog event_log) { - - } + public void onParticipantDeviceRemoved(ChatRoom cr, EventLog event_log) {} @Override - public void onParticipantDeviceAdded(ChatRoom cr, EventLog event_log) { - - } + public void onParticipantDeviceAdded(ChatRoom cr, EventLog event_log) {} @Override public void onSecurityEvent(ChatRoom cr, EventLog eventLog) { @@ -503,25 +551,19 @@ public class GroupInfoFragment extends Fragment implements ChatRoomListener { } @Override - public void onUndecryptableMessageReceived(ChatRoom cr, ChatMessage msg) { - - } + public void onUndecryptableMessageReceived(ChatRoom cr, ChatMessage msg) {} @Override - public void onStateChanged(ChatRoom cr, ChatRoom.State newState) { - - } + public void onStateChanged(ChatRoom cr, ChatRoom.State newState) {} @Override - public void onParticipantDeviceFetchRequested(ChatRoom cr, Address addr) { - - } + public void onParticipantDeviceFetchRequested(ChatRoom cr, Address addr) {} @Override - public void onParticipantRegistrationSubscriptionRequested(ChatRoom cr, Address participantAddr) { - } + public void onParticipantRegistrationSubscriptionRequested( + ChatRoom cr, Address participantAddr) {} @Override - public void onParticipantRegistrationUnsubscriptionRequested(ChatRoom cr, Address participantAddr) { - } + public void onParticipantRegistrationUnsubscriptionRequested( + ChatRoom cr, Address participantAddr) {} } diff --git a/app/src/main/java/org/linphone/chat/ImdnFragment.java b/app/src/main/java/org/linphone/chat/ImdnFragment.java index 74b336e11..216970ccf 100644 --- a/app/src/main/java/org/linphone/chat/ImdnFragment.java +++ b/app/src/main/java/org/linphone/chat/ImdnFragment.java @@ -27,7 +27,7 @@ import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; - +import androidx.annotation.Nullable; import org.linphone.LinphoneActivity; import org.linphone.LinphoneManager; import org.linphone.R; @@ -43,11 +43,16 @@ import org.linphone.fragments.FragmentsAvailable; import org.linphone.utils.LinphoneUtils; import org.linphone.views.ContactAvatar; -import androidx.annotation.Nullable; - public class ImdnFragment extends Fragment { private LayoutInflater mInflater; - private LinearLayout mRead, mReadHeader, mDelivered, mDeliveredHeader, mSent, mSentHeader, mUndelivered, mUndeliveredHeader; + private LinearLayout mRead, + mReadHeader, + mDelivered, + mDeliveredHeader, + mSent, + mSentHeader, + mUndelivered, + mUndeliveredHeader; private ImageView mBackButton; private ChatMessageViewHolder mBubble; private ViewGroup mContainer; @@ -60,7 +65,8 @@ public class ImdnFragment extends Fragment { @Nullable @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { + public View onCreateView( + LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { @@ -77,16 +83,17 @@ public class ImdnFragment extends Fragment { View view = mInflater.inflate(R.layout.chat_imdn, container, false); mBackButton = view.findViewById(R.id.back); - mBackButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - if (LinphoneActivity.instance().isTablet()) { - LinphoneActivity.instance().goToChat(mRoomUri, null); - } else { - LinphoneActivity.instance().onBackPressed(); - } - } - }); + mBackButton.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View view) { + if (LinphoneActivity.instance().isTablet()) { + LinphoneActivity.instance().goToChat(mRoomUri, null); + } else { + LinphoneActivity.instance().onBackPressed(); + } + } + }); mRead = view.findViewById(R.id.read_layout); mDelivered = view.findViewById(R.id.delivered_layout); @@ -100,12 +107,14 @@ public class ImdnFragment extends Fragment { mBubble = new ChatMessageViewHolder(getActivity(), view.findViewById(R.id.bubble), null); mMessage = mRoom.findMessage(mMessageId); - mListener = new ChatMessageListenerStub() { - @Override - public void onParticipantImdnStateChanged(ChatMessage msg, ParticipantImdnState state) { - refreshInfo(); - } - }; + mListener = + new ChatMessageListenerStub() { + @Override + public void onParticipantImdnStateChanged( + ChatMessage msg, ParticipantImdnState state) { + refreshInfo(); + } + }; if (mMessage == null) return null; mMessage.setListener(mListener); @@ -121,12 +130,14 @@ public class ImdnFragment extends Fragment { } refreshInfo(); - mMessage.setListener(new ChatMessageListenerStub() { - @Override - public void onParticipantImdnStateChanged(ChatMessage msg, ParticipantImdnState state) { - refreshInfo(); - } - }); + mMessage.setListener( + new ChatMessageListenerStub() { + @Override + public void onParticipantImdnStateChanged( + ChatMessage msg, ParticipantImdnState state) { + refreshInfo(); + } + }); } @Override @@ -137,11 +148,12 @@ public class ImdnFragment extends Fragment { private void refreshInfo() { if (mMessage == null) { - //TODO: error + // TODO: error return; } Address remoteSender = mMessage.getFromAddress(); - LinphoneContact contact = ContactsManager.getInstance().findContactFromAddress(remoteSender); + LinphoneContact contact = + ContactsManager.getInstance().findContactFromAddress(remoteSender); mBubble.deleteMessage.setVisibility(View.GONE); mBubble.deleteEvent.setVisibility(View.GONE); @@ -156,23 +168,34 @@ public class ImdnFragment extends Fragment { mSent.removeAllViews(); mUndelivered.removeAllViews(); - ParticipantImdnState[] participants = mMessage.getParticipantsByImdnState(ChatMessage.State.Displayed); + ParticipantImdnState[] participants = + mMessage.getParticipantsByImdnState(ChatMessage.State.Displayed); mReadHeader.setVisibility(participants.length == 0 ? View.GONE : View.VISIBLE); boolean first = true; for (ParticipantImdnState participant : participants) { Address address = participant.getParticipant().getAddress(); - LinphoneContact participantContact = ContactsManager.getInstance().findContactFromAddress(address); - String participantDisplayName = participantContact != null ? participantContact.getFullName() : LinphoneUtils.getAddressDisplayName(address); + LinphoneContact participantContact = + ContactsManager.getInstance().findContactFromAddress(address); + String participantDisplayName = + participantContact != null + ? participantContact.getFullName() + : LinphoneUtils.getAddressDisplayName(address); View v = mInflater.inflate(R.layout.chat_imdn_cell, mContainer, false); v.findViewById(R.id.separator).setVisibility(first ? View.GONE : View.VISIBLE); - ((TextView) v.findViewById(R.id.time)).setText(LinphoneUtils.timestampToHumanDate(getActivity(), participant.getStateChangeTime(), R.string.messages_date_format)); + ((TextView) v.findViewById(R.id.time)) + .setText( + LinphoneUtils.timestampToHumanDate( + getActivity(), + participant.getStateChangeTime(), + R.string.messages_date_format)); ((TextView) v.findViewById(R.id.name)).setText(participantDisplayName); if (participantContact != null) { ContactAvatar.displayAvatar(participantContact, v.findViewById(R.id.avatar_layout)); } else { - ContactAvatar.displayAvatar(participantDisplayName, v.findViewById(R.id.avatar_layout)); + ContactAvatar.displayAvatar( + participantDisplayName, v.findViewById(R.id.avatar_layout)); } mRead.addView(v); @@ -185,17 +208,27 @@ public class ImdnFragment extends Fragment { for (ParticipantImdnState participant : participants) { Address address = participant.getParticipant().getAddress(); - LinphoneContact participantContact = ContactsManager.getInstance().findContactFromAddress(address); - String participantDisplayName = participantContact != null ? participantContact.getFullName() : LinphoneUtils.getAddressDisplayName(address); + LinphoneContact participantContact = + ContactsManager.getInstance().findContactFromAddress(address); + String participantDisplayName = + participantContact != null + ? participantContact.getFullName() + : LinphoneUtils.getAddressDisplayName(address); View v = mInflater.inflate(R.layout.chat_imdn_cell, mContainer, false); v.findViewById(R.id.separator).setVisibility(first ? View.GONE : View.VISIBLE); - ((TextView) v.findViewById(R.id.time)).setText(LinphoneUtils.timestampToHumanDate(getActivity(), participant.getStateChangeTime(), R.string.messages_date_format)); + ((TextView) v.findViewById(R.id.time)) + .setText( + LinphoneUtils.timestampToHumanDate( + getActivity(), + participant.getStateChangeTime(), + R.string.messages_date_format)); ((TextView) v.findViewById(R.id.name)).setText(participantDisplayName); if (participantContact != null) { ContactAvatar.displayAvatar(participantContact, v.findViewById(R.id.avatar_layout)); } else { - ContactAvatar.displayAvatar(participantDisplayName, v.findViewById(R.id.avatar_layout)); + ContactAvatar.displayAvatar( + participantDisplayName, v.findViewById(R.id.avatar_layout)); } mDelivered.addView(v); @@ -208,17 +241,27 @@ public class ImdnFragment extends Fragment { for (ParticipantImdnState participant : participants) { Address address = participant.getParticipant().getAddress(); - LinphoneContact participantContact = ContactsManager.getInstance().findContactFromAddress(address); - String participantDisplayName = participantContact != null ? participantContact.getFullName() : LinphoneUtils.getAddressDisplayName(address); + LinphoneContact participantContact = + ContactsManager.getInstance().findContactFromAddress(address); + String participantDisplayName = + participantContact != null + ? participantContact.getFullName() + : LinphoneUtils.getAddressDisplayName(address); View v = mInflater.inflate(R.layout.chat_imdn_cell, mContainer, false); v.findViewById(R.id.separator).setVisibility(first ? View.GONE : View.VISIBLE); - ((TextView) v.findViewById(R.id.time)).setText(LinphoneUtils.timestampToHumanDate(getActivity(), participant.getStateChangeTime(), R.string.messages_date_format)); + ((TextView) v.findViewById(R.id.time)) + .setText( + LinphoneUtils.timestampToHumanDate( + getActivity(), + participant.getStateChangeTime(), + R.string.messages_date_format)); ((TextView) v.findViewById(R.id.name)).setText(participantDisplayName); if (participantContact != null) { ContactAvatar.displayAvatar(participantContact, v.findViewById(R.id.avatar_layout)); } else { - ContactAvatar.displayAvatar(participantDisplayName, v.findViewById(R.id.avatar_layout)); + ContactAvatar.displayAvatar( + participantDisplayName, v.findViewById(R.id.avatar_layout)); } mSent.addView(v); @@ -231,8 +274,12 @@ public class ImdnFragment extends Fragment { for (ParticipantImdnState participant : participants) { Address address = participant.getParticipant().getAddress(); - LinphoneContact participantContact = ContactsManager.getInstance().findContactFromAddress(address); - String participantDisplayName = participantContact != null ? participantContact.getFullName() : LinphoneUtils.getAddressDisplayName(address); + LinphoneContact participantContact = + ContactsManager.getInstance().findContactFromAddress(address); + String participantDisplayName = + participantContact != null + ? participantContact.getFullName() + : LinphoneUtils.getAddressDisplayName(address); View v = mInflater.inflate(R.layout.chat_imdn_cell, mContainer, false); v.findViewById(R.id.separator).setVisibility(first ? View.GONE : View.VISIBLE); @@ -240,7 +287,8 @@ public class ImdnFragment extends Fragment { if (participantContact != null) { ContactAvatar.displayAvatar(participantContact, v.findViewById(R.id.avatar_layout)); } else { - ContactAvatar.displayAvatar(participantDisplayName, v.findViewById(R.id.avatar_layout)); + ContactAvatar.displayAvatar( + participantDisplayName, v.findViewById(R.id.avatar_layout)); } mUndelivered.addView(v); diff --git a/app/src/main/java/org/linphone/chat/ImdnOldFragment.java b/app/src/main/java/org/linphone/chat/ImdnOldFragment.java index 6eb71723a..f1b296924 100644 --- a/app/src/main/java/org/linphone/chat/ImdnOldFragment.java +++ b/app/src/main/java/org/linphone/chat/ImdnOldFragment.java @@ -21,7 +21,6 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import android.app.Fragment; import android.os.Bundle; -import androidx.annotation.Nullable; import android.text.Spanned; import android.text.method.LinkMovementMethod; import android.view.LayoutInflater; @@ -31,12 +30,10 @@ import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; - -import org.linphone.LinphoneManager; -import org.linphone.utils.FileUtils; -import org.linphone.utils.LinphoneUtils; -import org.linphone.R; +import androidx.annotation.Nullable; import org.linphone.LinphoneActivity; +import org.linphone.LinphoneManager; +import org.linphone.R; import org.linphone.compatibility.Compatibility; import org.linphone.contacts.ContactsManager; import org.linphone.contacts.LinphoneContact; @@ -47,11 +44,20 @@ import org.linphone.core.ChatRoom; import org.linphone.core.Core; import org.linphone.core.ParticipantImdnState; import org.linphone.fragments.FragmentsAvailable; +import org.linphone.utils.FileUtils; +import org.linphone.utils.LinphoneUtils; import org.linphone.views.ContactAvatar; public class ImdnOldFragment extends Fragment { private LayoutInflater mInflater; - private LinearLayout mRead, mReadHeader, mDelivered, mDeliveredHeader, mSent, mSentHeader, mUndelivered, mUndeliveredHeader; + private LinearLayout mRead, + mReadHeader, + mDelivered, + mDeliveredHeader, + mSent, + mSentHeader, + mUndelivered, + mUndeliveredHeader; private ImageView mBackButton; private ChatMessageOldViewHolder mBubble; private ViewGroup mContainer; @@ -64,7 +70,8 @@ public class ImdnOldFragment extends Fragment { @Nullable @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { + public View onCreateView( + LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { @@ -81,16 +88,17 @@ public class ImdnOldFragment extends Fragment { View view = mInflater.inflate(R.layout.chat_imdn_old, container, false); mBackButton = view.findViewById(R.id.back); - mBackButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - if (LinphoneActivity.instance().isTablet()) { - LinphoneActivity.instance().goToChat(mRoomUri, null); - } else { - LinphoneActivity.instance().onBackPressed(); - } - } - }); + mBackButton.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View view) { + if (LinphoneActivity.instance().isTablet()) { + LinphoneActivity.instance().goToChat(mRoomUri, null); + } else { + LinphoneActivity.instance().onBackPressed(); + } + } + }); mRead = view.findViewById(R.id.read_layout); mDelivered = view.findViewById(R.id.delivered_layout); @@ -115,28 +123,36 @@ public class ImdnOldFragment extends Fragment { mBubble.imdmLayout.setVisibility(View.INVISIBLE); mMessage = mRoom.findMessage(mMessageId); - mListener = new ChatMessageListenerStub() { - @Override - public void onParticipantImdnStateChanged(ChatMessage msg, ParticipantImdnState state) { - refreshInfo(); - } - }; + mListener = + new ChatMessageListenerStub() { + @Override + public void onParticipantImdnStateChanged( + ChatMessage msg, ParticipantImdnState state) { + refreshInfo(); + } + }; if (mMessage == null) return null; mMessage.setListener(mListener); - RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); + RelativeLayout.LayoutParams layoutParams = + new RelativeLayout.LayoutParams( + RelativeLayout.LayoutParams.WRAP_CONTENT, + RelativeLayout.LayoutParams.WRAP_CONTENT); layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); layoutParams.setMargins(100, 10, 10, 10); if (mMessage.isOutgoing()) { mBubble.background.setBackgroundResource(R.drawable.resizable_chat_bubble_outgoing); Compatibility.setTextAppearance(mBubble.contactName, getActivity(), R.style.font3); - Compatibility.setTextAppearance(mBubble.fileTransferAction, getActivity(), R.style.font15); - mBubble.fileTransferAction.setBackgroundResource(R.drawable.resizable_confirm_delete_button); + Compatibility.setTextAppearance( + mBubble.fileTransferAction, getActivity(), R.style.font15); + mBubble.fileTransferAction.setBackgroundResource( + R.drawable.resizable_confirm_delete_button); ContactAvatar.setAvatarMask(mBubble.avatarLayout, R.drawable.avatar_chat_mask_outgoing); } else { mBubble.background.setBackgroundResource(R.drawable.resizable_chat_bubble_incoming); Compatibility.setTextAppearance(mBubble.contactName, getActivity(), R.style.font9); - Compatibility.setTextAppearance(mBubble.fileTransferAction, getActivity(), R.style.font8); + Compatibility.setTextAppearance( + mBubble.fileTransferAction, getActivity(), R.style.font8); mBubble.fileTransferAction.setBackgroundResource(R.drawable.resizable_assistant_button); ContactAvatar.setAvatarMask(mBubble.avatarLayout, R.drawable.avatar_chat_mask); } @@ -157,7 +173,8 @@ public class ImdnOldFragment extends Fragment { private void refreshInfo() { Address remoteSender = mMessage.getFromAddress(); - LinphoneContact contact = ContactsManager.getInstance().findContactFromAddress(remoteSender); + LinphoneContact contact = + ContactsManager.getInstance().findContactFromAddress(remoteSender); String displayName; if (contact != null) { @@ -172,7 +189,11 @@ public class ImdnOldFragment extends Fragment { displayName = LinphoneUtils.getAddressDisplayName(remoteSender); ContactAvatar.displayAvatar(displayName, mBubble.avatarLayout); } - mBubble.contactName.setText(LinphoneUtils.timestampToHumanDate(getActivity(), mMessage.getTime(), R.string.messages_date_format) + " - " + displayName); + mBubble.contactName.setText( + LinphoneUtils.timestampToHumanDate( + getActivity(), mMessage.getTime(), R.string.messages_date_format) + + " - " + + displayName); if (mMessage.hasTextContent()) { String msg = mMessage.getTextContent(); @@ -194,23 +215,34 @@ public class ImdnOldFragment extends Fragment { mSent.removeAllViews(); mUndelivered.removeAllViews(); - ParticipantImdnState[] participants = mMessage.getParticipantsByImdnState(ChatMessage.State.Displayed); + ParticipantImdnState[] participants = + mMessage.getParticipantsByImdnState(ChatMessage.State.Displayed); mReadHeader.setVisibility(participants.length == 0 ? View.GONE : View.VISIBLE); boolean first = true; for (ParticipantImdnState participant : participants) { Address address = participant.getParticipant().getAddress(); - LinphoneContact participantContact = ContactsManager.getInstance().findContactFromAddress(address); - String participantDisplayName = participantContact != null ? participantContact.getFullName() : LinphoneUtils.getAddressDisplayName(address); + LinphoneContact participantContact = + ContactsManager.getInstance().findContactFromAddress(address); + String participantDisplayName = + participantContact != null + ? participantContact.getFullName() + : LinphoneUtils.getAddressDisplayName(address); View v = mInflater.inflate(R.layout.chat_imdn_cell, mContainer, false); v.findViewById(R.id.separator).setVisibility(first ? View.GONE : View.VISIBLE); - ((TextView) v.findViewById(R.id.time)).setText(LinphoneUtils.timestampToHumanDate(getActivity(), participant.getStateChangeTime(), R.string.messages_date_format)); + ((TextView) v.findViewById(R.id.time)) + .setText( + LinphoneUtils.timestampToHumanDate( + getActivity(), + participant.getStateChangeTime(), + R.string.messages_date_format)); ((TextView) v.findViewById(R.id.name)).setText(participantDisplayName); if (participantContact != null) { ContactAvatar.displayAvatar(participantContact, v.findViewById(R.id.avatar_layout)); } else { - ContactAvatar.displayAvatar(participantDisplayName, v.findViewById(R.id.avatar_layout)); + ContactAvatar.displayAvatar( + participantDisplayName, v.findViewById(R.id.avatar_layout)); } mRead.addView(v); @@ -223,17 +255,27 @@ public class ImdnOldFragment extends Fragment { for (ParticipantImdnState participant : participants) { Address address = participant.getParticipant().getAddress(); - LinphoneContact participantContact = ContactsManager.getInstance().findContactFromAddress(address); - String participantDisplayName = participantContact != null ? participantContact.getFullName() : LinphoneUtils.getAddressDisplayName(address); + LinphoneContact participantContact = + ContactsManager.getInstance().findContactFromAddress(address); + String participantDisplayName = + participantContact != null + ? participantContact.getFullName() + : LinphoneUtils.getAddressDisplayName(address); View v = mInflater.inflate(R.layout.chat_imdn_cell, mContainer, false); v.findViewById(R.id.separator).setVisibility(first ? View.GONE : View.VISIBLE); - ((TextView) v.findViewById(R.id.time)).setText(LinphoneUtils.timestampToHumanDate(getActivity(), participant.getStateChangeTime(), R.string.messages_date_format)); + ((TextView) v.findViewById(R.id.time)) + .setText( + LinphoneUtils.timestampToHumanDate( + getActivity(), + participant.getStateChangeTime(), + R.string.messages_date_format)); ((TextView) v.findViewById(R.id.name)).setText(participantDisplayName); if (participantContact != null) { ContactAvatar.displayAvatar(participantContact, v.findViewById(R.id.avatar_layout)); } else { - ContactAvatar.displayAvatar(participantDisplayName, v.findViewById(R.id.avatar_layout)); + ContactAvatar.displayAvatar( + participantDisplayName, v.findViewById(R.id.avatar_layout)); } mDelivered.addView(v); @@ -246,17 +288,27 @@ public class ImdnOldFragment extends Fragment { for (ParticipantImdnState participant : participants) { Address address = participant.getParticipant().getAddress(); - LinphoneContact participantContact = ContactsManager.getInstance().findContactFromAddress(address); - String participantDisplayName = participantContact != null ? participantContact.getFullName() : LinphoneUtils.getAddressDisplayName(address); + LinphoneContact participantContact = + ContactsManager.getInstance().findContactFromAddress(address); + String participantDisplayName = + participantContact != null + ? participantContact.getFullName() + : LinphoneUtils.getAddressDisplayName(address); View v = mInflater.inflate(R.layout.chat_imdn_cell, mContainer, false); v.findViewById(R.id.separator).setVisibility(first ? View.GONE : View.VISIBLE); - ((TextView) v.findViewById(R.id.time)).setText(LinphoneUtils.timestampToHumanDate(getActivity(), participant.getStateChangeTime(), R.string.messages_date_format)); + ((TextView) v.findViewById(R.id.time)) + .setText( + LinphoneUtils.timestampToHumanDate( + getActivity(), + participant.getStateChangeTime(), + R.string.messages_date_format)); ((TextView) v.findViewById(R.id.name)).setText(participantDisplayName); if (participantContact != null) { ContactAvatar.displayAvatar(participantContact, v.findViewById(R.id.avatar_layout)); } else { - ContactAvatar.displayAvatar(participantDisplayName, v.findViewById(R.id.avatar_layout)); + ContactAvatar.displayAvatar( + participantDisplayName, v.findViewById(R.id.avatar_layout)); } mSent.addView(v); @@ -269,8 +321,12 @@ public class ImdnOldFragment extends Fragment { for (ParticipantImdnState participant : participants) { Address address = participant.getParticipant().getAddress(); - LinphoneContact participantContact = ContactsManager.getInstance().findContactFromAddress(address); - String participantDisplayName = participantContact != null ? participantContact.getFullName() : LinphoneUtils.getAddressDisplayName(address); + LinphoneContact participantContact = + ContactsManager.getInstance().findContactFromAddress(address); + String participantDisplayName = + participantContact != null + ? participantContact.getFullName() + : LinphoneUtils.getAddressDisplayName(address); View v = mInflater.inflate(R.layout.chat_imdn_cell, mContainer, false); v.findViewById(R.id.separator).setVisibility(first ? View.GONE : View.VISIBLE); @@ -278,7 +334,8 @@ public class ImdnOldFragment extends Fragment { if (participantContact != null) { ContactAvatar.displayAvatar(participantContact, v.findViewById(R.id.avatar_layout)); } else { - ContactAvatar.displayAvatar(participantDisplayName, v.findViewById(R.id.avatar_layout)); + ContactAvatar.displayAvatar( + participantDisplayName, v.findViewById(R.id.avatar_layout)); } mUndelivered.addView(v); diff --git a/app/src/main/java/org/linphone/compatibility/ApiTwentyEightPlus.java b/app/src/main/java/org/linphone/compatibility/ApiTwentyEightPlus.java index 7f8e621db..38169d978 100644 --- a/app/src/main/java/org/linphone/compatibility/ApiTwentyEightPlus.java +++ b/app/src/main/java/org/linphone/compatibility/ApiTwentyEightPlus.java @@ -19,6 +19,12 @@ along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ +import static org.linphone.compatibility.Compatibility.CHAT_NOTIFICATIONS_GROUP; +import static org.linphone.compatibility.Compatibility.INTENT_LOCAL_IDENTITY; +import static org.linphone.compatibility.Compatibility.INTENT_NOTIF_ID; +import static org.linphone.compatibility.Compatibility.INTENT_REPLY_NOTIF_ACTION; +import static org.linphone.compatibility.Compatibility.KEY_TEXT_REPLY; + import android.annotation.TargetApi; import android.app.Notification; import android.app.PendingIntent; @@ -28,48 +34,51 @@ import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.Icon; -import android.net.Uri; - import org.linphone.R; -import org.linphone.mediastream.Log; import org.linphone.notifications.Notifiable; import org.linphone.notifications.NotifiableMessage; import org.linphone.notifications.NotificationBroadcastReceiver; -import org.linphone.utils.FileUtils; - -import static org.linphone.compatibility.Compatibility.CHAT_NOTIFICATIONS_GROUP; -import static org.linphone.compatibility.Compatibility.INTENT_LOCAL_IDENTITY; -import static org.linphone.compatibility.Compatibility.INTENT_NOTIF_ID; -import static org.linphone.compatibility.Compatibility.INTENT_REPLY_NOTIF_ACTION; -import static org.linphone.compatibility.Compatibility.KEY_TEXT_REPLY; @TargetApi(28) public class ApiTwentyEightPlus { - public static Notification createMessageNotification(Context context, Notifiable notif, Bitmap contactIcon, PendingIntent intent) { + public static Notification createMessageNotification( + Context context, Notifiable notif, Bitmap contactIcon, PendingIntent intent) { String replyLabel = context.getResources().getString(R.string.notification_reply_label); - RemoteInput remoteInput = new RemoteInput.Builder(KEY_TEXT_REPLY).setLabel(replyLabel).build(); + RemoteInput remoteInput = + new RemoteInput.Builder(KEY_TEXT_REPLY).setLabel(replyLabel).build(); Intent replyIntent = new Intent(context, NotificationBroadcastReceiver.class); replyIntent.setAction(INTENT_REPLY_NOTIF_ACTION); replyIntent.putExtra(INTENT_NOTIF_ID, notif.getNotificationId()); replyIntent.putExtra(INTENT_LOCAL_IDENTITY, notif.getLocalIdentity()); - PendingIntent replyPendingIntent = PendingIntent.getBroadcast(context, - notif.getNotificationId(), replyIntent, PendingIntent.FLAG_UPDATE_CURRENT); + PendingIntent replyPendingIntent = + PendingIntent.getBroadcast( + context, + notif.getNotificationId(), + replyIntent, + PendingIntent.FLAG_UPDATE_CURRENT); - Notification.Action action = new Notification.Action.Builder(R.drawable.chat_send_over, - context.getString(R.string.notification_reply_label), replyPendingIntent) - .addRemoteInput(remoteInput) - .setAllowGeneratedReplies(true) - .build(); + Notification.Action action = + new Notification.Action.Builder( + R.drawable.chat_send_over, + context.getString(R.string.notification_reply_label), + replyPendingIntent) + .addRemoteInput(remoteInput) + .setAllowGeneratedReplies(true) + .build(); Person me = new Person.Builder().setName(notif.getMyself()).build(); Notification.MessagingStyle style = new Notification.MessagingStyle(me); for (NotifiableMessage message : notif.getMessages()) { Icon userIcon = Icon.createWithBitmap(message.getSenderBitmap()); - Person user = new Person.Builder().setName(message.getSender()).setIcon(userIcon).build(); - Notification.MessagingStyle.Message msg = new Notification.MessagingStyle.Message(message.getMessage(), message.getTime(), user); - if (message.getFilePath() != null) msg.setData(message.getFileMime(), message.getFilePath()); + Person user = + new Person.Builder().setName(message.getSender()).setIcon(userIcon).build(); + Notification.MessagingStyle.Message msg = + new Notification.MessagingStyle.Message( + message.getMessage(), message.getTime(), user); + if (message.getFilePath() != null) + msg.setData(message.getFileMime(), message.getFilePath()); style.addMessage(msg); } if (notif.isGroup()) { @@ -77,22 +86,26 @@ public class ApiTwentyEightPlus { } style.setGroupConversation(notif.isGroup()); - return new Notification.Builder(context, context.getString(R.string.notification_channel_id)) - .setSmallIcon(R.drawable.topbar_chat_notification) - .setAutoCancel(true) - .setContentIntent(intent) - .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS) - .setLargeIcon(contactIcon) - .setCategory(Notification.CATEGORY_MESSAGE) - .setGroup(CHAT_NOTIFICATIONS_GROUP) - .setVisibility(Notification.VISIBILITY_PRIVATE) - .setPriority(Notification.PRIORITY_HIGH) - .setNumber(notif.getMessages().size()) - .setWhen(System.currentTimeMillis()) - .setShowWhen(true) - .setColor(context.getColor(R.color.notification_color_led)) - .setStyle(style) - .addAction(action) - .build(); + return new Notification.Builder( + context, context.getString(R.string.notification_channel_id)) + .setSmallIcon(R.drawable.topbar_chat_notification) + .setAutoCancel(true) + .setContentIntent(intent) + .setDefaults( + Notification.DEFAULT_SOUND + | Notification.DEFAULT_VIBRATE + | Notification.DEFAULT_LIGHTS) + .setLargeIcon(contactIcon) + .setCategory(Notification.CATEGORY_MESSAGE) + .setGroup(CHAT_NOTIFICATIONS_GROUP) + .setVisibility(Notification.VISIBILITY_PRIVATE) + .setPriority(Notification.PRIORITY_HIGH) + .setNumber(notif.getMessages().size()) + .setWhen(System.currentTimeMillis()) + .setShowWhen(true) + .setColor(context.getColor(R.color.notification_color_led)) + .setStyle(style) + .addAction(action) + .build(); } } diff --git a/app/src/main/java/org/linphone/compatibility/ApiTwentyFourPlus.java b/app/src/main/java/org/linphone/compatibility/ApiTwentyFourPlus.java index 324578072..99aee97ad 100644 --- a/app/src/main/java/org/linphone/compatibility/ApiTwentyFourPlus.java +++ b/app/src/main/java/org/linphone/compatibility/ApiTwentyFourPlus.java @@ -19,22 +19,6 @@ along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -import android.annotation.TargetApi; -import android.app.Notification; -import android.app.PendingIntent; -import android.app.RemoteInput; -import android.content.Context; -import android.content.Intent; -import android.graphics.Bitmap; -import android.net.Uri; - -import org.linphone.R; -import org.linphone.mediastream.Log; -import org.linphone.notifications.Notifiable; -import org.linphone.notifications.NotifiableMessage; -import org.linphone.notifications.NotificationBroadcastReceiver; -import org.linphone.utils.FileUtils; - import static org.linphone.compatibility.Compatibility.CHAT_NOTIFICATIONS_GROUP; import static org.linphone.compatibility.Compatibility.INTENT_ANSWER_CALL_NOTIF_ACTION; import static org.linphone.compatibility.Compatibility.INTENT_HANGUP_CALL_NOTIF_ACTION; @@ -43,97 +27,141 @@ import static org.linphone.compatibility.Compatibility.INTENT_NOTIF_ID; import static org.linphone.compatibility.Compatibility.INTENT_REPLY_NOTIF_ACTION; import static org.linphone.compatibility.Compatibility.KEY_TEXT_REPLY; +import android.annotation.TargetApi; +import android.app.Notification; +import android.app.PendingIntent; +import android.app.RemoteInput; +import android.content.Context; +import android.content.Intent; +import android.graphics.Bitmap; +import org.linphone.R; +import org.linphone.notifications.Notifiable; +import org.linphone.notifications.NotifiableMessage; +import org.linphone.notifications.NotificationBroadcastReceiver; + @TargetApi(24) public class ApiTwentyFourPlus { - public static Notification createRepliedNotification(Context context, String reply) { - return new Notification.Builder(context) - .setSmallIcon(R.drawable.topbar_chat_notification) - .setContentText(context.getString(R.string.notification_replied_label).replace("%s", reply)) - .build(); - } + public static Notification createRepliedNotification(Context context, String reply) { + return new Notification.Builder(context) + .setSmallIcon(R.drawable.topbar_chat_notification) + .setContentText( + context.getString(R.string.notification_replied_label).replace("%s", reply)) + .build(); + } - public static Notification createMessageNotification(Context context, Notifiable notif, Bitmap contactIcon, PendingIntent intent) { - String replyLabel = context.getResources().getString(R.string.notification_reply_label); - RemoteInput remoteInput = new RemoteInput.Builder(KEY_TEXT_REPLY).setLabel(replyLabel).build(); + public static Notification createMessageNotification( + Context context, Notifiable notif, Bitmap contactIcon, PendingIntent intent) { + String replyLabel = context.getResources().getString(R.string.notification_reply_label); + RemoteInput remoteInput = + new RemoteInput.Builder(KEY_TEXT_REPLY).setLabel(replyLabel).build(); - Intent replyIntent = new Intent(context, NotificationBroadcastReceiver.class); - replyIntent.setAction(INTENT_REPLY_NOTIF_ACTION); - replyIntent.putExtra(INTENT_NOTIF_ID, notif.getNotificationId()); - replyIntent.putExtra(INTENT_LOCAL_IDENTITY, notif.getLocalIdentity()); + Intent replyIntent = new Intent(context, NotificationBroadcastReceiver.class); + replyIntent.setAction(INTENT_REPLY_NOTIF_ACTION); + replyIntent.putExtra(INTENT_NOTIF_ID, notif.getNotificationId()); + replyIntent.putExtra(INTENT_LOCAL_IDENTITY, notif.getLocalIdentity()); - PendingIntent replyPendingIntent = PendingIntent.getBroadcast(context, - notif.getNotificationId(), replyIntent, PendingIntent.FLAG_UPDATE_CURRENT); + PendingIntent replyPendingIntent = + PendingIntent.getBroadcast( + context, + notif.getNotificationId(), + replyIntent, + PendingIntent.FLAG_UPDATE_CURRENT); - Notification.Action action = new Notification.Action.Builder(R.drawable.chat_send_over, - context.getString(R.string.notification_reply_label), replyPendingIntent) - .addRemoteInput(remoteInput) - .setAllowGeneratedReplies(true) - .build(); + Notification.Action action = + new Notification.Action.Builder( + R.drawable.chat_send_over, + context.getString(R.string.notification_reply_label), + replyPendingIntent) + .addRemoteInput(remoteInput) + .setAllowGeneratedReplies(true) + .build(); - Notification.MessagingStyle style = new Notification.MessagingStyle(notif.getMyself()); - for (NotifiableMessage message : notif.getMessages()) { - Notification.MessagingStyle.Message msg = new Notification.MessagingStyle.Message(message.getMessage(), message.getTime(), message.getSender()); - if (message.getFilePath() != null) msg.setData(message.getFileMime(), message.getFilePath()); + Notification.MessagingStyle style = new Notification.MessagingStyle(notif.getMyself()); + for (NotifiableMessage message : notif.getMessages()) { + Notification.MessagingStyle.Message msg = + new Notification.MessagingStyle.Message( + message.getMessage(), message.getTime(), message.getSender()); + if (message.getFilePath() != null) + msg.setData(message.getFileMime(), message.getFilePath()); style.addMessage(msg); - } - if (notif.isGroup()) { - style.setConversationTitle(notif.getGroupTitle()); - } + } + if (notif.isGroup()) { + style.setConversationTitle(notif.getGroupTitle()); + } - return new Notification.Builder(context) - .setSmallIcon(R.drawable.topbar_chat_notification) - .setAutoCancel(true) - .setContentIntent(intent) - .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS) - .setLargeIcon(contactIcon) - .setCategory(Notification.CATEGORY_MESSAGE) - .setGroup(CHAT_NOTIFICATIONS_GROUP) - .setVisibility(Notification.VISIBILITY_PRIVATE) - .setPriority(Notification.PRIORITY_HIGH) - .setNumber(notif.getMessages().size()) - .setWhen(System.currentTimeMillis()) - .setShowWhen(true) - .setColor(context.getColor(R.color.notification_color_led)) - .setStyle(style) - .addAction(action) - .build(); - } + return new Notification.Builder(context) + .setSmallIcon(R.drawable.topbar_chat_notification) + .setAutoCancel(true) + .setContentIntent(intent) + .setDefaults( + Notification.DEFAULT_SOUND + | Notification.DEFAULT_VIBRATE + | Notification.DEFAULT_LIGHTS) + .setLargeIcon(contactIcon) + .setCategory(Notification.CATEGORY_MESSAGE) + .setGroup(CHAT_NOTIFICATIONS_GROUP) + .setVisibility(Notification.VISIBILITY_PRIVATE) + .setPriority(Notification.PRIORITY_HIGH) + .setNumber(notif.getMessages().size()) + .setWhen(System.currentTimeMillis()) + .setShowWhen(true) + .setColor(context.getColor(R.color.notification_color_led)) + .setStyle(style) + .addAction(action) + .build(); + } - public static Notification createInCallNotification(Context context, - int callId, boolean showAnswerAction, String msg, int iconID, Bitmap contactIcon, String contactName, PendingIntent intent) { + public static Notification createInCallNotification( + Context context, + int callId, + boolean showAnswerAction, + String msg, + int iconID, + Bitmap contactIcon, + String contactName, + PendingIntent intent) { - Intent hangupIntent = new Intent(context, NotificationBroadcastReceiver.class); - hangupIntent.setAction(INTENT_HANGUP_CALL_NOTIF_ACTION); - hangupIntent.putExtra(INTENT_NOTIF_ID, callId); + Intent hangupIntent = new Intent(context, NotificationBroadcastReceiver.class); + hangupIntent.setAction(INTENT_HANGUP_CALL_NOTIF_ACTION); + hangupIntent.putExtra(INTENT_NOTIF_ID, callId); - PendingIntent hangupPendingIntent = PendingIntent.getBroadcast(context, - callId, hangupIntent, PendingIntent.FLAG_UPDATE_CURRENT); + PendingIntent hangupPendingIntent = + PendingIntent.getBroadcast( + context, callId, hangupIntent, PendingIntent.FLAG_UPDATE_CURRENT); - Notification.Builder builder = new Notification.Builder(context) - .setContentTitle(contactName) - .setContentText(msg) - .setSmallIcon(iconID) - .setAutoCancel(false) - .setContentIntent(intent) - .setLargeIcon(contactIcon) - .setCategory(Notification.CATEGORY_CALL) - .setVisibility(Notification.VISIBILITY_PUBLIC) - .setPriority(Notification.PRIORITY_HIGH) - .setWhen(System.currentTimeMillis()) - .setShowWhen(true) - .setColor(context.getColor(R.color.notification_color_led)) - .addAction(R.drawable.call_hangup, context.getString(R.string.notification_call_hangup_label), hangupPendingIntent); + Notification.Builder builder = + new Notification.Builder(context) + .setContentTitle(contactName) + .setContentText(msg) + .setSmallIcon(iconID) + .setAutoCancel(false) + .setContentIntent(intent) + .setLargeIcon(contactIcon) + .setCategory(Notification.CATEGORY_CALL) + .setVisibility(Notification.VISIBILITY_PUBLIC) + .setPriority(Notification.PRIORITY_HIGH) + .setWhen(System.currentTimeMillis()) + .setShowWhen(true) + .setColor(context.getColor(R.color.notification_color_led)) + .addAction( + R.drawable.call_hangup, + context.getString(R.string.notification_call_hangup_label), + hangupPendingIntent); if (showAnswerAction) { Intent answerIntent = new Intent(context, NotificationBroadcastReceiver.class); answerIntent.setAction(INTENT_ANSWER_CALL_NOTIF_ACTION); answerIntent.putExtra(INTENT_NOTIF_ID, callId); - PendingIntent answerPendingIntent = PendingIntent.getBroadcast(context, - callId, answerIntent, PendingIntent.FLAG_UPDATE_CURRENT); + PendingIntent answerPendingIntent = + PendingIntent.getBroadcast( + context, callId, answerIntent, PendingIntent.FLAG_UPDATE_CURRENT); - builder.addAction(R.drawable.call_audio_start, context.getString(R.string.notification_call_answer_label), answerPendingIntent); + builder.addAction( + R.drawable.call_audio_start, + context.getString(R.string.notification_call_answer_label), + answerPendingIntent); } return builder.build(); diff --git a/app/src/main/java/org/linphone/compatibility/ApiTwentyOnePlus.java b/app/src/main/java/org/linphone/compatibility/ApiTwentyOnePlus.java index 2d3f7d638..55f2366fb 100644 --- a/app/src/main/java/org/linphone/compatibility/ApiTwentyOnePlus.java +++ b/app/src/main/java/org/linphone/compatibility/ApiTwentyOnePlus.java @@ -25,148 +25,183 @@ import android.app.PendingIntent; import android.content.Context; import android.graphics.Bitmap; import androidx.core.content.ContextCompat; - import org.linphone.R; @TargetApi(21) public class ApiTwentyOnePlus { @SuppressWarnings("deprecation") - public static Notification createMessageNotification(Context context, - int msgCount, String msgSender, String msg, Bitmap contactIcon, - PendingIntent intent) { + public static Notification createMessageNotification( + Context context, + int msgCount, + String msgSender, + String msg, + Bitmap contactIcon, + PendingIntent intent) { String title; if (msgCount == 1) { title = msgSender; } else { - title = context.getString(R.string.unread_messages).replace("%i", String.valueOf(msgCount)); + title = + context.getString(R.string.unread_messages) + .replace("%i", String.valueOf(msgCount)); } - Notification notif = new Notification.Builder(context) - .setContentTitle(title) - .setContentText(msg) - .setSmallIcon(R.drawable.topbar_chat_notification) - .setAutoCancel(true) - .setContentIntent(intent) - .setDefaults(Notification.DEFAULT_SOUND - | Notification.DEFAULT_VIBRATE - | Notification.DEFAULT_LIGHTS) - .setLargeIcon(contactIcon) - .setLights(ContextCompat.getColor(context, R.color.notification_color_led), - context.getResources().getInteger(R.integer.notification_ms_on), - context.getResources().getInteger(R.integer.notification_ms_off)) - .setCategory(Notification.CATEGORY_MESSAGE) - .setVisibility(Notification.VISIBILITY_PRIVATE) - .setPriority(Notification.PRIORITY_HIGH) - .setNumber(msgCount) - .setWhen(System.currentTimeMillis()) - .setShowWhen(true) - .build(); + Notification notif = + new Notification.Builder(context) + .setContentTitle(title) + .setContentText(msg) + .setSmallIcon(R.drawable.topbar_chat_notification) + .setAutoCancel(true) + .setContentIntent(intent) + .setDefaults( + Notification.DEFAULT_SOUND + | Notification.DEFAULT_VIBRATE + | Notification.DEFAULT_LIGHTS) + .setLargeIcon(contactIcon) + .setLights( + ContextCompat.getColor(context, R.color.notification_color_led), + context.getResources().getInteger(R.integer.notification_ms_on), + context.getResources().getInteger(R.integer.notification_ms_off)) + .setCategory(Notification.CATEGORY_MESSAGE) + .setVisibility(Notification.VISIBILITY_PRIVATE) + .setPriority(Notification.PRIORITY_HIGH) + .setNumber(msgCount) + .setWhen(System.currentTimeMillis()) + .setShowWhen(true) + .build(); return notif; } - public static Notification createInCallNotification(Context context, - String title, String msg, int iconID, Bitmap contactIcon, - String contactName, PendingIntent intent) { + public static Notification createInCallNotification( + Context context, + String title, + String msg, + int iconID, + Bitmap contactIcon, + String contactName, + PendingIntent intent) { - Notification notif = new Notification.Builder(context).setContentTitle(contactName) - .setContentText(msg) - .setSmallIcon(iconID) - .setAutoCancel(false) - .setContentIntent(intent) - .setLargeIcon(contactIcon) - .setCategory(Notification.CATEGORY_CALL) - .setVisibility(Notification.VISIBILITY_PUBLIC) - .setPriority(Notification.PRIORITY_HIGH) - .setLights(ContextCompat.getColor(context, R.color.notification_color_led), - context.getResources().getInteger(R.integer.notification_ms_on), - context.getResources().getInteger(R.integer.notification_ms_off)) - .setShowWhen(true) - .build(); + Notification notif = + new Notification.Builder(context) + .setContentTitle(contactName) + .setContentText(msg) + .setSmallIcon(iconID) + .setAutoCancel(false) + .setContentIntent(intent) + .setLargeIcon(contactIcon) + .setCategory(Notification.CATEGORY_CALL) + .setVisibility(Notification.VISIBILITY_PUBLIC) + .setPriority(Notification.PRIORITY_HIGH) + .setLights( + ContextCompat.getColor(context, R.color.notification_color_led), + context.getResources().getInteger(R.integer.notification_ms_on), + context.getResources().getInteger(R.integer.notification_ms_off)) + .setShowWhen(true) + .build(); return notif; } - public static Notification createNotification(Context context, String title, String message, int icon, int level, Bitmap largeIcon, PendingIntent intent, boolean isOngoingEvent, int priority) { + public static Notification createNotification( + Context context, + String title, + String message, + int icon, + int level, + Bitmap largeIcon, + PendingIntent intent, + boolean isOngoingEvent, + int priority) { Notification notif; if (largeIcon != null) { - notif = new Notification.Builder(context) - .setContentTitle(title) - .setContentText(message) - .setSmallIcon(icon, level) - .setLargeIcon(largeIcon) - .setContentIntent(intent) - .setCategory(Notification.CATEGORY_SERVICE) - .setVisibility(Notification.VISIBILITY_SECRET) - .setLights(ContextCompat.getColor(context, R.color.notification_color_led), - context.getResources().getInteger(R.integer.notification_ms_on), - context.getResources().getInteger(R.integer.notification_ms_off)) - .setWhen(System.currentTimeMillis()) - .setPriority(priority) - .setShowWhen(true) - .build(); + notif = + new Notification.Builder(context) + .setContentTitle(title) + .setContentText(message) + .setSmallIcon(icon, level) + .setLargeIcon(largeIcon) + .setContentIntent(intent) + .setCategory(Notification.CATEGORY_SERVICE) + .setVisibility(Notification.VISIBILITY_SECRET) + .setLights( + ContextCompat.getColor(context, R.color.notification_color_led), + context.getResources().getInteger(R.integer.notification_ms_on), + context.getResources() + .getInteger(R.integer.notification_ms_off)) + .setWhen(System.currentTimeMillis()) + .setPriority(priority) + .setShowWhen(true) + .build(); } else { - notif = new Notification.Builder(context) - .setContentTitle(title) - .setContentText(message) - .setSmallIcon(icon, level) - .setContentIntent(intent) - .setCategory(Notification.CATEGORY_SERVICE) - .setVisibility(Notification.VISIBILITY_SECRET) - .setLights(ContextCompat.getColor(context, R.color.notification_color_led), - context.getResources().getInteger(R.integer.notification_ms_on), - context.getResources().getInteger(R.integer.notification_ms_off)) - .setPriority(priority) - .setWhen(System.currentTimeMillis()) - .setShowWhen(true) - .build(); + notif = + new Notification.Builder(context) + .setContentTitle(title) + .setContentText(message) + .setSmallIcon(icon, level) + .setContentIntent(intent) + .setCategory(Notification.CATEGORY_SERVICE) + .setVisibility(Notification.VISIBILITY_SECRET) + .setLights( + ContextCompat.getColor(context, R.color.notification_color_led), + context.getResources().getInteger(R.integer.notification_ms_on), + context.getResources() + .getInteger(R.integer.notification_ms_off)) + .setPriority(priority) + .setWhen(System.currentTimeMillis()) + .setShowWhen(true) + .build(); } return notif; } - public static Notification createMissedCallNotification(Context context, String title, String text, PendingIntent intent) { - Notification notif = new Notification.Builder(context) - .setContentTitle(title) - .setContentText(text) - .setSmallIcon(R.drawable.call_status_missed) - .setAutoCancel(true) - .setContentIntent(intent) - .setDefaults(Notification.DEFAULT_SOUND - | Notification.DEFAULT_VIBRATE) - .setCategory(Notification.CATEGORY_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 createMissedCallNotification( + Context context, String title, String text, PendingIntent intent) { + Notification notif = + new Notification.Builder(context) + .setContentTitle(title) + .setContentText(text) + .setSmallIcon(R.drawable.call_status_missed) + .setAutoCancel(true) + .setContentIntent(intent) + .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE) + .setCategory(Notification.CATEGORY_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; } - public static Notification createSimpleNotification(Context context, String title, String text, PendingIntent intent) { - Notification notif = new Notification.Builder(context) - .setContentTitle(title) - .setContentText(text) - .setSmallIcon(R.drawable.linphone_logo) - .setAutoCancel(true) - .setContentIntent(intent) - .setDefaults(Notification.DEFAULT_SOUND - | Notification.DEFAULT_VIBRATE) - .setCategory(Notification.CATEGORY_MESSAGE) - .setVisibility(Notification.VISIBILITY_PRIVATE) - .setLights(ContextCompat.getColor(context, R.color.notification_color_led), - context.getResources().getInteger(R.integer.notification_ms_on), - context.getResources().getInteger(R.integer.notification_ms_off)) - .setWhen(System.currentTimeMillis()) - .setPriority(Notification.PRIORITY_HIGH) - .setShowWhen(true) - .build(); + public static Notification createSimpleNotification( + Context context, String title, String text, PendingIntent intent) { + Notification notif = + new Notification.Builder(context) + .setContentTitle(title) + .setContentText(text) + .setSmallIcon(R.drawable.linphone_logo) + .setAutoCancel(true) + .setContentIntent(intent) + .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE) + .setCategory(Notification.CATEGORY_MESSAGE) + .setVisibility(Notification.VISIBILITY_PRIVATE) + .setLights( + ContextCompat.getColor(context, R.color.notification_color_led), + context.getResources().getInteger(R.integer.notification_ms_on), + context.getResources().getInteger(R.integer.notification_ms_off)) + .setWhen(System.currentTimeMillis()) + .setPriority(Notification.PRIORITY_HIGH) + .setShowWhen(true) + .build(); return notif; } diff --git a/app/src/main/java/org/linphone/compatibility/ApiTwentySixPlus.java b/app/src/main/java/org/linphone/compatibility/ApiTwentySixPlus.java index 6573fc2c3..0a6bea2b1 100644 --- a/app/src/main/java/org/linphone/compatibility/ApiTwentySixPlus.java +++ b/app/src/main/java/org/linphone/compatibility/ApiTwentySixPlus.java @@ -19,6 +19,14 @@ along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ +import static org.linphone.compatibility.Compatibility.CHAT_NOTIFICATIONS_GROUP; +import static org.linphone.compatibility.Compatibility.INTENT_ANSWER_CALL_NOTIF_ACTION; +import static org.linphone.compatibility.Compatibility.INTENT_HANGUP_CALL_NOTIF_ACTION; +import static org.linphone.compatibility.Compatibility.INTENT_LOCAL_IDENTITY; +import static org.linphone.compatibility.Compatibility.INTENT_NOTIF_ID; +import static org.linphone.compatibility.Compatibility.INTENT_REPLY_NOTIF_ACTION; +import static org.linphone.compatibility.Compatibility.KEY_TEXT_REPLY; + import android.annotation.TargetApi; import android.app.FragmentTransaction; import android.app.Notification; @@ -29,45 +37,37 @@ import android.app.RemoteInput; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; -import android.net.Uri; - import org.linphone.R; import org.linphone.notifications.Notifiable; import org.linphone.notifications.NotifiableMessage; import org.linphone.notifications.NotificationBroadcastReceiver; -import org.linphone.utils.FileUtils; - -import static org.linphone.compatibility.Compatibility.CHAT_NOTIFICATIONS_GROUP; -import static org.linphone.compatibility.Compatibility.INTENT_ANSWER_CALL_NOTIF_ACTION; -import static org.linphone.compatibility.Compatibility.INTENT_HANGUP_CALL_NOTIF_ACTION; -import static org.linphone.compatibility.Compatibility.INTENT_LOCAL_IDENTITY; -import static org.linphone.compatibility.Compatibility.INTENT_NOTIF_ID; -import static org.linphone.compatibility.Compatibility.INTENT_REPLY_NOTIF_ACTION; -import static org.linphone.compatibility.Compatibility.KEY_TEXT_REPLY; @TargetApi(26) public class ApiTwentySixPlus { - public static Notification createRepliedNotification(Context context, String reply) { - return new Notification.Builder(context, context.getString(R.string.notification_channel_id)) - .setSmallIcon(R.drawable.topbar_chat_notification) - .setContentText(context.getString(R.string.notification_replied_label).replace("%s", reply)) - .build(); - } + public static Notification createRepliedNotification(Context context, String reply) { + return new Notification.Builder( + context, context.getString(R.string.notification_channel_id)) + .setSmallIcon(R.drawable.topbar_chat_notification) + .setContentText( + context.getString(R.string.notification_replied_label).replace("%s", reply)) + .build(); + } - public static void createServiceChannel(Context context) { - NotificationManager notificationManager = - (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); - // Create service/call notification channel - String id = context.getString(R.string.notification_service_channel_id); - CharSequence name = context.getString(R.string.content_title_notification_service); - String description = context.getString(R.string.content_title_notification_service); - NotificationChannel channel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_NONE); - channel.setDescription(description); - channel.enableVibration(false); - channel.enableLights(false); + public static void createServiceChannel(Context context) { + NotificationManager notificationManager = + (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); + // Create service/call notification channel + String id = context.getString(R.string.notification_service_channel_id); + CharSequence name = context.getString(R.string.content_title_notification_service); + String description = context.getString(R.string.content_title_notification_service); + NotificationChannel channel = + new NotificationChannel(id, name, NotificationManager.IMPORTANCE_NONE); + channel.setDescription(description); + channel.enableVibration(false); + channel.enableLights(false); channel.setShowBadge(false); - notificationManager.createNotificationChannel(channel); - } + notificationManager.createNotificationChannel(channel); + } public static void createMessageChannel(Context context) { NotificationManager notificationManager = @@ -76,7 +76,8 @@ public class ApiTwentySixPlus { String id = context.getString(R.string.notification_channel_id); String name = context.getString(R.string.content_title_notification); String description = context.getString(R.string.content_title_notification); - NotificationChannel channel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_HIGH); + NotificationChannel channel = + new NotificationChannel(id, name, NotificationManager.IMPORTANCE_HIGH); channel.setDescription(description); channel.setLightColor(context.getColor(R.color.notification_color_led)); channel.enableLights(true); @@ -85,166 +86,213 @@ public class ApiTwentySixPlus { notificationManager.createNotificationChannel(channel); } - public static Notification createMessageNotification(Context context, Notifiable notif, Bitmap contactIcon, PendingIntent intent) { - String replyLabel = context.getResources().getString(R.string.notification_reply_label); - RemoteInput remoteInput = new RemoteInput.Builder(KEY_TEXT_REPLY).setLabel(replyLabel).build(); + public static Notification createMessageNotification( + Context context, Notifiable notif, Bitmap contactIcon, PendingIntent intent) { + String replyLabel = context.getResources().getString(R.string.notification_reply_label); + RemoteInput remoteInput = + new RemoteInput.Builder(KEY_TEXT_REPLY).setLabel(replyLabel).build(); - Intent replyIntent = new Intent(context, NotificationBroadcastReceiver.class); - replyIntent.setAction(INTENT_REPLY_NOTIF_ACTION); - replyIntent.putExtra(INTENT_NOTIF_ID, notif.getNotificationId()); - replyIntent.putExtra(INTENT_LOCAL_IDENTITY, notif.getLocalIdentity()); + Intent replyIntent = new Intent(context, NotificationBroadcastReceiver.class); + replyIntent.setAction(INTENT_REPLY_NOTIF_ACTION); + replyIntent.putExtra(INTENT_NOTIF_ID, notif.getNotificationId()); + replyIntent.putExtra(INTENT_LOCAL_IDENTITY, notif.getLocalIdentity()); - PendingIntent replyPendingIntent = PendingIntent.getBroadcast(context, - notif.getNotificationId(), replyIntent, PendingIntent.FLAG_UPDATE_CURRENT); + PendingIntent replyPendingIntent = + PendingIntent.getBroadcast( + context, + notif.getNotificationId(), + replyIntent, + PendingIntent.FLAG_UPDATE_CURRENT); - Notification.Action action = new Notification.Action.Builder(R.drawable.chat_send_over, - context.getString(R.string.notification_reply_label), replyPendingIntent) - .addRemoteInput(remoteInput) - .setAllowGeneratedReplies(true) - .build(); + Notification.Action action = + new Notification.Action.Builder( + R.drawable.chat_send_over, + context.getString(R.string.notification_reply_label), + replyPendingIntent) + .addRemoteInput(remoteInput) + .setAllowGeneratedReplies(true) + .build(); - Notification.MessagingStyle style = new Notification.MessagingStyle(notif.getMyself()); - for (NotifiableMessage message : notif.getMessages()) { - Notification.MessagingStyle.Message msg = new Notification.MessagingStyle.Message(message.getMessage(), message.getTime(), message.getSender()); - if (message.getFilePath() != null) msg.setData(message.getFileMime(), message.getFilePath()); + Notification.MessagingStyle style = new Notification.MessagingStyle(notif.getMyself()); + for (NotifiableMessage message : notif.getMessages()) { + Notification.MessagingStyle.Message msg = + new Notification.MessagingStyle.Message( + message.getMessage(), message.getTime(), message.getSender()); + if (message.getFilePath() != null) + msg.setData(message.getFileMime(), message.getFilePath()); style.addMessage(msg); - } - if (notif.isGroup()) { - style.setConversationTitle(notif.getGroupTitle()); - } + } + if (notif.isGroup()) { + style.setConversationTitle(notif.getGroupTitle()); + } - return new Notification.Builder(context, context.getString(R.string.notification_channel_id)) - .setSmallIcon(R.drawable.topbar_chat_notification) - .setAutoCancel(true) - .setContentIntent(intent) - .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS) - .setLargeIcon(contactIcon) - .setCategory(Notification.CATEGORY_MESSAGE) - .setGroup(CHAT_NOTIFICATIONS_GROUP) - .setVisibility(Notification.VISIBILITY_PRIVATE) - .setPriority(Notification.PRIORITY_HIGH) - .setNumber(notif.getMessages().size()) - .setWhen(System.currentTimeMillis()) - .setShowWhen(true) - .setColor(context.getColor(R.color.notification_color_led)) - .setStyle(style) - .addAction(action) - .build(); - } + return new Notification.Builder( + context, context.getString(R.string.notification_channel_id)) + .setSmallIcon(R.drawable.topbar_chat_notification) + .setAutoCancel(true) + .setContentIntent(intent) + .setDefaults( + Notification.DEFAULT_SOUND + | Notification.DEFAULT_VIBRATE + | Notification.DEFAULT_LIGHTS) + .setLargeIcon(contactIcon) + .setCategory(Notification.CATEGORY_MESSAGE) + .setGroup(CHAT_NOTIFICATIONS_GROUP) + .setVisibility(Notification.VISIBILITY_PRIVATE) + .setPriority(Notification.PRIORITY_HIGH) + .setNumber(notif.getMessages().size()) + .setWhen(System.currentTimeMillis()) + .setShowWhen(true) + .setColor(context.getColor(R.color.notification_color_led)) + .setStyle(style) + .addAction(action) + .build(); + } - public static Notification createInCallNotification(Context context, - int callId, boolean showAnswerAction, String msg, int iconID, Bitmap contactIcon, String contactName, PendingIntent intent) { + public static Notification createInCallNotification( + Context context, + int callId, + boolean showAnswerAction, + String msg, + int iconID, + Bitmap contactIcon, + String contactName, + PendingIntent intent) { Intent hangupIntent = new Intent(context, NotificationBroadcastReceiver.class); hangupIntent.setAction(INTENT_HANGUP_CALL_NOTIF_ACTION); hangupIntent.putExtra(INTENT_NOTIF_ID, callId); - PendingIntent hangupPendingIntent = PendingIntent.getBroadcast(context, - callId, hangupIntent, PendingIntent.FLAG_UPDATE_CURRENT); + PendingIntent hangupPendingIntent = + PendingIntent.getBroadcast( + context, callId, hangupIntent, PendingIntent.FLAG_UPDATE_CURRENT); - Notification.Builder builder = new Notification.Builder(context, context.getString(R.string.notification_service_channel_id)) - .setContentTitle(contactName) - .setContentText(msg) - .setSmallIcon(iconID) - .setAutoCancel(false) - .setContentIntent(intent) - .setLargeIcon(contactIcon) - .setCategory(Notification.CATEGORY_CALL) - .setVisibility(Notification.VISIBILITY_PUBLIC) - .setPriority(Notification.PRIORITY_HIGH) - .setWhen(System.currentTimeMillis()) - .setShowWhen(true) - .setColor(context.getColor(R.color.notification_color_led)) - .addAction(R.drawable.call_hangup, context.getString(R.string.notification_call_hangup_label), hangupPendingIntent); + Notification.Builder builder = + new Notification.Builder( + context, + context.getString(R.string.notification_service_channel_id)) + .setContentTitle(contactName) + .setContentText(msg) + .setSmallIcon(iconID) + .setAutoCancel(false) + .setContentIntent(intent) + .setLargeIcon(contactIcon) + .setCategory(Notification.CATEGORY_CALL) + .setVisibility(Notification.VISIBILITY_PUBLIC) + .setPriority(Notification.PRIORITY_HIGH) + .setWhen(System.currentTimeMillis()) + .setShowWhen(true) + .setColor(context.getColor(R.color.notification_color_led)) + .addAction( + R.drawable.call_hangup, + context.getString(R.string.notification_call_hangup_label), + hangupPendingIntent); if (showAnswerAction) { Intent answerIntent = new Intent(context, NotificationBroadcastReceiver.class); answerIntent.setAction(INTENT_ANSWER_CALL_NOTIF_ACTION); answerIntent.putExtra(INTENT_NOTIF_ID, callId); - PendingIntent answerPendingIntent = PendingIntent.getBroadcast(context, - callId, answerIntent, PendingIntent.FLAG_UPDATE_CURRENT); + PendingIntent answerPendingIntent = + PendingIntent.getBroadcast( + context, callId, answerIntent, PendingIntent.FLAG_UPDATE_CURRENT); - builder.addAction(R.drawable.call_audio_start, context.getString(R.string.notification_call_answer_label), answerPendingIntent); + builder.addAction( + R.drawable.call_audio_start, + context.getString(R.string.notification_call_answer_label), + answerPendingIntent); } return builder.build(); - } + } - public static Notification createNotification(Context context, String title, String message, int icon, int level, - Bitmap largeIcon, PendingIntent intent, boolean isOngoingEvent,int priority) { + public static Notification createNotification( + Context context, + String title, + String message, + int icon, + int level, + Bitmap largeIcon, + PendingIntent intent, + boolean isOngoingEvent, + int priority) { - if (largeIcon != null) { - return new Notification.Builder(context, context.getString(R.string.notification_service_channel_id)) - .setContentTitle(title) - .setContentText(message) - .setSmallIcon(icon, level) - .setLargeIcon(largeIcon) - .setContentIntent(intent) - .setCategory(Notification.CATEGORY_SERVICE) - .setVisibility(Notification.VISIBILITY_SECRET) - .setPriority(priority) - .setWhen(System.currentTimeMillis()) - .setShowWhen(true) - .setColor(context.getColor(R.color.notification_color_led)) - .build(); - } else { - return new Notification.Builder(context, context.getString(R.string.notification_service_channel_id)) - .setContentTitle(title) - .setContentText(message) - .setSmallIcon(icon, level) - .setContentIntent(intent) - .setCategory(Notification.CATEGORY_SERVICE) - .setVisibility(Notification.VISIBILITY_SECRET) - .setPriority(priority) - .setWhen(System.currentTimeMillis()) - .setShowWhen(true) - .setColor(context.getColor(R.color.notification_color_led)) - .build(); - } - } + if (largeIcon != null) { + return new Notification.Builder( + context, context.getString(R.string.notification_service_channel_id)) + .setContentTitle(title) + .setContentText(message) + .setSmallIcon(icon, level) + .setLargeIcon(largeIcon) + .setContentIntent(intent) + .setCategory(Notification.CATEGORY_SERVICE) + .setVisibility(Notification.VISIBILITY_SECRET) + .setPriority(priority) + .setWhen(System.currentTimeMillis()) + .setShowWhen(true) + .setColor(context.getColor(R.color.notification_color_led)) + .build(); + } else { + return new Notification.Builder( + context, context.getString(R.string.notification_service_channel_id)) + .setContentTitle(title) + .setContentText(message) + .setSmallIcon(icon, level) + .setContentIntent(intent) + .setCategory(Notification.CATEGORY_SERVICE) + .setVisibility(Notification.VISIBILITY_SECRET) + .setPriority(priority) + .setWhen(System.currentTimeMillis()) + .setShowWhen(true) + .setColor(context.getColor(R.color.notification_color_led)) + .build(); + } + } - public static Notification createMissedCallNotification(Context context, String title, String text, PendingIntent intent) { - return new Notification.Builder(context, context.getString(R.string.notification_channel_id)) - .setContentTitle(title) - .setContentText(text) - .setSmallIcon(R.drawable.call_status_missed) - .setAutoCancel(true) - .setContentIntent(intent) - .setDefaults(Notification.DEFAULT_SOUND - | Notification.DEFAULT_VIBRATE) - .setCategory(Notification.CATEGORY_EVENT) - .setVisibility(Notification.VISIBILITY_PRIVATE) - .setPriority(Notification.PRIORITY_HIGH) - .setWhen(System.currentTimeMillis()) - .setShowWhen(true) - .setColor(context.getColor(R.color.notification_color_led)) - .build(); - } + public static Notification createMissedCallNotification( + Context context, String title, String text, PendingIntent intent) { + return new Notification.Builder( + context, context.getString(R.string.notification_channel_id)) + .setContentTitle(title) + .setContentText(text) + .setSmallIcon(R.drawable.call_status_missed) + .setAutoCancel(true) + .setContentIntent(intent) + .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE) + .setCategory(Notification.CATEGORY_EVENT) + .setVisibility(Notification.VISIBILITY_PRIVATE) + .setPriority(Notification.PRIORITY_HIGH) + .setWhen(System.currentTimeMillis()) + .setShowWhen(true) + .setColor(context.getColor(R.color.notification_color_led)) + .build(); + } - public static Notification createSimpleNotification(Context context, String title, String text, PendingIntent intent) { - return new Notification.Builder(context, context.getString(R.string.notification_channel_id)) - .setContentTitle(title) - .setContentText(text) - .setSmallIcon(R.drawable.linphone_logo) - .setAutoCancel(true) - .setContentIntent(intent) - .setDefaults(Notification.DEFAULT_SOUND - | Notification.DEFAULT_VIBRATE) - .setCategory(Notification.CATEGORY_MESSAGE) - .setVisibility(Notification.VISIBILITY_PRIVATE) - .setPriority(Notification.PRIORITY_HIGH) - .setWhen(System.currentTimeMillis()) - .setShowWhen(true) - .setColorized(true) - .setColor(context.getColor(R.color.notification_color_led)) - .build(); - } + public static Notification createSimpleNotification( + Context context, String title, String text, PendingIntent intent) { + return new Notification.Builder( + context, context.getString(R.string.notification_channel_id)) + .setContentTitle(title) + .setContentText(text) + .setSmallIcon(R.drawable.linphone_logo) + .setAutoCancel(true) + .setContentIntent(intent) + .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE) + .setCategory(Notification.CATEGORY_MESSAGE) + .setVisibility(Notification.VISIBILITY_PRIVATE) + .setPriority(Notification.PRIORITY_HIGH) + .setWhen(System.currentTimeMillis()) + .setShowWhen(true) + .setColorized(true) + .setColor(context.getColor(R.color.notification_color_led)) + .build(); + } - public static void startService(Context context, Intent intent) { - context.startForegroundService(intent); - } + public static void startService(Context context, Intent intent) { + context.startForegroundService(intent); + } - public static void setFragmentTransactionReorderingAllowed(FragmentTransaction transaction, boolean allowed) { - transaction.setReorderingAllowed(allowed); - } + public static void setFragmentTransactionReorderingAllowed( + FragmentTransaction transaction, boolean allowed) { + transaction.setReorderingAllowed(allowed); + } } diff --git a/app/src/main/java/org/linphone/compatibility/Compatibility.java b/app/src/main/java/org/linphone/compatibility/Compatibility.java index 484fded83..d8c591bd6 100644 --- a/app/src/main/java/org/linphone/compatibility/Compatibility.java +++ b/app/src/main/java/org/linphone/compatibility/Compatibility.java @@ -27,7 +27,6 @@ import android.graphics.Bitmap; import android.os.Build; import android.provider.Settings; import android.widget.TextView; - import org.linphone.mediastream.Version; import org.linphone.notifications.Notifiable; @@ -47,29 +46,39 @@ public class Compatibility { } } - public static Notification createSimpleNotification(Context context, String title, String text, PendingIntent intent) { + public static Notification createSimpleNotification( + Context context, String title, String text, PendingIntent intent) { if (Version.sdkAboveOrEqual(Version.API26_O_80)) { return ApiTwentySixPlus.createSimpleNotification(context, title, text, intent); } return ApiTwentyOnePlus.createSimpleNotification(context, title, text, intent); } - public static Notification createMissedCallNotification(Context context, String title, String text, PendingIntent intent) { + public static Notification createMissedCallNotification( + Context context, String title, String text, PendingIntent intent) { if (Version.sdkAboveOrEqual(Version.API26_O_80)) { return ApiTwentySixPlus.createMissedCallNotification(context, title, text, intent); } return ApiTwentyOnePlus.createMissedCallNotification(context, title, text, intent); } - public static Notification createMessageNotification(Context context, Notifiable notif, String msgSender, String msg, Bitmap contactIcon, PendingIntent intent) { + public static Notification createMessageNotification( + Context context, + Notifiable notif, + String msgSender, + String msg, + Bitmap contactIcon, + PendingIntent intent) { if (Version.sdkAboveOrEqual(28)) { - return ApiTwentyEightPlus.createMessageNotification(context, notif, contactIcon, intent); + return ApiTwentyEightPlus.createMessageNotification( + context, notif, contactIcon, intent); } else if (Version.sdkAboveOrEqual(Version.API26_O_80)) { return ApiTwentySixPlus.createMessageNotification(context, notif, contactIcon, intent); } else if (Version.sdkAboveOrEqual(Version.API24_NOUGAT_70)) { return ApiTwentyFourPlus.createMessageNotification(context, notif, contactIcon, intent); } - return ApiTwentyOnePlus.createMessageNotification(context, notif.getMessages().size(), msgSender, msg, contactIcon, intent); + return ApiTwentyOnePlus.createMessageNotification( + context, notif.getMessages().size(), msgSender, msg, contactIcon, intent); } public static Notification createRepliedNotification(Context context, String reply) { @@ -81,20 +90,73 @@ public class Compatibility { return null; } - public static Notification createInCallNotification(Context context, int callId, boolean showAnswerAction, String title, String msg, int iconID, Bitmap contactIcon, String contactName, PendingIntent intent) { + public static Notification createInCallNotification( + Context context, + int callId, + boolean showAnswerAction, + String title, + String msg, + int iconID, + Bitmap contactIcon, + String contactName, + PendingIntent intent) { if (Version.sdkAboveOrEqual(Version.API26_O_80)) { - return ApiTwentySixPlus.createInCallNotification(context, callId, showAnswerAction, msg, iconID, contactIcon, contactName, intent); + return ApiTwentySixPlus.createInCallNotification( + context, + callId, + showAnswerAction, + msg, + iconID, + contactIcon, + contactName, + intent); } else if (Version.sdkAboveOrEqual(Version.API24_NOUGAT_70)) { - return ApiTwentyFourPlus.createInCallNotification(context, callId, showAnswerAction, msg, iconID, contactIcon, contactName, intent); + return ApiTwentyFourPlus.createInCallNotification( + context, + callId, + showAnswerAction, + msg, + iconID, + contactIcon, + contactName, + intent); } - return ApiTwentyOnePlus.createInCallNotification(context, title, msg, iconID, contactIcon, contactName, intent); + return ApiTwentyOnePlus.createInCallNotification( + context, title, msg, iconID, contactIcon, contactName, intent); } - public static Notification createNotification(Context context, String title, String message, int icon, int iconLevel, Bitmap largeIcon, PendingIntent intent, boolean isOngoingEvent, int priority) { + public static Notification createNotification( + Context context, + String title, + String message, + int icon, + int iconLevel, + Bitmap largeIcon, + PendingIntent intent, + boolean isOngoingEvent, + int priority) { if (Version.sdkAboveOrEqual(Version.API26_O_80)) { - return ApiTwentySixPlus.createNotification(context, title, message, icon, iconLevel, largeIcon, intent, isOngoingEvent, priority); + return ApiTwentySixPlus.createNotification( + context, + title, + message, + icon, + iconLevel, + largeIcon, + intent, + isOngoingEvent, + priority); } - return ApiTwentyOnePlus.createNotification(context, title, message, icon, iconLevel, largeIcon, intent, isOngoingEvent, priority); + return ApiTwentyOnePlus.createNotification( + context, + title, + message, + icon, + iconLevel, + largeIcon, + intent, + isOngoingEvent, + priority); } public static boolean canDrawOverlays(Context context) { @@ -120,7 +182,8 @@ public class Compatibility { } } - public static void setFragmentTransactionReorderingAllowed(FragmentTransaction transaction, boolean allowed) { + public static void setFragmentTransactionReorderingAllowed( + FragmentTransaction transaction, boolean allowed) { if (Version.sdkAboveOrEqual(Version.API26_O_80)) { ApiTwentySixPlus.setFragmentTransactionReorderingAllowed(transaction, allowed); } diff --git a/app/src/main/java/org/linphone/compatibility/CompatibilityScaleGestureDetector.java b/app/src/main/java/org/linphone/compatibility/CompatibilityScaleGestureDetector.java index d24e4d110..df1a4a309 100644 --- a/app/src/main/java/org/linphone/compatibility/CompatibilityScaleGestureDetector.java +++ b/app/src/main/java/org/linphone/compatibility/CompatibilityScaleGestureDetector.java @@ -25,7 +25,8 @@ import android.view.MotionEvent; import android.view.ScaleGestureDetector; @TargetApi(8) -public class CompatibilityScaleGestureDetector extends ScaleGestureDetector.SimpleOnScaleGestureListener { +public class CompatibilityScaleGestureDetector + extends ScaleGestureDetector.SimpleOnScaleGestureListener { private ScaleGestureDetector detector; private CompatibilityScaleGestureListener listener; @@ -58,4 +59,4 @@ public class CompatibilityScaleGestureDetector extends ScaleGestureDetector.Simp listener = null; detector = null; } -} \ No newline at end of file +} diff --git a/app/src/main/java/org/linphone/compatibility/CompatibilityScaleGestureListener.java b/app/src/main/java/org/linphone/compatibility/CompatibilityScaleGestureListener.java index bd4393385..f9f76b85e 100644 --- a/app/src/main/java/org/linphone/compatibility/CompatibilityScaleGestureListener.java +++ b/app/src/main/java/org/linphone/compatibility/CompatibilityScaleGestureListener.java @@ -21,4 +21,4 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. public interface CompatibilityScaleGestureListener { public boolean onScale(CompatibilityScaleGestureDetector detector); -} \ No newline at end of file +} diff --git a/app/src/main/java/org/linphone/contacts/ContactAddress.java b/app/src/main/java/org/linphone/contacts/ContactAddress.java index 78a6d2e5e..3797d277f 100644 --- a/app/src/main/java/org/linphone/contacts/ContactAddress.java +++ b/app/src/main/java/org/linphone/contacts/ContactAddress.java @@ -20,13 +20,11 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import android.view.View; - +import java.io.Serializable; import org.linphone.core.Address; import org.linphone.core.Factory; import org.linphone.core.SearchResult; -import java.io.Serializable; - public class ContactAddress implements Serializable { private LinphoneContact contact; private SearchResult result; @@ -37,6 +35,15 @@ public class ContactAddress implements Serializable { private boolean isAdmin = false; private transient View view; + public ContactAddress(LinphoneContact c, String a, String pn, boolean isLC) { + init(c, a, pn, isLC); + } + + public ContactAddress(LinphoneContact c, String a, String pn, boolean isLC, boolean isAdmin) { + init(c, a, pn, isLC); + this.isAdmin = isAdmin; + } + public boolean isAdmin() { return isAdmin; } @@ -49,14 +56,18 @@ public class ContactAddress implements Serializable { return isSelect; } - public void setView(View v) { - view = v; + public void setSelect(boolean select) { + isSelect = select; } public View getView() { return view; } + public void setView(View v) { + view = v; + } + public LinphoneContact getContact() { return contact; } @@ -76,7 +87,9 @@ public class ContactAddress implements Serializable { } public Address getAddress() { - String presence = contact.getPresenceModelForUriOrTel((phoneNumber != null && !phoneNumber.isEmpty()) ? phoneNumber : address); + String presence = + contact.getPresenceModelForUriOrTel( + (phoneNumber != null && !phoneNumber.isEmpty()) ? phoneNumber : address); Address addr = Factory.instance().createAddress(presence != null ? presence : address); // Remove the user=phone URI param if existing, it will break everything otherwise if (addr.hasUriParam("user")) { @@ -109,10 +122,6 @@ public class ContactAddress implements Serializable { return phoneNumber; } - public void setSelect(boolean select) { - isSelect = select; - } - public boolean isLinphoneContact() { return isLinphoneContact; } @@ -124,22 +133,13 @@ public class ContactAddress implements Serializable { isLinphoneContact = isLC; } - public ContactAddress(LinphoneContact c, String a, String pn, boolean isLC) { - init(c, a, pn, isLC); - } - - public ContactAddress(LinphoneContact c, String a, String pn, boolean isLC, boolean isAdmin) { - init(c, a, pn, isLC); - this.isAdmin = isAdmin; - } - @Override public boolean equals(Object other) { if (other == null) return false; if (other == this) return true; if (!(other instanceof ContactAddress)) return false; - if (((ContactAddress) other).getAddressAsDisplayableString() == this.getAddressAsDisplayableString()) - return true; + if (((ContactAddress) other).getAddressAsDisplayableString() + == this.getAddressAsDisplayableString()) return true; return false; } } diff --git a/app/src/main/java/org/linphone/contacts/ContactDetailsFragment.java b/app/src/main/java/org/linphone/contacts/ContactDetailsFragment.java index 02e1c9a86..e59622676 100644 --- a/app/src/main/java/org/linphone/contacts/ContactDetailsFragment.java +++ b/app/src/main/java/org/linphone/contacts/ContactDetailsFragment.java @@ -25,7 +25,6 @@ import android.app.Fragment; import android.content.Intent; import android.net.Uri; import android.os.Bundle; -import android.provider.ContactsContract; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; @@ -35,13 +34,9 @@ import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TableLayout; import android.widget.TextView; - -import org.linphone.LinphoneManager; -import org.linphone.settings.LinphonePreferences; -import org.linphone.utils.ImageUtils; -import org.linphone.utils.LinphoneUtils; -import org.linphone.R; import org.linphone.LinphoneActivity; +import org.linphone.LinphoneManager; +import org.linphone.R; import org.linphone.core.Address; import org.linphone.core.ChatRoom; import org.linphone.core.ChatRoomListenerStub; @@ -52,6 +47,9 @@ import org.linphone.core.PresenceModel; import org.linphone.core.ProxyConfig; import org.linphone.fragments.FragmentsAvailable; import org.linphone.mediastream.Log; +import org.linphone.settings.LinphonePreferences; +import org.linphone.utils.ImageUtils; +import org.linphone.utils.LinphoneUtils; public class ContactDetailsFragment extends Fragment implements OnClickListener { private LinphoneContact contact; @@ -64,49 +62,68 @@ public class ContactDetailsFragment extends Fragment implements OnClickListener private ChatRoom mChatRoom; private ChatRoomListenerStub mChatRoomCreationListener; - private OnClickListener dialListener = new OnClickListener() { - @Override - public void onClick(View v) { - if (LinphoneActivity.isInstanciated()) { - String tag = (String) v.getTag(); - LinphoneActivity.instance().setAddresGoToDialerAndCall(tag, contact.getFullName(), contact.getPhotoUri()); - } - } - }; + private OnClickListener dialListener = + new OnClickListener() { + @Override + public void onClick(View v) { + if (LinphoneActivity.isInstanciated()) { + String tag = (String) v.getTag(); + LinphoneActivity.instance() + .setAddresGoToDialerAndCall( + tag, contact.getFullName(), contact.getPhotoUri()); + } + } + }; - private OnClickListener chatListener = new OnClickListener() { - @Override - public void onClick(View v) { - if (LinphoneActivity.isInstanciated()) { - String tag = (String) v.getTag(); - Core lc = LinphoneManager.getLc(); - Address participant = Factory.instance().createAddress(tag); - ProxyConfig defaultProxyConfig = lc.getDefaultProxyConfig(); - boolean isSecured = v.getId() == R.id.contact_chat_secured; + private OnClickListener chatListener = + new OnClickListener() { + @Override + public void onClick(View v) { + if (LinphoneActivity.isInstanciated()) { + String tag = (String) v.getTag(); + Core lc = LinphoneManager.getLc(); + Address participant = Factory.instance().createAddress(tag); + ProxyConfig defaultProxyConfig = lc.getDefaultProxyConfig(); + boolean isSecured = v.getId() == R.id.contact_chat_secured; - if (defaultProxyConfig != null) { - ChatRoom room = lc.findOneToOneChatRoom(defaultProxyConfig.getContact(), participant, isSecured); - if (room != null) { - LinphoneActivity.instance().goToChat(room.getPeerAddress().asStringUriOnly(), null); - } else { - if (defaultProxyConfig.getConferenceFactoryUri() != null && (isSecured || !LinphonePreferences.instance().useBasicChatRoomFor1To1())) { - mWaitLayout.setVisibility(View.VISIBLE); - mChatRoom = lc.createClientGroupChatRoom(getString(R.string.dummy_group_chat_subject), !isSecured, isSecured); - mChatRoom.addListener(mChatRoomCreationListener); - Address participants[] = new Address[1]; - participants[0] = participant; - mChatRoom.addParticipants(participants); - } else { - room = lc.getChatRoom(participant); - LinphoneActivity.instance().goToChat(room.getPeerAddress().asStringUriOnly(), null); + if (defaultProxyConfig != null) { + ChatRoom room = + lc.findOneToOneChatRoom( + defaultProxyConfig.getContact(), + participant, + isSecured); + if (room != null) { + LinphoneActivity.instance() + .goToChat(room.getPeerAddress().asStringUriOnly(), null); + } else { + if (defaultProxyConfig.getConferenceFactoryUri() != null + && (isSecured + || !LinphonePreferences.instance() + .useBasicChatRoomFor1To1())) { + mWaitLayout.setVisibility(View.VISIBLE); + mChatRoom = + lc.createClientGroupChatRoom( + getString(R.string.dummy_group_chat_subject), + !isSecured, + isSecured); + mChatRoom.addListener(mChatRoomCreationListener); + Address participants[] = new Address[1]; + participants[0] = participant; + mChatRoom.addParticipants(participants); + } else { + room = lc.getChatRoom(participant); + LinphoneActivity.instance() + .goToChat( + room.getPeerAddress().asStringUriOnly(), null); + } + } } } } - } - } - }; + }; - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { contact = (LinphoneContact) getArguments().getSerializable("Contact"); this.inflater = inflater; @@ -141,19 +158,24 @@ public class ContactDetailsFragment extends Fragment implements OnClickListener back.setOnClickListener(this); } - mChatRoomCreationListener = new ChatRoomListenerStub() { - @Override - public void onStateChanged(ChatRoom cr, ChatRoom.State newState) { - if (newState == ChatRoom.State.Created) { - mWaitLayout.setVisibility(View.GONE); - LinphoneActivity.instance().goToChat(cr.getPeerAddress().asStringUriOnly(), null); - } else if (newState == ChatRoom.State.CreationFailed) { - mWaitLayout.setVisibility(View.GONE); - LinphoneActivity.instance().displayChatRoomError(); - Log.e("Group chat room for address " + cr.getPeerAddress() + " has failed !"); - } - } - }; + mChatRoomCreationListener = + new ChatRoomListenerStub() { + @Override + public void onStateChanged(ChatRoom cr, ChatRoom.State newState) { + if (newState == ChatRoom.State.Created) { + mWaitLayout.setVisibility(View.GONE); + LinphoneActivity.instance() + .goToChat(cr.getPeerAddress().asStringUriOnly(), null); + } else if (newState == ChatRoom.State.CreationFailed) { + mWaitLayout.setVisibility(View.GONE); + LinphoneActivity.instance().displayChatRoomError(); + Log.e( + "Group chat room for address " + + cr.getPeerAddress() + + " has failed !"); + } + } + }; return view; } @@ -175,7 +197,11 @@ public class ContactDetailsFragment extends Fragment implements OnClickListener private void displayContact(LayoutInflater inflater, View view) { ImageView contactPicture = view.findViewById(R.id.contact_picture); if (contact.hasPhoto()) { - ImageUtils.setImagePictureFromUri(getActivity(), contactPicture, contact.getPhotoUri(), contact.getThumbnailUri()); + ImageUtils.setImagePictureFromUri( + getActivity(), + contactPicture, + contact.getPhotoUri(), + contact.getThumbnailUri()); } else { contactPicture.setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap()); } @@ -191,7 +217,8 @@ public class ContactDetailsFragment extends Fragment implements OnClickListener View v = inflater.inflate(R.layout.contact_control_row, null); String value = noa.getValue(); - String displayednumberOrAddress = LinphoneUtils.getDisplayableUsernameFromAddress(value); + String displayednumberOrAddress = + LinphoneUtils.getDisplayableUsernameFromAddress(value); TextView label = v.findViewById(R.id.address_label); if (noa.isSIPAddress()) { @@ -206,7 +233,6 @@ public class ContactDetailsFragment extends Fragment implements OnClickListener tv.setText(displayednumberOrAddress); tv.setSelected(true); - ProxyConfig lpc = LinphoneManager.getLc().getDefaultProxyConfig(); if (lpc != null) { String username = lpc.normalizePhoneNumber(displayednumberOrAddress); @@ -221,27 +247,32 @@ public class ContactDetailsFragment extends Fragment implements OnClickListener if (pm != null && pm.getBasicStatus().equals(PresenceBasicStatus.Open)) { v.findViewById(R.id.friendLinphone).setVisibility(View.VISIBLE); } else { - if (getResources().getBoolean(R.bool.hide_numbers_and_addresses_without_presence)) { + if (getResources() + .getBoolean(R.bool.hide_numbers_and_addresses_without_presence)) { skip = true; } } } v.findViewById(R.id.inviteFriend).setVisibility(View.GONE); - if (!noa.isSIPAddress() && v.findViewById(R.id.friendLinphone).getVisibility() == View.GONE) { + if (!noa.isSIPAddress() + && v.findViewById(R.id.friendLinphone).getVisibility() == View.GONE) { v.findViewById(R.id.inviteFriend).setVisibility(View.VISIBLE); v.findViewById(R.id.inviteFriend).setTag(noa.getNormalizedPhone()); - v.findViewById(R.id.inviteFriend).setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - String number = (String)v.getTag(); - Intent smsIntent = new Intent(Intent.ACTION_SENDTO); - smsIntent.putExtra("address", number); - smsIntent.setData(Uri.parse("smsto:" + number)); - smsIntent.putExtra("sms_body", getString(R.string.invite_friend_text)); - startActivity(smsIntent); - } - }); + v.findViewById(R.id.inviteFriend) + .setOnClickListener( + new OnClickListener() { + @Override + public void onClick(View v) { + String number = (String) v.getTag(); + Intent smsIntent = new Intent(Intent.ACTION_SENDTO); + smsIntent.putExtra("address", number); + smsIntent.setData(Uri.parse("smsto:" + number)); + smsIntent.putExtra( + "sms_body", getString(R.string.invite_friend_text)); + startActivity(smsIntent); + } + }); } String contactAddress = contact.getPresenceModelForUriOrTel(noa.getValue()); @@ -266,8 +297,8 @@ public class ContactDetailsFragment extends Fragment implements OnClickListener v.findViewById(R.id.contact_chat_secured).setTag(value); } - - if (v.findViewById(R.id.friendLinphone).getVisibility() == View.VISIBLE /* TODO Does contact have LIME capability ?*/ + if (v.findViewById(R.id.friendLinphone).getVisibility() + == View.VISIBLE /* TODO Does contact have LIME capability ?*/ && lpc.getConferenceFactoryUri() != null) { v.findViewById(R.id.contact_chat_secured).setVisibility(View.VISIBLE); } else { @@ -303,26 +334,28 @@ public class ContactDetailsFragment extends Fragment implements OnClickListener if (id == R.id.editContact) { ContactsManager.getInstance().editContact(getActivity(), contact, null); } else if (id == R.id.deleteContact) { - final Dialog dialog = LinphoneActivity.instance().displayDialog(getString(R.string.delete_text)); + final Dialog dialog = + LinphoneActivity.instance().displayDialog(getString(R.string.delete_text)); Button delete = dialog.findViewById(R.id.dialog_delete_button); Button cancel = dialog.findViewById(R.id.dialog_cancel_button); - delete.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View view) { - contact.delete(); - LinphoneActivity.instance().displayContacts(false); - dialog.dismiss(); - } - }); + delete.setOnClickListener( + new OnClickListener() { + @Override + public void onClick(View view) { + contact.delete(); + LinphoneActivity.instance().displayContacts(false); + dialog.dismiss(); + } + }); - cancel.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View view) { - dialog.dismiss(); - - } - }); + cancel.setOnClickListener( + new OnClickListener() { + @Override + public void onClick(View view) { + dialog.dismiss(); + } + }); dialog.show(); } else if (id == R.id.back) { getFragmentManager().popBackStackImmediate(); diff --git a/app/src/main/java/org/linphone/contacts/ContactEditorFragment.java b/app/src/main/java/org/linphone/contacts/ContactEditorFragment.java index 3f0fc2d1a..768b73864 100644 --- a/app/src/main/java/org/linphone/contacts/ContactEditorFragment.java +++ b/app/src/main/java/org/linphone/contacts/ContactEditorFragment.java @@ -1,23 +1,23 @@ package org.linphone.contacts; /* - ContactEditorFragment.java - Copyright (C) 2017 Belledonne Communications, Grenoble, France +ContactEditorFragment.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 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. +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. - */ +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.annotation.SuppressLint; import android.app.Activity; @@ -46,34 +46,30 @@ import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; - -import org.linphone.LinphoneManager; -import org.linphone.utils.FileUtils; -import org.linphone.utils.ImageUtils; -import org.linphone.utils.LinphoneUtils; -import org.linphone.R; -import org.linphone.LinphoneActivity; -import org.linphone.mediastream.Log; -import org.linphone.mediastream.Version; - import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.List; +import org.linphone.LinphoneActivity; +import org.linphone.LinphoneManager; +import org.linphone.R; +import org.linphone.mediastream.Log; +import org.linphone.mediastream.Version; +import org.linphone.utils.FileUtils; +import org.linphone.utils.ImageUtils; +import org.linphone.utils.LinphoneUtils; public class ContactEditorFragment extends Fragment { + private static final int ADD_PHOTO = 1337; + private static final int PHOTO_SIZE = 128; private View view; private ImageView cancel, deleteContact, ok; private ImageView addNumber, addSipAddress, contactPicture; private LinearLayout phoneNumbersSection, sipAddressesSection; private EditText firstName, lastName, organization; private LayoutInflater inflater; - - private static final int ADD_PHOTO = 1337; - private static final int PHOTO_SIZE = 128; - private boolean isNewContact; private LinphoneContact contact; private List numbersAndAddresses; @@ -83,7 +79,8 @@ public class ContactEditorFragment extends Fragment { private Uri pickedPhotoForContactUri; private byte[] photoToAdd; - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { this.inflater = inflater; contact = null; @@ -111,8 +108,9 @@ public class ContactEditorFragment extends Fragment { view = inflater.inflate(R.layout.contact_edit, container, false); phoneNumbersSection = view.findViewById(R.id.phone_numbers); - if (getResources().getBoolean(R.bool.hide_phone_numbers_in_editor) || !ContactsManager.getInstance().hasContactsAccess()) { - //Currently linphone friends don't support phone numbers, so hide them + if (getResources().getBoolean(R.bool.hide_phone_numbers_in_editor) + || !ContactsManager.getInstance().hasContactsAccess()) { + // Currently linphone friends don't support phone numbers, so hide them phoneNumbersSection.setVisibility(View.GONE); } @@ -124,97 +122,106 @@ public class ContactEditorFragment extends Fragment { deleteContact = view.findViewById(R.id.delete_contact); cancel = view.findViewById(R.id.cancel); - cancel.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - getFragmentManager().popBackStackImmediate(); - } - }); + cancel.setOnClickListener( + new OnClickListener() { + @Override + public void onClick(View v) { + getFragmentManager().popBackStackImmediate(); + } + }); ok = view.findViewById(R.id.ok); - ok.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - if (isNewContact) { - boolean areAllFielsEmpty = true; - for (LinphoneNumberOrAddress nounoa : numbersAndAddresses) { - if (nounoa.getValue() != null && !nounoa.getValue().equals("")) { - areAllFielsEmpty = false; - break; + ok.setOnClickListener( + new OnClickListener() { + @Override + public void onClick(View v) { + if (isNewContact) { + boolean areAllFielsEmpty = true; + for (LinphoneNumberOrAddress nounoa : numbersAndAddresses) { + if (nounoa.getValue() != null && !nounoa.getValue().equals("")) { + areAllFielsEmpty = false; + break; + } + } + if (areAllFielsEmpty) { + getFragmentManager().popBackStackImmediate(); + return; + } + contact = LinphoneContact.createContact(); } - } - if (areAllFielsEmpty) { + contact.setFirstNameAndLastName( + firstName.getText().toString(), + lastName.getText().toString(), + true); + if (photoToAdd != null) { + contact.setPhoto(photoToAdd); + } + for (LinphoneNumberOrAddress noa : numbersAndAddresses) { + if (noa.isSIPAddress() && noa.getValue() != null) { + noa.setValue( + LinphoneUtils.getFullAddressFromUsername(noa.getValue())); + } + contact.addOrUpdateNumberOrAddress(noa); + } + contact.setOrganization(organization.getText().toString(), true); + contact.save(); getFragmentManager().popBackStackImmediate(); - return; } - contact = LinphoneContact.createContact(); - } - contact.setFirstNameAndLastName(firstName.getText().toString(), lastName.getText().toString(), true); - if (photoToAdd != null) { - contact.setPhoto(photoToAdd); - } - for (LinphoneNumberOrAddress noa : numbersAndAddresses) { - if (noa.isSIPAddress() && noa.getValue() != null) { - noa.setValue(LinphoneUtils.getFullAddressFromUsername(noa.getValue())); - } - contact.addOrUpdateNumberOrAddress(noa); - } - contact.setOrganization(organization.getText().toString(), true); - contact.save(); - getFragmentManager().popBackStackImmediate(); - } - }); + }); lastName = view.findViewById(R.id.contactLastName); // Hack to display keyboard when touching focused edittext on Nexus One if (Version.sdkStrictlyBelow(Version.API11_HONEYCOMB_30)) { - lastName.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - InputMethodManager imm = (InputMethodManager) LinphoneActivity.instance().getSystemService(Context.INPUT_METHOD_SERVICE); - imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); - } - }); + lastName.setOnClickListener( + new OnClickListener() { + @Override + public void onClick(View v) { + InputMethodManager imm = + (InputMethodManager) + LinphoneActivity.instance() + .getSystemService(Context.INPUT_METHOD_SERVICE); + imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); + } + }); } - lastName.addTextChangedListener(new TextWatcher() { - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - if (lastName.getText().length() > 0 || firstName.getText().length() > 0) { - ok.setEnabled(true); - } else { - ok.setEnabled(false); - } - } + lastName.addTextChangedListener( + new TextWatcher() { + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + if (lastName.getText().length() > 0 || firstName.getText().length() > 0) { + ok.setEnabled(true); + } else { + ok.setEnabled(false); + } + } - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - } + @Override + public void beforeTextChanged( + CharSequence s, int start, int count, int after) {} - @Override - public void afterTextChanged(Editable s) { - } - }); + @Override + public void afterTextChanged(Editable s) {} + }); firstName = view.findViewById(R.id.contactFirstName); - firstName.addTextChangedListener(new TextWatcher() { - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - if (firstName.getText().length() > 0 || lastName.getText().length() > 0) { - ok.setEnabled(true); - } else { - ok.setEnabled(false); - } - } + firstName.addTextChangedListener( + new TextWatcher() { + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + if (firstName.getText().length() > 0 || lastName.getText().length() > 0) { + ok.setEnabled(true); + } else { + ok.setEnabled(false); + } + } - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - } - - @Override - public void afterTextChanged(Editable s) { - } - }); + @Override + public void beforeTextChanged( + CharSequence s, int start, int count, int after) {} + @Override + public void afterTextChanged(Editable s) {} + }); organization = view.findViewById(R.id.contactOrganization); boolean isOrgVisible = getResources().getBoolean(R.bool.display_contact_organization); @@ -238,50 +245,59 @@ public class ContactEditorFragment extends Fragment { firstName.setText(""); } - deleteContact.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - final Dialog dialog = LinphoneActivity.instance().displayDialog(getString(R.string.delete_text)); - Button delete = dialog.findViewById(R.id.dialog_delete_button); - Button cancel = dialog.findViewById(R.id.dialog_cancel_button); - - delete.setOnClickListener(new OnClickListener() { + deleteContact.setOnClickListener( + new OnClickListener() { @Override - public void onClick(View view) { - contact.delete(); - LinphoneActivity.instance().displayContacts(false); - dialog.dismiss(); + public void onClick(View v) { + final Dialog dialog = + LinphoneActivity.instance() + .displayDialog(getString(R.string.delete_text)); + Button delete = dialog.findViewById(R.id.dialog_delete_button); + Button cancel = dialog.findViewById(R.id.dialog_cancel_button); + + delete.setOnClickListener( + new OnClickListener() { + @Override + public void onClick(View view) { + contact.delete(); + LinphoneActivity.instance().displayContacts(false); + dialog.dismiss(); + } + }); + + cancel.setOnClickListener( + new OnClickListener() { + @Override + public void onClick(View view) { + dialog.dismiss(); + } + }); + dialog.show(); } }); - - cancel.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View view) { - dialog.dismiss(); - - } - }); - dialog.show(); - } - }); } else { deleteContact.setVisibility(View.INVISIBLE); } contactPicture = view.findViewById(R.id.contact_picture); if (contact != null) { - ImageUtils.setImagePictureFromUri(getActivity(), contactPicture, contact.getPhotoUri(), contact.getThumbnailUri()); + ImageUtils.setImagePictureFromUri( + getActivity(), + contactPicture, + contact.getPhotoUri(), + contact.getThumbnailUri()); } else { contactPicture.setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap()); } - contactPicture.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View view) { - pickImage(); - LinphoneActivity.instance().checkAndRequestCameraPermission(); - } - }); + contactPicture.setOnClickListener( + new OnClickListener() { + @Override + public void onClick(View view) { + pickImage(); + LinphoneActivity.instance().checkAndRequestCameraPermission(); + } + }); numbersAndAddresses = new ArrayList<>(); sipAddresses = initSipAddressFields(contact); @@ -291,23 +307,25 @@ public class ContactEditorFragment extends Fragment { if (getResources().getBoolean(R.bool.allow_only_one_sip_address)) { addSipAddress.setVisibility(View.GONE); } - addSipAddress.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View view) { - addEmptyRowToAllowNewNumberOrAddress(sipAddresses, true); - } - }); + addSipAddress.setOnClickListener( + new OnClickListener() { + @Override + public void onClick(View view) { + addEmptyRowToAllowNewNumberOrAddress(sipAddresses, true); + } + }); addNumber = view.findViewById(R.id.add_number_field); if (getResources().getBoolean(R.bool.allow_only_one_phone_number)) { addNumber.setVisibility(View.GONE); } - addNumber.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View view) { - addEmptyRowToAllowNewNumberOrAddress(numbers, false); - } - }); + addNumber.setOnClickListener( + new OnClickListener() { + @Override + public void onClick(View view) { + addEmptyRowToAllowNewNumberOrAddress(numbers, false); + } + }); lastName.requestFocus(); @@ -318,17 +336,21 @@ public class ContactEditorFragment extends Fragment { public void onResume() { super.onResume(); - if (LinphoneActivity.isInstanciated()) { - } + if (LinphoneActivity.isInstanciated()) {} // Force hide keyboard - getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); + getActivity() + .getWindow() + .setSoftInputMode( + WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN + | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); } @Override public void onPause() { // Force hide keyboard - InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); + InputMethodManager imm = + (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); View view = getActivity().getCurrentFocus(); if (imm != null && view != null) { imm.hideSoftInputFromWindow(view.getWindowToken(), 0); @@ -341,7 +363,10 @@ public class ContactEditorFragment extends Fragment { pickedPhotoForContactUri = null; final List cameraIntents = new ArrayList<>(); final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); - File file = new File(FileUtils.getStorageDirectory(LinphoneActivity.instance()), getString(R.string.temp_photo_name)); + File file = + new File( + FileUtils.getStorageDirectory(LinphoneActivity.instance()), + getString(R.string.temp_photo_name)); pickedPhotoForContactUri = Uri.fromFile(file); captureIntent.putExtra("outputX", PHOTO_SIZE); captureIntent.putExtra("outputY", PHOTO_SIZE); @@ -356,8 +381,10 @@ public class ContactEditorFragment extends Fragment { galleryIntent.setType("image/*"); galleryIntent.setAction(Intent.ACTION_GET_CONTENT); - final Intent chooserIntent = Intent.createChooser(galleryIntent, getString(R.string.image_picker_title)); - chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{})); + final Intent chooserIntent = + Intent.createChooser(galleryIntent, getString(R.string.image_picker_title)); + chooserIntent.putExtra( + Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[] {})); startActivityForResult(chooserIntent, ADD_PHOTO); } @@ -371,8 +398,12 @@ public class ContactEditorFragment extends Fragment { } else if (data != null && data.getData() != null) { Uri selectedImageUri = data.getData(); try { - Bitmap selectedImage = MediaStore.Images.Media.getBitmap(LinphoneManager.getInstance().getContext().getContentResolver(), selectedImageUri); - selectedImage = Bitmap.createScaledBitmap(selectedImage, PHOTO_SIZE, PHOTO_SIZE, false); + Bitmap selectedImage = + MediaStore.Images.Media.getBitmap( + LinphoneManager.getInstance().getContext().getContentResolver(), + selectedImageUri); + selectedImage = + Bitmap.createScaledBitmap(selectedImage, PHOTO_SIZE, PHOTO_SIZE, false); editContactPicture(null, selectedImage); } catch (IOException e) { Log.e(e); @@ -381,7 +412,10 @@ public class ContactEditorFragment extends Fragment { String filePath = pickedPhotoForContactUri.getPath(); editContactPicture(filePath, null); } else { - File file = new File(FileUtils.getStorageDirectory(LinphoneActivity.instance()), getString(R.string.temp_photo_name)); + File file = + new File( + FileUtils.getStorageDirectory(LinphoneActivity.instance()), + getString(R.string.temp_photo_name)); if (file.exists()) { pickedPhotoForContactUri = Uri.fromFile(file); String filePath = pickedPhotoForContactUri.getPath(); @@ -415,7 +449,15 @@ public class ContactEditorFragment extends Fragment { private int getThumbnailSize() { int value = -1; - Cursor c = LinphoneActivity.instance().getContentResolver().query(DisplayPhoto.CONTENT_MAX_DIMENSIONS_URI, new String[]{DisplayPhoto.THUMBNAIL_MAX_DIM}, null, null, null); + Cursor c = + LinphoneActivity.instance() + .getContentResolver() + .query( + DisplayPhoto.CONTENT_MAX_DIMENSIONS_URI, + new String[] {DisplayPhoto.THUMBNAIL_MAX_DIM}, + null, + null, + null); try { c.moveToFirst(); value = c.getInt(0); @@ -433,25 +475,24 @@ public class ContactEditorFragment extends Fragment { for (LinphoneNumberOrAddress numberOrAddress : contact.getNumbersOrAddresses()) { if (!numberOrAddress.isSIPAddress()) { View view = displayNumberOrAddress(controls, numberOrAddress.getValue(), false); - if (view != null) - controls.addView(view); + if (view != null) controls.addView(view); } } } if (newSipOrNumberToAdd != null) { - boolean isSip = LinphoneUtils.isStrictSipAddress(newSipOrNumberToAdd) || !LinphoneUtils.isNumberAddress(newSipOrNumberToAdd); + boolean isSip = + LinphoneUtils.isStrictSipAddress(newSipOrNumberToAdd) + || !LinphoneUtils.isNumberAddress(newSipOrNumberToAdd); if (!isSip) { View view = displayNumberOrAddress(controls, newSipOrNumberToAdd, false); - if (view != null) - controls.addView(view); + if (view != null) controls.addView(view); } } if (newDisplayName != null) { EditText lastNameEditText = view.findViewById(R.id.contactLastName); - if (view != null) - lastNameEditText.setText(newDisplayName); + if (view != null) lastNameEditText.setText(newDisplayName); } if (controls.getChildCount() == 0) { @@ -469,18 +510,18 @@ public class ContactEditorFragment extends Fragment { for (LinphoneNumberOrAddress numberOrAddress : contact.getNumbersOrAddresses()) { if (numberOrAddress.isSIPAddress()) { View view = displayNumberOrAddress(controls, numberOrAddress.getValue(), true); - if (view != null) - controls.addView(view); + if (view != null) controls.addView(view); } } } if (newSipOrNumberToAdd != null) { - boolean isSip = LinphoneUtils.isStrictSipAddress(newSipOrNumberToAdd) || !LinphoneUtils.isNumberAddress(newSipOrNumberToAdd); + boolean isSip = + LinphoneUtils.isStrictSipAddress(newSipOrNumberToAdd) + || !LinphoneUtils.isNumberAddress(newSipOrNumberToAdd); if (isSip) { View view = displayNumberOrAddress(controls, newSipOrNumberToAdd, true); - if (view != null) - controls.addView(view); + if (view != null) controls.addView(view); } } @@ -491,24 +532,31 @@ public class ContactEditorFragment extends Fragment { return controls; } - private View displayNumberOrAddress(final LinearLayout controls, String numberOrAddress, boolean isSIP) { + private View displayNumberOrAddress( + final LinearLayout controls, String numberOrAddress, boolean isSIP) { return displayNumberOrAddress(controls, numberOrAddress, isSIP, false); } @SuppressLint("InflateParams") - private View displayNumberOrAddress(final LinearLayout controls, String numberOrAddress, boolean isSIP, boolean forceAddNumber) { + private View displayNumberOrAddress( + final LinearLayout controls, + String numberOrAddress, + boolean isSIP, + boolean forceAddNumber) { String displayNumberOrAddress = numberOrAddress; if (isSIP) { if (firstSipAddressIndex == -1) { firstSipAddressIndex = controls.getChildCount(); } - displayNumberOrAddress = LinphoneUtils.getDisplayableUsernameFromAddress(numberOrAddress); + displayNumberOrAddress = + LinphoneUtils.getDisplayableUsernameFromAddress(numberOrAddress); } - if ((getResources().getBoolean(R.bool.hide_phone_numbers_in_editor) && !isSIP) || (getResources().getBoolean(R.bool.hide_sip_addresses_in_editor) && isSIP)) { + if ((getResources().getBoolean(R.bool.hide_phone_numbers_in_editor) && !isSIP) + || (getResources().getBoolean(R.bool.hide_sip_addresses_in_editor) && isSIP)) { if (forceAddNumber) - isSIP = !isSIP; // If number can't be displayed because we hide a sort of number, change that category - else - return null; + isSIP = !isSIP; // If number can't be displayed because we hide a sort of number, + // change that category + else return null; } LinphoneNumberOrAddress tempNounoa; @@ -531,44 +579,46 @@ public class ContactEditorFragment extends Fragment { noa.setInputType(InputType.TYPE_CLASS_PHONE); } noa.setText(displayNumberOrAddress); - noa.addTextChangedListener(new TextWatcher() { - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - nounoa.setValue(noa.getText().toString()); - } + noa.addTextChangedListener( + new TextWatcher() { + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + nounoa.setValue(noa.getText().toString()); + } - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - } + @Override + public void beforeTextChanged( + CharSequence s, int start, int count, int after) {} - @Override - public void afterTextChanged(Editable s) { - } - }); + @Override + public void afterTextChanged(Editable s) {} + }); if (forceAddNumber) { nounoa.setValue(noa.getText().toString()); } ImageView delete = view.findViewById(R.id.delete_field); - if ((getResources().getBoolean(R.bool.allow_only_one_phone_number) && !isSIP) || (getResources().getBoolean(R.bool.allow_only_one_sip_address) && isSIP)) { + if ((getResources().getBoolean(R.bool.allow_only_one_phone_number) && !isSIP) + || (getResources().getBoolean(R.bool.allow_only_one_sip_address) && isSIP)) { delete.setVisibility(View.GONE); } - delete.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - if (contact != null) { - contact.removeNumberOrAddress(nounoa); - } - numbersAndAddresses.remove(nounoa); - view.setVisibility(View.GONE); - - } - }); + delete.setOnClickListener( + new OnClickListener() { + @Override + public void onClick(View v) { + if (contact != null) { + contact.removeNumberOrAddress(nounoa); + } + numbersAndAddresses.remove(nounoa); + view.setVisibility(View.GONE); + } + }); return view; } @SuppressLint("InflateParams") - private void addEmptyRowToAllowNewNumberOrAddress(final LinearLayout controls, final boolean isSip) { + private void addEmptyRowToAllowNewNumberOrAddress( + final LinearLayout controls, final boolean isSip) { final View view = inflater.inflate(R.layout.contact_edit_row, null); final LinphoneNumberOrAddress nounoa = new LinphoneNumberOrAddress(null, isSip); @@ -579,33 +629,35 @@ public class ContactEditorFragment extends Fragment { noa.setInputType(InputType.TYPE_CLASS_PHONE); } noa.requestFocus(); - noa.addTextChangedListener(new TextWatcher() { - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - nounoa.setValue(noa.getText().toString()); - } + noa.addTextChangedListener( + new TextWatcher() { + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + nounoa.setValue(noa.getText().toString()); + } - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - } + @Override + public void beforeTextChanged( + CharSequence s, int start, int count, int after) {} - @Override - public void afterTextChanged(Editable s) { - } - }); + @Override + public void afterTextChanged(Editable s) {} + }); final ImageView delete = view.findViewById(R.id.delete_field); - if ((getResources().getBoolean(R.bool.allow_only_one_phone_number) && !isSip) || (getResources().getBoolean(R.bool.allow_only_one_sip_address) && isSip)) { + if ((getResources().getBoolean(R.bool.allow_only_one_phone_number) && !isSip) + || (getResources().getBoolean(R.bool.allow_only_one_sip_address) && isSip)) { delete.setVisibility(View.GONE); } - delete.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - numbersAndAddresses.remove(nounoa); - view.setVisibility(View.GONE); - } - }); + delete.setOnClickListener( + new OnClickListener() { + @Override + public void onClick(View v) { + numbersAndAddresses.remove(nounoa); + view.setVisibility(View.GONE); + } + }); controls.addView(view); } -} \ No newline at end of file +} diff --git a/app/src/main/java/org/linphone/contacts/ContactPicked.java b/app/src/main/java/org/linphone/contacts/ContactPicked.java index 98453556a..6aa8de15d 100644 --- a/app/src/main/java/org/linphone/contacts/ContactPicked.java +++ b/app/src/main/java/org/linphone/contacts/ContactPicked.java @@ -1,21 +1,21 @@ /* - ContactPicked.java - Copyright (C) 2017 Belledonne Communications, Grenoble, France +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 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. +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. - */ +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; @@ -23,4 +23,4 @@ import android.net.Uri; public interface ContactPicked { void setAddresGoToDialerAndCall(String number, String name, Uri photo); -} \ No newline at end of file +} diff --git a/app/src/main/java/org/linphone/contacts/ContactsListAdapter.java b/app/src/main/java/org/linphone/contacts/ContactsListAdapter.java index 4fc75ab3e..31e2415c4 100644 --- a/app/src/main/java/org/linphone/contacts/ContactsListAdapter.java +++ b/app/src/main/java/org/linphone/contacts/ContactsListAdapter.java @@ -1,27 +1,25 @@ package org.linphone.contacts; /* - ContactsListAdapter.java - Copyright (C) 2018 Belledonne Communications, Grenoble, France +ContactsListAdapter.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 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. +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. - */ +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.content.Context; -import androidx.annotation.NonNull; -import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -31,67 +29,20 @@ import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.SectionIndexer; import android.widget.TextView; - -import org.linphone.R; -import org.linphone.views.ContactAvatar; -import org.linphone.utils.SelectableAdapter; -import org.linphone.utils.SelectableHelper; - +import androidx.annotation.NonNull; +import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; +import org.linphone.R; +import org.linphone.utils.SelectableAdapter; +import org.linphone.utils.SelectableHelper; +import org.linphone.views.ContactAvatar; -public class ContactsListAdapter extends SelectableAdapter implements SectionIndexer { - 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); - } - } - +public class ContactsListAdapter extends SelectableAdapter + implements SectionIndexer { private List mContacts; private String[] mSections; private ArrayList mSectionsList; @@ -100,7 +51,11 @@ public class ContactsListAdapter extends SelectableAdapter contactsList, ViewHolder.ClickListener clickListener, SelectableHelper helper) { + ContactsListAdapter( + Context context, + List contactsList, + ViewHolder.ClickListener clickListener, + SelectableHelper helper) { super(helper); mContext = context; updateDataSet(contactsList); @@ -110,7 +65,9 @@ public class ContactsListAdapter extends SelectableAdapter 0) { + if (contactsList != null + && contactsList.getAdapter() != null + && contactsList.getAdapter().getItemCount() > 0) { ContactsListAdapter mAdapt = (ContactsListAdapter) contactsList.getAdapter(); LinphoneActivity.instance().displayContact((LinphoneContact) mAdapt.getItem(0), false); } else { @@ -203,7 +212,7 @@ public class ContactsListFragment extends Fragment implements OnItemClickListene mContactAdapter = new ContactsListAdapter(mContext, listContact, this, mSelectionHelper); -// contactsList.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE); + // contactsList.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE); mSelectionHelper.setAdapter(mContactAdapter); if (isEditionEnabled) { mSelectionHelper.enterEditionMode(); @@ -211,7 +220,6 @@ public class ContactsListFragment extends Fragment implements OnItemClickListene contactsList.setAdapter(mContactAdapter); } - private void changeContactsAdapter() { changeContactsToggle(); List listContact; @@ -228,9 +236,13 @@ public class ContactsListFragment extends Fragment implements OnItemClickListene } } else { if (onlyDisplayLinphoneContacts) { - listContact = ContactsManager.getInstance().getSIPContacts(mSearchView.getQuery().toString()); + listContact = + ContactsManager.getInstance() + .getSIPContacts(mSearchView.getQuery().toString()); } else { - listContact = ContactsManager.getInstance().getContacts(mSearchView.getQuery().toString()); + listContact = + ContactsManager.getInstance() + .getContacts(mSearchView.getQuery().toString()); } } @@ -257,7 +269,8 @@ public class ContactsListFragment extends Fragment implements OnItemClickListene } private void changeContactsToggle() { - if (onlyDisplayLinphoneContacts && !getResources().getBoolean(R.bool.hide_non_linphone_contacts)) { + if (onlyDisplayLinphoneContacts + && !getResources().getBoolean(R.bool.hide_non_linphone_contacts)) { allContacts.setEnabled(true); allContactsSelected.setVisibility(View.INVISIBLE); linphoneContacts.setEnabled(false); @@ -319,7 +332,9 @@ public class ContactsListFragment extends Fragment implements OnItemClickListene if (LinphoneActivity.isInstanciated()) { LinphoneActivity.instance().selectMenu(FragmentsAvailable.CONTACTS_LIST); - onlyDisplayLinphoneContacts = ContactsManager.getInstance().isLinphoneContactsPrefered() || getResources().getBoolean(R.bool.hide_non_linphone_contacts); + onlyDisplayLinphoneContacts = + ContactsManager.getInstance().isLinphoneContactsPrefered() + || getResources().getBoolean(R.bool.hide_non_linphone_contacts); } changeContactsToggle(); invalidate(); @@ -333,10 +348,14 @@ public class ContactsListFragment extends Fragment implements OnItemClickListene @Override public void onContactsUpdated() { - if (!LinphoneActivity.isInstanciated() || LinphoneActivity.instance().getCurrentFragment() != FragmentsAvailable.CONTACTS_LIST) - return; + if (!LinphoneActivity.isInstanciated() + || LinphoneActivity.instance().getCurrentFragment() + != FragmentsAvailable.CONTACTS_LIST) return; if (mContactAdapter != null) { - mContactAdapter.updateDataSet(onlyDisplayLinphoneContacts ? ContactsManager.getInstance().getSIPContacts() : ContactsManager.getInstance().getContacts()); + mContactAdapter.updateDataSet( + onlyDisplayLinphoneContacts + ? ContactsManager.getInstance().getSIPContacts() + : ContactsManager.getInstance().getContacts()); mContactAdapter.notifyDataSetChanged(); if (mContactAdapter.getItemCount() > 0) { @@ -345,7 +364,6 @@ public class ContactsListFragment extends Fragment implements OnItemClickListene } } contactsFetchInProgress.setVisibility(View.GONE); - } public void invalidate() { diff --git a/app/src/main/java/org/linphone/contacts/ContactsManager.java b/app/src/main/java/org/linphone/contacts/ContactsManager.java index 73d6ea6b1..a2990a255 100644 --- a/app/src/main/java/org/linphone/contacts/ContactsManager.java +++ b/app/src/main/java/org/linphone/contacts/ContactsManager.java @@ -19,13 +19,14 @@ along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ +import static android.os.AsyncTask.THREAD_POOL_EXECUTOR; + import android.accounts.Account; import android.accounts.AccountManager; import android.annotation.SuppressLint; import android.app.Activity; import android.content.ContentProviderOperation; import android.content.ContentResolver; -import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; @@ -37,12 +38,14 @@ import android.net.Uri; import android.os.AsyncTask; import android.provider.ContactsContract; import android.provider.ContactsContract.Data; - +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; import org.linphone.LinphoneActivity; import org.linphone.LinphoneManager; -import org.linphone.settings.LinphonePreferences; import org.linphone.LinphoneService; -import org.linphone.utils.LinphoneUtils; import org.linphone.R; import org.linphone.core.Address; import org.linphone.core.Core; @@ -54,18 +57,24 @@ import org.linphone.core.PresenceBasicStatus; import org.linphone.core.PresenceModel; import org.linphone.core.ProxyConfig; import org.linphone.mediastream.Log; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; - -import static android.os.AsyncTask.THREAD_POOL_EXECUTOR; +import org.linphone.settings.LinphonePreferences; +import org.linphone.utils.LinphoneUtils; public class ContactsManager extends ContentObserver implements FriendListListener { - private static ContactsManager instance; + @SuppressLint("InlinedApi") + private static final String[] PROJECTION = { + Data.CONTACT_ID, + ContactsContract.Contacts.LOOKUP_KEY, + ContactsContract.Contacts.DISPLAY_NAME_PRIMARY, + Data.MIMETYPE, + "data1", // Company, Phone or SIP Address + "data2", // ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME + "data3", // ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME + "data4", // Normalized phone number + }; + private static ContactsManager instance; + private static ArrayList contactsUpdatedListeners; private List mContacts, mSipContacts; private MagicSearch magicSearch; private Bitmap defaultAvatar; @@ -73,7 +82,18 @@ public class ContactsManager extends ContentObserver implements FriendListListen private Context mContext; private AsyncContactsLoader mLoadContactTask; - private static ArrayList contactsUpdatedListeners; + private ContactsManager() { + super(LinphoneService.instance().mHandler); + defaultAvatar = + BitmapFactory.decodeResource( + LinphoneService.instance().getResources(), R.drawable.avatar); + contactsUpdatedListeners = new ArrayList<>(); + mContacts = new ArrayList<>(); + mSipContacts = new ArrayList<>(); + if (LinphoneManager.getLcIfManagerNotDestroyedOrNull() != null) { + magicSearch = LinphoneManager.getLcIfManagerNotDestroyedOrNull().createMagicSearch(); + } + } public static void addContactsListener(ContactsUpdatedListener listener) { contactsUpdatedListeners.add(listener); @@ -83,15 +103,39 @@ public class ContactsManager extends ContentObserver implements FriendListListen contactsUpdatedListeners.remove(listener); } - private ContactsManager() { - super(LinphoneService.instance().mHandler); - defaultAvatar = BitmapFactory.decodeResource(LinphoneService.instance().getResources(), R.drawable.avatar); - contactsUpdatedListeners = new ArrayList<>(); - mContacts = new ArrayList<>(); - mSipContacts = new ArrayList<>(); - if (LinphoneManager.getLcIfManagerNotDestroyedOrNull() != null) { - magicSearch = LinphoneManager.getLcIfManagerNotDestroyedOrNull().createMagicSearch(); + public static final ContactsManager getInstance() { + if (instance == null) instance = new ContactsManager(); + return instance; + } + + public static String getAddressOrNumberForAndroidContact( + ContentResolver resolver, Uri contactUri) { + // Phone Numbers + String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.NUMBER}; + Cursor c = resolver.query(contactUri, projection, null, null, null); + if (c != null) { + while (c.moveToNext()) { + int numberIndex = c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER); + String number = c.getString(numberIndex); + c.close(); + return number; + } } + + // SIP addresses + projection = new String[] {ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS}; + c = resolver.query(contactUri, projection, null, null, null); + if (c != null) { + while (c.moveToNext()) { + int numberIndex = + c.getColumnIndex(ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS); + String address = c.getString(numberIndex); + c.close(); + return address; + } + c.close(); + } + return null; } public void destroy() { @@ -122,17 +166,11 @@ public class ContactsManager extends ContentObserver implements FriendListListen onChange(selfChange, null); } - @Override public void onChange(boolean selfChange, Uri uri) { fetchContactsAsync(); } - public static final ContactsManager getInstance() { - if (instance == null) instance = new ContactsManager(); - return instance; - } - public synchronized boolean hasContacts() { return mContacts.size() > 0; } @@ -143,6 +181,12 @@ public class ContactsManager extends ContentObserver implements FriendListListen } } + public void setContacts(List c) { + synchronized (mContacts) { + mContacts = c; + } + } + public List getSIPContacts() { synchronized (mSipContacts) { return mSipContacts; @@ -157,7 +201,9 @@ public class ContactsManager extends ContentObserver implements FriendListListen if (contact.getFullName() != null) { if (contact.getFullName().toLowerCase(Locale.getDefault()).startsWith(search)) { searchContactsBegin.add(contact); - } else if (contact.getFullName().toLowerCase(Locale.getDefault()).contains(search)) { + } else if (contact.getFullName() + .toLowerCase(Locale.getDefault()) + .contains(search)) { searchContactsContain.add(contact); } } @@ -174,7 +220,9 @@ public class ContactsManager extends ContentObserver implements FriendListListen if (contact.getFullName() != null) { if (contact.getFullName().toLowerCase(Locale.getDefault()).startsWith(search)) { searchContactsBegin.add(contact); - } else if (contact.getFullName().toLowerCase(Locale.getDefault()).contains(search)) { + } else if (contact.getFullName() + .toLowerCase(Locale.getDefault()) + .contains(search)) { searchContactsContain.add(contact); } } @@ -198,14 +246,21 @@ public class ContactsManager extends ContentObserver implements FriendListListen if (mContext == null) { return false; } - boolean contactsR = (PackageManager.PERMISSION_GRANTED == - mContext.getPackageManager().checkPermission(android.Manifest.permission.READ_CONTACTS, mContext.getPackageName())); - return contactsR && !mContext.getResources().getBoolean(R.bool.force_use_of_linphone_friends); + boolean contactsR = + (PackageManager.PERMISSION_GRANTED + == mContext.getPackageManager() + .checkPermission( + android.Manifest.permission.READ_CONTACTS, + mContext.getPackageName())); + return contactsR + && !mContext.getResources().getBoolean(R.bool.force_use_of_linphone_friends); } public boolean isLinphoneContactsPrefered() { ProxyConfig lpc = LinphoneManager.getLc().getDefaultProxyConfig(); - if (lpc != null && lpc.getIdentityAddress().getDomain().equals(getString(R.string.default_domain))) return true; + if (lpc != null + && lpc.getIdentityAddress().getDomain().equals(getString(R.string.default_domain))) + return true; return false; } @@ -219,12 +274,14 @@ public class ContactsManager extends ContentObserver implements FriendListListen public void initializeSyncAccount(Activity activity) { initializeContactManager(activity); - AccountManager accountManager = (AccountManager) activity.getSystemService(Context.ACCOUNT_SERVICE); + AccountManager accountManager = + (AccountManager) activity.getSystemService(Context.ACCOUNT_SERVICE); Account[] accounts = accountManager.getAccountsByType(activity.getPackageName()); if (accounts != null && accounts.length == 0) { - Account newAccount = new Account(getString(R.string.sync_account_name), activity.getPackageName()); + Account newAccount = + new Account(getString(R.string.sync_account_name), activity.getPackageName()); try { accountManager.addAccountExplicitly(newAccount, null, null); } catch (Exception e) { @@ -259,7 +316,9 @@ public class ContactsManager extends ContentObserver implements FriendListListen return null; } addr.setUriParam("user", "phone"); - Friend lf = lc.findFriend(addr); // Without this, the hashmap inside liblinphone won't find it... + Friend lf = + lc.findFriend( + addr); // Without this, the hashmap inside liblinphone won't find it... if (lf != null) { LinphoneContact contact = (LinphoneContact) lf.getUserData(); return contact; @@ -276,34 +335,6 @@ public class ContactsManager extends ContentObserver implements FriendListListen return false; } - public static String getAddressOrNumberForAndroidContact(ContentResolver resolver, Uri contactUri) { - // Phone Numbers - String[] projection = new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER}; - Cursor c = resolver.query(contactUri, projection, null, null, null); - if (c != null) { - while (c.moveToNext()) { - int numberIndex = c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER); - String number = c.getString(numberIndex); - c.close(); - return number; - } - } - - // SIP addresses - projection = new String[]{ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS}; - c = resolver.query(contactUri, projection, null, null, null); - if (c != null) { - while (c.moveToNext()) { - int numberIndex = c.getColumnIndex(ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS); - String address = c.getString(numberIndex); - c.close(); - return address; - } - c.close(); - } - return null; - } - public void delete(String id) { ArrayList ids = new ArrayList<>(); ids.add(id); @@ -315,8 +346,11 @@ public class ContactsManager extends ContentObserver implements FriendListListen ArrayList ops = new ArrayList<>(); for (String id : ids) { - String[] args = new String[]{id}; - ops.add(ContentProviderOperation.newDelete(ContactsContract.RawContacts.CONTENT_URI).withSelection(select, args).build()); + String[] args = new String[] {id}; + ops.add( + ContentProviderOperation.newDelete(ContactsContract.RawContacts.CONTENT_URI) + .withSelection(select, args) + .build()); } try { @@ -332,24 +366,16 @@ public class ContactsManager extends ContentObserver implements FriendListListen } @Override - public void onContactCreated(FriendList list, Friend lf) { - - } + public void onContactCreated(FriendList list, Friend lf) {} @Override - public void onContactDeleted(FriendList list, Friend lf) { - - } + public void onContactDeleted(FriendList list, Friend lf) {} @Override - public void onContactUpdated(FriendList list, Friend newFriend, Friend oldFriend) { - - } + public void onContactUpdated(FriendList list, Friend newFriend, Friend oldFriend) {} @Override - public void onSyncStatusChanged(FriendList list, FriendList.SyncStatus status, String msg) { - - } + public void onSyncStatusChanged(FriendList list, FriendList.SyncStatus status, String msg) {} @Override public void onPresenceReceived(FriendList list, Friend[] friends) { @@ -371,18 +397,47 @@ public class ContactsManager extends ContentObserver implements FriendListListen mLoadContactTask.executeOnExecutor(THREAD_POOL_EXECUTOR); } - @SuppressLint("InlinedApi") - private static final String[] PROJECTION = - { - Data.CONTACT_ID, - ContactsContract.Contacts.LOOKUP_KEY, - ContactsContract.Contacts.DISPLAY_NAME_PRIMARY, - Data.MIMETYPE, - "data1", //Company, Phone or SIP Address - "data2", //ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME - "data3", //ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME - "data4", //Normalized phone number - }; + public synchronized void setSipContacts(List c) { + synchronized (mSipContacts) { + mSipContacts = c; + } + } + + public void editContact(Context context, LinphoneContact contact, String valueToAdd) { + if (context.getResources().getBoolean(R.bool.use_native_contact_editor)) { + Intent intent = new Intent(Intent.ACTION_EDIT); + Uri contactUri = + ContactsContract.Contacts.getLookupUri( + Long.parseLong(contact.getAndroidId()), contact.getAndroidLookupKey()); + intent.setDataAndType(contactUri, ContactsContract.Contacts.CONTENT_ITEM_TYPE); + intent.putExtra( + "finishActivityOnSaveCompleted", true); // So after save will go back here + if (valueToAdd != null) { + intent.putExtra(ContactsContract.Intents.Insert.IM_HANDLE, valueToAdd); + } + context.startActivity(intent); + } else { + LinphoneActivity.instance().editContact(contact); + } + } + + public void createContact(Context context, String name, String valueToAdd) { + if (context.getResources().getBoolean(R.bool.use_native_contact_editor)) { + Intent intent = new Intent(ContactsContract.Intents.Insert.ACTION); + intent.setType(ContactsContract.RawContacts.CONTENT_TYPE); + intent.putExtra( + "finishActivityOnSaveCompleted", true); // So after save will go back here + if (name != null) { + intent.putExtra(ContactsContract.Intents.Insert.NAME, name); + } + if (valueToAdd != null) { + intent.putExtra(ContactsContract.Intents.Insert.IM_HANDLE, valueToAdd); + } + context.startActivity(intent); + } else { + LinphoneActivity.instance().addContact(name, valueToAdd); + } + } class AsyncContactsData { List contacts; @@ -402,10 +457,13 @@ public class ContactsManager extends ContentObserver implements FriendListListen mAndroidContactsCache = new HashMap<>(); mContactsFetchedOnce = true; - if (LinphonePreferences.instance() != null && LinphonePreferences.instance().isFriendlistsubscriptionEnabled()) { + if (LinphonePreferences.instance() != null + && LinphonePreferences.instance().isFriendlistsubscriptionEnabled()) { String rls = getString(R.string.rls_uri); for (FriendList list : LinphoneManager.getLc().getFriendsLists()) { - if (rls != null && (list.getRlsAddress() == null || !list.getRlsAddress().asStringUriOnly().equals(rls))) { + if (rls != null + && (list.getRlsAddress() == null + || !list.getRlsAddress().asStringUriOnly().equals(rls))) { list.setRlsUri(rls); } list.setListener(ContactsManager.this); @@ -415,7 +473,14 @@ public class ContactsManager extends ContentObserver implements FriendListListen @Override protected AsyncContactsData doInBackground(Void... params) { - Cursor c = mContext.getContentResolver().query(ContactsContract.Data.CONTENT_URI, PROJECTION, Data.IN_VISIBLE_GROUP + " == 1", null, null); + Cursor c = + mContext.getContentResolver() + .query( + ContactsContract.Data.CONTENT_URI, + PROJECTION, + Data.IN_VISIBLE_GROUP + " == 1", + null, + null); AsyncContactsData data = new AsyncContactsData(); Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull(); @@ -432,7 +497,9 @@ public class ContactsManager extends ContentObserver implements FriendListListen } } else { if (friend.getRefKey() != null) { - // Friend has a refkey and but no LinphoneContact => represents a native contact stored in db from a previous version of Linphone, remove it + // Friend has a refkey and but no LinphoneContact => represents a + // native contact stored in db from a previous version of Linphone, + // remove it list.removeFriend(friend); } else { // No refkey so it's a standalone contact @@ -458,7 +525,8 @@ public class ContactsManager extends ContentObserver implements FriendListListen String data2 = c.getString(c.getColumnIndex("data2")); String data3 = c.getString(c.getColumnIndex("data3")); String data4 = c.getString(c.getColumnIndex("data4")); - String lookupKey = c.getString(c.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY)); + String lookupKey = + c.getString(c.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY)); LinphoneContact contact = mAndroidContactsCache.get(id); if (contact == null) { @@ -475,11 +543,15 @@ public class ContactsManager extends ContentObserver implements FriendListListen if (ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE.equals(mime)) { contact.addNumberOrAddress(new LinphoneNumberOrAddress(data1, data4)); - } else if (ContactsContract.CommonDataKinds.SipAddress.CONTENT_ITEM_TYPE.equals(mime) || getInstance().getString(R.string.sync_mimetype).equals(mime)) { + } else if (ContactsContract.CommonDataKinds.SipAddress.CONTENT_ITEM_TYPE.equals( + mime) + || getInstance().getString(R.string.sync_mimetype).equals(mime)) { contact.addNumberOrAddress(new LinphoneNumberOrAddress(data1, true)); - } else if (ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE.equals(mime)) { + } else if (ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE + .equals(mime)) { contact.setOrganization(data1, false); - } else if (ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE.equals(mime)) { + } else if (ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE + .equals(mime)) { contact.setFirstNameAndLastName(data2, data3, false); } } @@ -504,13 +576,19 @@ public class ContactsManager extends ContentObserver implements FriendListListen for (LinphoneContact contact : mAndroidContactsCache.values()) { if (isCancelled()) return data; - boolean hideContactsWithoutPresence = mContext.getResources().getBoolean(R.bool.hide_sip_contacts_without_presence); + boolean hideContactsWithoutPresence = + mContext.getResources() + .getBoolean(R.bool.hide_sip_contacts_without_presence); if (contact.hasAddress()) { if (contact.getFullName() == null) { for (LinphoneNumberOrAddress noa : contact.getNumbersOrAddresses()) { if (noa.isSIPAddress()) { - contact.setFullName(LinphoneUtils.getAddressDisplayName(noa.getValue())); - Log.w("[Contacts Manager] Couldn't find a display name for contact " + contact.getFullName() + ", used SIP address display name / username instead..."); + contact.setFullName( + LinphoneUtils.getAddressDisplayName(noa.getValue())); + Log.w( + "[Contacts Manager] Couldn't find a display name for contact " + + contact.getFullName() + + ", used SIP address display name / username instead..."); break; } } @@ -518,8 +596,11 @@ public class ContactsManager extends ContentObserver implements FriendListListen if (hideContactsWithoutPresence) { if (contact.getFriend() != null) { for (LinphoneNumberOrAddress noa : contact.getNumbersOrAddresses()) { - PresenceModel pm = contact.getFriend().getPresenceModelForUriOrTel(noa.getValue()); - if (pm != null && pm.getBasicStatus().equals(PresenceBasicStatus.Open)) { + PresenceModel pm = + contact.getFriend() + .getPresenceModelForUriOrTel(noa.getValue()); + if (pm != null + && pm.getBasicStatus().equals(PresenceBasicStatus.Open)) { data.sipContacts.add(contact); break; } @@ -552,48 +633,4 @@ public class ContactsManager extends ContentObserver implements FriendListListen setSipContacts(data.sipContacts); } } - - public void setContacts(List c) { - synchronized (mContacts) { - mContacts = c; - } - } - - public synchronized void setSipContacts(List c) { - synchronized (mSipContacts) { - mSipContacts = c; - } - } - - public void editContact(Context context, LinphoneContact contact, String valueToAdd) { - if (context.getResources().getBoolean(R.bool.use_native_contact_editor)) { - Intent intent = new Intent(Intent.ACTION_EDIT); - Uri contactUri = ContactsContract.Contacts.getLookupUri(Long.parseLong(contact.getAndroidId()), contact.getAndroidLookupKey()); - intent.setDataAndType(contactUri, ContactsContract.Contacts.CONTENT_ITEM_TYPE); - intent.putExtra("finishActivityOnSaveCompleted", true); // So after save will go back here - if (valueToAdd != null) { - intent.putExtra(ContactsContract.Intents.Insert.IM_HANDLE, valueToAdd); - } - context.startActivity(intent); - } else { - LinphoneActivity.instance().editContact(contact); - } - } - - public void createContact(Context context, String name, String valueToAdd) { - if (context.getResources().getBoolean(R.bool.use_native_contact_editor)) { - Intent intent = new Intent(ContactsContract.Intents.Insert.ACTION); - intent.setType(ContactsContract.RawContacts.CONTENT_TYPE); - intent.putExtra("finishActivityOnSaveCompleted", true); // So after save will go back here - if (name != null) { - intent.putExtra(ContactsContract.Intents.Insert.NAME, name); - } - if (valueToAdd != null) { - intent.putExtra(ContactsContract.Intents.Insert.IM_HANDLE, valueToAdd); - } - context.startActivity(intent); - } else { - LinphoneActivity.instance().addContact(name, valueToAdd); - } - } } diff --git a/app/src/main/java/org/linphone/contacts/ContactsUpdatedListener.java b/app/src/main/java/org/linphone/contacts/ContactsUpdatedListener.java index bc7f67f6a..6c50526c1 100644 --- a/app/src/main/java/org/linphone/contacts/ContactsUpdatedListener.java +++ b/app/src/main/java/org/linphone/contacts/ContactsUpdatedListener.java @@ -21,4 +21,4 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. public interface ContactsUpdatedListener { void onContactsUpdated(); -} \ No newline at end of file +} diff --git a/app/src/main/java/org/linphone/contacts/LinphoneContact.java b/app/src/main/java/org/linphone/contacts/LinphoneContact.java index debc6fc3d..0fef18413 100644 --- a/app/src/main/java/org/linphone/contacts/LinphoneContact.java +++ b/app/src/main/java/org/linphone/contacts/LinphoneContact.java @@ -27,7 +27,11 @@ import android.database.Cursor; import android.net.Uri; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds; - +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Locale; import org.linphone.LinphoneManager; import org.linphone.LinphoneService; import org.linphone.R; @@ -40,17 +44,18 @@ import org.linphone.core.PresenceModel; import org.linphone.core.SubscribePolicy; import org.linphone.mediastream.Log; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Locale; - public class LinphoneContact implements Serializable, Comparable { private static final long serialVersionUID = 9015568163905205244L; private transient Friend friend; - private String fullName, firstName, lastName, androidId, androidRawId, androidTagId, organization, androidLookupKey; + private String fullName, + firstName, + lastName, + androidId, + androidRawId, + androidTagId, + organization, + androidLookupKey; private transient Uri photoUri, thumbnailUri; private List addresses; private transient ArrayList changesToCommit; @@ -68,10 +73,48 @@ public class LinphoneContact implements Serializable, Comparable 0 && lastName.length() > 0) { + if (firstName != null + && lastName != null + && firstName.length() > 0 + && lastName.length() > 0) { fullName = firstName + " " + lastName; } else if (firstName != null && firstName.length() > 0) { fullName = firstName; @@ -176,31 +245,54 @@ public class LinphoneContact implements Serializable, Comparable 0) { + if (isAndroidContact() + && ContactsManager.getInstance().hasContactsAccess() + && changesToCommit.size() > 0) { try { - LinphoneService.instance().getContentResolver().applyBatch(ContactsContract.AUTHORITY, changesToCommit); + LinphoneService.instance() + .getContentResolver() + .applyBatch(ContactsContract.AUTHORITY, changesToCommit); createLinphoneTagIfNeeded(); } catch (Exception e) { Log.e(e); @@ -598,7 +831,8 @@ public class LinphoneContact implements Serializable, Comparable result = new ArrayList<>(); ContentResolver resolver = LinphoneService.instance().getContentResolver(); - String select = ContactsContract.Data.CONTACT_ID + " =? AND (" + ContactsContract.Data.MIMETYPE + "=? OR " + ContactsContract.Data.MIMETYPE + "=? OR " + ContactsContract.Data.MIMETYPE + "=?)"; - String[] projection = new String[]{"data1", "data4", ContactsContract.Data.MIMETYPE}; // PHONE_NUMBER == SIP_ADDRESS == "data1"... - Cursor c = resolver.query(ContactsContract.Data.CONTENT_URI, projection, select, new String[]{getAndroidId(), ContactsContract.CommonDataKinds.SipAddress.CONTENT_ITEM_TYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE, ContactsManager.getInstance().getString(R.string.sync_mimetype)}, null); + String select = + ContactsContract.Data.CONTACT_ID + + " =? AND (" + + ContactsContract.Data.MIMETYPE + + "=? OR " + + ContactsContract.Data.MIMETYPE + + "=? OR " + + ContactsContract.Data.MIMETYPE + + "=?)"; + String[] projection = + new String[] { + "data1", "data4", ContactsContract.Data.MIMETYPE + }; // PHONE_NUMBER == SIP_ADDRESS == "data1"... + Cursor c = + resolver.query( + ContactsContract.Data.CONTENT_URI, + projection, + select, + new String[] { + getAndroidId(), + ContactsContract.CommonDataKinds.SipAddress.CONTENT_ITEM_TYPE, + ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE, + ContactsManager.getInstance().getString(R.string.sync_mimetype) + }, + null); if (c != null) { while (c.moveToNext()) { String mime = c.getString(c.getColumnIndex(ContactsContract.Data.MIMETYPE)); if (mime != null && mime.length() > 0) { - if (mime.equals(ContactsContract.CommonDataKinds.SipAddress.CONTENT_ITEM_TYPE) || mime.equals(ContactsManager.getInstance().getString(R.string.sync_mimetype))) { + if (mime.equals(ContactsContract.CommonDataKinds.SipAddress.CONTENT_ITEM_TYPE) + || mime.equals( + ContactsManager.getInstance() + .getString(R.string.sync_mimetype))) { String number = c.getString(c.getColumnIndex("data1")); // SIP_ADDRESS result.add(new LinphoneNumberOrAddress(number, true)); - } else if (mime.equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)) { + } else if (mime.equals( + ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)) { String number = c.getString(c.getColumnIndex("data1")); // PHONE_NUMBER - String normalized_number = c.getString(c.getColumnIndex("data4")); // NORMALIZED_PHONE_NUMBER + String normalized_number = + c.getString(c.getColumnIndex("data4")); // NORMALIZED_PHONE_NUMBER result.add(new LinphoneNumberOrAddress(number, normalized_number)); } } @@ -746,37 +1043,26 @@ public class LinphoneContact implements Serializable, Comparable batch = new ArrayList<>(); - batch.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI) - .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, ContactsManager.getInstance().getString(R.string.sync_account_type)) - .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, ContactsManager.getInstance().getString(R.string.sync_account_name)) - .withValue(ContactsContract.RawContacts.AGGREGATION_MODE, ContactsContract.RawContacts.AGGREGATION_MODE_DEFAULT) - .build()); + batch.add( + ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI) + .withValue( + ContactsContract.RawContacts.ACCOUNT_TYPE, + ContactsManager.getInstance().getString(R.string.sync_account_type)) + .withValue( + ContactsContract.RawContacts.ACCOUNT_NAME, + ContactsManager.getInstance().getString(R.string.sync_account_name)) + .withValue( + ContactsContract.RawContacts.AGGREGATION_MODE, + ContactsContract.RawContacts.AGGREGATION_MODE_DEFAULT) + .build()); - batch.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) - .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0) - .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE) - .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, getFullName()) - .build()); + batch.add( + ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) + .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0) + .withValue( + ContactsContract.Data.MIMETYPE, + ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE) + .withValue( + ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, + getFullName()) + .build()); - batch.add(ContentProviderOperation.newUpdate(ContactsContract.AggregationExceptions.CONTENT_URI) - .withValue(ContactsContract.AggregationExceptions.TYPE, ContactsContract.AggregationExceptions.TYPE_KEEP_TOGETHER) - .withValue(ContactsContract.AggregationExceptions.RAW_CONTACT_ID1, androidRawId) - .withValueBackReference(ContactsContract.AggregationExceptions.RAW_CONTACT_ID2, 0) - .build()); + batch.add( + ContentProviderOperation.newUpdate( + ContactsContract.AggregationExceptions.CONTENT_URI) + .withValue( + ContactsContract.AggregationExceptions.TYPE, + ContactsContract.AggregationExceptions.TYPE_KEEP_TOGETHER) + .withValue( + ContactsContract.AggregationExceptions.RAW_CONTACT_ID1, + androidRawId) + .withValueBackReference( + ContactsContract.AggregationExceptions.RAW_CONTACT_ID2, 0) + .build()); if (changesToCommit2.size() > 0) { for (ContentProviderOperation cpo : changesToCommit2) { @@ -822,7 +1130,9 @@ public class LinphoneContact implements Serializable, Comparable { +public class SearchContactsListAdapter + extends RecyclerView.Adapter { @SuppressWarnings("unused") private static final String TAG = SearchContactsListAdapter.class.getSimpleName(); - public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { - public TextView name; - public TextView address; - public ImageView linphoneContact; - public ImageView isSelect; - public 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); - } - } - private List contacts; private List contactsSelected; private ProgressBar progressBar; @@ -88,6 +54,19 @@ public class SearchContactsListAdapter extends RecyclerView.Adapter contactsList, + ProgressBar pB, + ViewHolder.ClickListener clickListener, + boolean hideSelectionMark) { + mHideSelectionMark = hideSelectionMark; + mListener = clickListener; + progressBar = pB; + setContactsSelectedList(null); + setContactsList(contactsList); + mPreviousSearch = null; + } + public List getContacts() { return contacts; } @@ -100,32 +79,27 @@ public class SearchContactsListAdapter extends RecyclerView.Adapter contactsList, ProgressBar pB, ViewHolder.ClickListener clickListener, boolean hideSelectionMark) { - mHideSelectionMark = hideSelectionMark; - mListener = clickListener; - progressBar = pB; - setContactsSelectedList(null); - setContactsList(contactsList); - mPreviousSearch = null; - } - @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { - View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.search_contact_cell, parent, false); + View v = + LayoutInflater.from(parent.getContext()) + .inflate(R.layout.search_contact_cell, parent, false); return new ViewHolder(v, mListener); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { ContactAddress contact = getItem(position); - final String a = (contact.getAddressAsDisplayableString().isEmpty()) ? contact.getPhoneNumber() : contact.getAddressAsDisplayableString(); + final String a = + (contact.getAddressAsDisplayableString().isEmpty()) + ? contact.getPhoneNumber() + : contact.getAddressAsDisplayableString(); LinphoneContact c = contact.getContact(); String address = contact.getAddressAsDisplayableString(); if (c != null && c.getFullName() != null) { - if (address == null) - address = c.getPresenceModelForUriOrTel(a); + if (address == null) address = c.getPresenceModelForUriOrTel(a); holder.name.setVisibility(View.VISIBLE); holder.name.setText(c.getFullName()); } else if (contact.getAddress() != null) { @@ -139,7 +113,10 @@ public class SearchContactsListAdapter extends RecyclerView.Adapter contactsList) { - if (contactsList == null) { - contacts = getContactsList(); - if (progressBar != null) - progressBar.setVisibility(View.GONE); - } else { - contacts = contactsList; - } + public List getContactsSelectedList() { + return contactsSelected; } public void setContactsSelectedList(List contactsList) { @@ -211,26 +182,37 @@ public class SearchContactsListAdapter extends RecyclerView.Adapter getContactsSelectedList() { - return contactsSelected; - } - public List getContactsList() { List list = new ArrayList<>(); if (ContactsManager.getInstance().hasContacts()) { - List contacts = mOnlySipContact ? ContactsManager.getInstance().getSIPContacts() : ContactsManager.getInstance().getContacts(); + List contacts = + mOnlySipContact + ? ContactsManager.getInstance().getSIPContacts() + : ContactsManager.getInstance().getContacts(); for (LinphoneContact contact : contacts) { for (LinphoneNumberOrAddress noa : contact.getNumbersOrAddresses()) { - if (!mOnlySipContact || (mOnlySipContact && (noa.isSIPAddress() || contact.getPresenceModelForUriOrTel(noa.getValue()) != null))) { + if (!mOnlySipContact + || (mOnlySipContact + && (noa.isSIPAddress() + || contact.getPresenceModelForUriOrTel(noa.getValue()) + != null))) { ContactAddress ca = null; if (noa.isSIPAddress()) { Address address = LinphoneManager.getLc().interpretUrl(noa.getValue()); if (address != null) { - ca = new ContactAddress(contact, address.asString(), "", contact.isFriend()); + ca = + new ContactAddress( + contact, + address.asString(), + "", + contact.isFriend()); } } else { ProxyConfig prx = LinphoneManager.getLc().getDefaultProxyConfig(); - String number = (prx != null) ? prx.normalizePhoneNumber(noa.getValue()) : noa.getValue(); + String number = + (prx != null) + ? prx.normalizePhoneNumber(noa.getValue()) + : noa.getValue(); ca = new ContactAddress(contact, "", number, contact.isFriend()); } if (ca != null) list.add(ca); @@ -247,6 +229,15 @@ public class SearchContactsListAdapter extends RecyclerView.Adapter contactsList) { + if (contactsList == null) { + contacts = getContactsList(); + if (progressBar != null) progressBar.setVisibility(View.GONE); + } else { + contacts = contactsList; + } + } + public int getCount() { return contacts.size(); } @@ -255,7 +246,6 @@ public class SearchContactsListAdapter extends RecyclerView.Adapter 0) { + if (LinphoneActivity.isInstanciated() + && LinphoneManager.getLcIfManagerNotDestroyedOrNull() != null + && LinphoneManager.getLcIfManagerNotDestroyedOrNull().getCallsNb() > 0) { if (isCallTransferOngoing) { mCall.setImageResource(R.drawable.call_transfer); } else { mCall.setImageResource(R.drawable.call_add); } } else { - if (LinphoneManager.getLcIfManagerNotDestroyedOrNull() != null && LinphoneManager.getLcIfManagerNotDestroyedOrNull().getVideoActivationPolicy().getAutomaticallyInitiate()) { + if (LinphoneManager.getLcIfManagerNotDestroyedOrNull() != null + && LinphoneManager.getLcIfManagerNotDestroyedOrNull() + .getVideoActivationPolicy() + .getAutomaticallyInitiate()) { mCall.setImageResource(R.drawable.call_video_start); } else { mCall.setImageResource(R.drawable.call_audio_start); @@ -86,32 +95,41 @@ public class DialerFragment extends Fragment { } mAddContact = view.findViewById(R.id.add_contact); - mAddContact.setEnabled(!(LinphoneActivity.isInstanciated() && LinphoneManager.getLcIfManagerNotDestroyedOrNull() != null && LinphoneManager.getLc().getCallsNb() > 0)); + mAddContact.setEnabled( + !(LinphoneActivity.isInstanciated() + && LinphoneManager.getLcIfManagerNotDestroyedOrNull() != null + && LinphoneManager.getLc().getCallsNb() > 0)); - addContactListener = new OnClickListener() { - @Override - public void onClick(View v) { - LinphoneActivity.instance().displayContactsForEdition(mAddress.getText().toString()); - } - }; - cancelListener = new OnClickListener() { - @Override - public void onClick(View v) { - LinphoneActivity.instance().resetClassicMenuLayoutAndGoBackToCallIfStillRunning(); - } - }; - transferListener = new OnClickListener() { - @Override - public void onClick(View v) { - Core lc = LinphoneManager.getLc(); - if (lc.getCurrentCall() == null) { - return; - } - lc.transferCall(lc.getCurrentCall(), mAddress.getText().toString()); - isCallTransferOngoing = false; - LinphoneActivity.instance().resetClassicMenuLayoutAndGoBackToCallIfStillRunning(); - } - }; + addContactListener = + new OnClickListener() { + @Override + public void onClick(View v) { + LinphoneActivity.instance() + .displayContactsForEdition(mAddress.getText().toString()); + } + }; + cancelListener = + new OnClickListener() { + @Override + public void onClick(View v) { + LinphoneActivity.instance() + .resetClassicMenuLayoutAndGoBackToCallIfStillRunning(); + } + }; + transferListener = + new OnClickListener() { + @Override + public void onClick(View v) { + Core lc = LinphoneManager.getLc(); + if (lc.getCurrentCall() == null) { + return; + } + lc.transferCall(lc.getCurrentCall(), mAddress.getText().toString()); + isCallTransferOngoing = false; + LinphoneActivity.instance() + .resetClassicMenuLayoutAndGoBackToCallIfStillRunning(); + } + }; resetLayout(); @@ -129,13 +147,6 @@ public class DialerFragment extends Fragment { return view; } - /** - * @return null if not ready yet - */ - public static DialerFragment instance() { - return instance; - } - @Override public void onPause() { instance = null; @@ -153,7 +164,9 @@ public class DialerFragment extends Fragment { LinphoneActivity.instance().showStatusBar(); } - boolean isOrientationLandscape = getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE; + boolean isOrientationLandscape = + getResources().getConfiguration().orientation + == Configuration.ORIENTATION_LANDSCAPE; if (isOrientationLandscape && !getResources().getBoolean(R.bool.isTablet)) { ((LinearLayout) numpad).setVisibility(View.GONE); } else { @@ -165,7 +178,8 @@ public class DialerFragment extends Fragment { String addressWaitingToBeCalled = LinphoneActivity.instance().mAddressWaitingToBeCalled; if (addressWaitingToBeCalled != null) { mAddress.setText(addressWaitingToBeCalled); - if (getResources().getBoolean(R.bool.automatically_start_intercepted_outgoing_gsm_call)) { + if (getResources() + .getBoolean(R.bool.automatically_start_intercepted_outgoing_gsm_call)) { newOutgoingCall(addressWaitingToBeCalled); } LinphoneActivity.instance().mAddressWaitingToBeCalled = null; @@ -207,7 +221,10 @@ public class DialerFragment extends Fragment { } public void enableDisableAddContact() { - mAddContact.setEnabled(LinphoneManager.getLcIfManagerNotDestroyedOrNull() != null && LinphoneManager.getLc().getCallsNb() > 0 || !mAddress.getText().toString().equals("")); + mAddContact.setEnabled( + LinphoneManager.getLcIfManagerNotDestroyedOrNull() != null + && LinphoneManager.getLc().getCallsNb() > 0 + || !mAddress.getText().toString().equals("")); } public void displayTextInAddressBar(String numberOrSipAddress) { @@ -228,7 +245,9 @@ public class DialerFragment extends Fragment { mAddress.setText(intent.getData().getSchemeSpecificPart()); } else { Uri contactUri = intent.getData(); - String address = ContactsManager.getAddressOrNumberForAndroidContact(LinphoneService.instance().getContentResolver(), contactUri); + String address = + ContactsManager.getAddressOrNumberForAndroidContact( + LinphoneService.instance().getContentResolver(), contactUri); if (address != null) { mAddress.setText(address); } else { diff --git a/app/src/main/java/org/linphone/fragments/EmptyFragment.java b/app/src/main/java/org/linphone/fragments/EmptyFragment.java index e5763481b..9ea81516c 100644 --- a/app/src/main/java/org/linphone/fragments/EmptyFragment.java +++ b/app/src/main/java/org/linphone/fragments/EmptyFragment.java @@ -24,17 +24,15 @@ import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; - import org.linphone.R; public class EmptyFragment extends Fragment { @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.empty_fragment, container, false); return view; } - } diff --git a/app/src/main/java/org/linphone/fragments/FragmentsAvailable.java b/app/src/main/java/org/linphone/fragments/FragmentsAvailable.java index 9ed1af3da..db9ff7aec 100644 --- a/app/src/main/java/org/linphone/fragments/FragmentsAvailable.java +++ b/app/src/main/java/org/linphone/fragments/FragmentsAvailable.java @@ -46,16 +46,23 @@ public enum FragmentsAvailable { return fragment == HISTORY_LIST || fragment == HISTORY_DETAIL; case CONTACT_DETAIL: - return fragment == CONTACTS_LIST || fragment == CONTACT_EDITOR || fragment == CONTACT_DETAIL; + return fragment == CONTACTS_LIST + || fragment == CONTACT_EDITOR + || fragment == CONTACT_DETAIL; case CONTACT_EDITOR: - return fragment == CONTACTS_LIST || fragment == CONTACT_DETAIL || fragment == CONTACT_EDITOR; + return fragment == CONTACTS_LIST + || fragment == CONTACT_DETAIL + || fragment == CONTACT_EDITOR; case CHAT: return fragment == CHAT_LIST || fragment == CHAT; case GROUP_CHAT: - return fragment == CHAT_LIST || fragment == GROUP_CHAT || fragment == INFO_GROUP_CHAT || fragment == CREATE_CHAT; + return fragment == CHAT_LIST + || fragment == GROUP_CHAT + || fragment == INFO_GROUP_CHAT + || fragment == CREATE_CHAT; case MESSAGE_IMDN: return fragment == GROUP_CHAT || fragment == MESSAGE_IMDN; diff --git a/app/src/main/java/org/linphone/fragments/StatusFragment.java b/app/src/main/java/org/linphone/fragments/StatusFragment.java index fcc7e2671..dd67273b5 100644 --- a/app/src/main/java/org/linphone/fragments/StatusFragment.java +++ b/app/src/main/java/org/linphone/fragments/StatusFragment.java @@ -26,7 +26,6 @@ import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; -import androidx.core.content.ContextCompat; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; @@ -36,12 +35,11 @@ import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; - +import androidx.core.content.ContextCompat; +import org.linphone.LinphoneActivity; import org.linphone.LinphoneManager; -import org.linphone.settings.LinphonePreferences; import org.linphone.LinphoneService; import org.linphone.R; -import org.linphone.LinphoneActivity; import org.linphone.assistant.AssistantActivity; import org.linphone.call.CallActivity; import org.linphone.core.Call; @@ -53,6 +51,7 @@ import org.linphone.core.MediaEncryption; import org.linphone.core.ProxyConfig; import org.linphone.core.RegistrationState; import org.linphone.mediastream.Log; +import org.linphone.settings.LinphonePreferences; public class StatusFragment extends Fragment { private Handler refreshHandler = new Handler(); @@ -65,8 +64,8 @@ public class StatusFragment extends Fragment { private int mDisplayedQuality = -1; @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.status, container, false); statusText = view.findViewById(R.id.status_text); @@ -80,64 +79,71 @@ public class StatusFragment extends Fragment { // We create it once to not delay the first display populateSliderContent(); - mListener = new CoreListenerStub() { - @Override - public void onRegistrationStateChanged(final Core lc, final ProxyConfig proxy, final RegistrationState state, String smessage) { - if (!isAttached || !LinphoneService.isReady()) { - return; - } - - if (lc.getProxyConfigList() == null) { - statusLed.setImageResource(R.drawable.led_disconnected); - statusText.setText(getString(R.string.no_account)); - } else { - statusLed.setVisibility(View.VISIBLE); - } - - if (lc.getDefaultProxyConfig() != null && lc.getDefaultProxyConfig().equals(proxy)) { - statusLed.setImageResource(getStatusIconResource(state, true)); - statusText.setText(getStatusIconText(state)); - } else if (lc.getDefaultProxyConfig() == null) { - statusLed.setImageResource(getStatusIconResource(state, true)); - statusText.setText(getStatusIconText(state)); - } - - try { - statusText.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - lc.refreshRegisters(); + mListener = + new CoreListenerStub() { + @Override + public void onRegistrationStateChanged( + final Core lc, + final ProxyConfig proxy, + final RegistrationState state, + String smessage) { + if (!isAttached || !LinphoneService.isReady()) { + return; } - }); - } catch (IllegalStateException ise) { - } - } - @Override - public void onNotifyReceived(Core lc, Event ev, String eventName, Content content) { + if (lc.getProxyConfigList() == null) { + statusLed.setImageResource(R.drawable.led_disconnected); + statusText.setText(getString(R.string.no_account)); + } else { + statusLed.setVisibility(View.VISIBLE); + } - if (!content.getType().equals("application")) return; - if (!content.getSubtype().equals("simple-message-summary")) return; + if (lc.getDefaultProxyConfig() != null + && lc.getDefaultProxyConfig().equals(proxy)) { + statusLed.setImageResource(getStatusIconResource(state, true)); + statusText.setText(getStatusIconText(state)); + } else if (lc.getDefaultProxyConfig() == null) { + statusLed.setImageResource(getStatusIconResource(state, true)); + statusText.setText(getStatusIconText(state)); + } - if (content.getSize() == 0) return; + try { + statusText.setOnClickListener( + new OnClickListener() { + @Override + public void onClick(View v) { + lc.refreshRegisters(); + } + }); + } catch (IllegalStateException ise) { + } + } - int unreadCount = -1; - String data = content.getStringBuffer(); - String[] voiceMail = data.split("voice-message: "); - final String[] intToParse = voiceMail[1].split("/", 0); + @Override + public void onNotifyReceived( + Core lc, Event ev, String eventName, Content content) { - unreadCount = Integer.parseInt(intToParse[0]); - if (unreadCount > 0) { - voicemailCount.setText(unreadCount); - voicemail.setVisibility(View.VISIBLE); - voicemailCount.setVisibility(View.VISIBLE); - } else { - voicemail.setVisibility(View.GONE); - voicemailCount.setVisibility(View.GONE); - } - } + if (!content.getType().equals("application")) return; + if (!content.getSubtype().equals("simple-message-summary")) return; - }; + if (content.getSize() == 0) return; + + int unreadCount = -1; + String data = content.getStringBuffer(); + String[] voiceMail = data.split("voice-message: "); + final String[] intToParse = voiceMail[1].split("/", 0); + + unreadCount = Integer.parseInt(intToParse[0]); + if (unreadCount > 0) { + voicemailCount.setText(unreadCount); + voicemail.setVisibility(View.VISIBLE); + voicemailCount.setVisibility(View.VISIBLE); + } else { + voicemail.setVisibility(View.GONE); + voicemailCount.setVisibility(View.GONE); + } + } + }; isAttached = true; Activity activity = getActivity(); @@ -174,15 +180,15 @@ public class StatusFragment extends Fragment { isAttached = false; } - //NORMAL STATUS BAR + // NORMAL STATUS BAR private void populateSliderContent() { if (LinphoneManager.isInstanciated() && LinphoneManager.getLc() != null) { voicemailCount.setVisibility(View.GONE); if (isInCall && isAttached) { - //Call call = LinphoneManager.getLc().getCurrentCall(); - //initCallStatsRefresher(call, callStats); + // Call call = LinphoneManager.getLc().getCurrentCall(); + // initCallStatsRefresher(call, callStats); } else if (!isInCall) { voicemailCount.setVisibility(View.VISIBLE); } @@ -208,7 +214,13 @@ public class StatusFragment extends Fragment { private int getStatusIconResource(RegistrationState state, boolean isDefaultAccount) { try { Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull(); - boolean defaultAccountConnected = (isDefaultAccount && lc != null && lc.getDefaultProxyConfig() != null && lc.getDefaultProxyConfig().getState() == RegistrationState.Ok) || !isDefaultAccount; + boolean defaultAccountConnected = + (isDefaultAccount + && lc != null + && lc.getDefaultProxyConfig() != null + && lc.getDefaultProxyConfig().getState() + == RegistrationState.Ok) + || !isDefaultAccount; if (state == RegistrationState.Ok && defaultAccountConnected) { return R.drawable.led_connected; } else if (state == RegistrationState.Progress) { @@ -227,13 +239,15 @@ public class StatusFragment extends Fragment { private String getStatusIconText(RegistrationState state) { Context context = getActivity(); - if (!isAttached && LinphoneActivity.isInstanciated()) - context = LinphoneActivity.instance(); - else if (!isAttached && LinphoneService.isReady()) - context = LinphoneService.instance(); + if (!isAttached && LinphoneActivity.isInstanciated()) context = LinphoneActivity.instance(); + else if (!isAttached && LinphoneService.isReady()) context = LinphoneService.instance(); try { - if (state == RegistrationState.Ok && LinphoneManager.getLcIfManagerNotDestroyedOrNull().getDefaultProxyConfig().getState() == RegistrationState.Ok) { + if (state == RegistrationState.Ok + && LinphoneManager.getLcIfManagerNotDestroyedOrNull() + .getDefaultProxyConfig() + .getState() + == RegistrationState.Ok) { return context.getString(R.string.status_connected); } else if (state == RegistrationState.Progress) { return context.getString(R.string.status_in_progress); @@ -249,27 +263,28 @@ public class StatusFragment extends Fragment { return context.getString(R.string.status_not_connected); } - //INCALL STATUS BAR + // INCALL STATUS BAR private void startCallQuality() { callQuality.setVisibility(View.VISIBLE); - refreshHandler.postDelayed(mCallQualityUpdater = new Runnable() { - Call mCurrentCall = LinphoneManager.getLc() - .getCurrentCall(); + refreshHandler.postDelayed( + mCallQualityUpdater = + new Runnable() { + Call mCurrentCall = LinphoneManager.getLc().getCurrentCall(); - public void run() { - if (mCurrentCall == null) { - mCallQualityUpdater = null; - return; - } - float newQuality = mCurrentCall.getCurrentQuality(); - updateQualityOfSignalIcon(newQuality); + public void run() { + if (mCurrentCall == null) { + mCallQualityUpdater = null; + return; + } + float newQuality = mCurrentCall.getCurrentQuality(); + updateQualityOfSignalIcon(newQuality); - if (isInCall) { - refreshHandler.postDelayed(this, 1000); - } else - mCallQualityUpdater = null; - } - }, 1000); + if (isInCall) { + refreshHandler.postDelayed(this, 1000); + } else mCallQualityUpdater = null; + } + }, + 1000); } void updateQualityOfSignalIcon(float quality) { @@ -278,24 +293,19 @@ public class StatusFragment extends Fragment { if (iQuality == mDisplayedQuality) return; if (quality >= 4) // Good Quality { - callQuality.setImageResource( - R.drawable.call_quality_indicator_4); + callQuality.setImageResource(R.drawable.call_quality_indicator_4); } else if (quality >= 3) // Average quality { - callQuality.setImageResource( - R.drawable.call_quality_indicator_3); + callQuality.setImageResource(R.drawable.call_quality_indicator_3); } else if (quality >= 2) // Low quality { - callQuality.setImageResource( - R.drawable.call_quality_indicator_2); + callQuality.setImageResource(R.drawable.call_quality_indicator_2); } else if (quality >= 1) // Very low quality { - callQuality.setImageResource( - R.drawable.call_quality_indicator_1); + callQuality.setImageResource(R.drawable.call_quality_indicator_1); } else // Worst quality { - callQuality.setImageResource( - R.drawable.call_quality_indicator_0); + callQuality.setImageResource(R.drawable.call_quality_indicator_0); } mDisplayedQuality = iQuality; } @@ -326,7 +336,8 @@ public class StatusFragment extends Fragment { statusLed.setImageResource(R.drawable.led_disconnected); statusText.setText(getString(R.string.no_account)); } else { - statusLed.setImageResource(getStatusIconResource(lc.getDefaultProxyConfig().getState(), true)); + statusLed.setImageResource( + getStatusIconResource(lc.getDefaultProxyConfig().getState(), true)); statusText.setText(getStatusIconText(lc.getDefaultProxyConfig().getState())); } } @@ -357,15 +368,19 @@ public class StatusFragment extends Fragment { MediaEncryption mediaEncryption = call.getCurrentParams().getMediaEncryption(); if (isVideoEnabled) { - //background.setVisibility(View.GONE); + // background.setVisibility(View.GONE); } else { - //background.setVisibility(View.VISIBLE); + // background.setVisibility(View.VISIBLE); } encryption.setVisibility(View.VISIBLE); - if (mediaEncryption == MediaEncryption.SRTP || (mediaEncryption == MediaEncryption.ZRTP && call.getAuthenticationTokenVerified()) || mediaEncryption == MediaEncryption.DTLS) { + if (mediaEncryption == MediaEncryption.SRTP + || (mediaEncryption == MediaEncryption.ZRTP + && call.getAuthenticationTokenVerified()) + || mediaEncryption == MediaEncryption.DTLS) { encryption.setImageResource(R.drawable.security_ok); - } else if (mediaEncryption == MediaEncryption.ZRTP && !call.getAuthenticationTokenVerified()) { + } else if (mediaEncryption == MediaEncryption.ZRTP + && !call.getAuthenticationTokenVerified()) { encryption.setImageResource(R.drawable.security_pending); } else { encryption.setImageResource(R.drawable.security_ko); @@ -376,12 +391,13 @@ public class StatusFragment extends Fragment { } if (mediaEncryption == MediaEncryption.ZRTP) { - encryption.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - showZRTPDialog(call); - } - }); + encryption.setOnClickListener( + new OnClickListener() { + @Override + public void onClick(View v) { + showZRTPDialog(call); + } + }); } else { encryption.setOnClickListener(null); } @@ -414,7 +430,10 @@ public class StatusFragment extends Fragment { Drawable d = new ColorDrawable(ContextCompat.getColor(getActivity(), R.color.colorC)); d.setAlpha(200); ZRTPdialog.setContentView(R.layout.dialog); - ZRTPdialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT); + ZRTPdialog.getWindow() + .setLayout( + WindowManager.LayoutParams.MATCH_PARENT, + WindowManager.LayoutParams.MATCH_PARENT); ZRTPdialog.getWindow().setBackgroundDrawable(d); String zrtpToRead, zrtpToListen; @@ -450,29 +469,31 @@ public class StatusFragment extends Fragment { icon.setVisibility(View.VISIBLE); icon.setImageResource(R.drawable.security_2_indicator); - delete.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View view) { - if (call != null) { - call.setAuthenticationTokenVerified(false); - if (encryption != null) { - encryption.setImageResource(R.drawable.security_ko); + delete.setOnClickListener( + new OnClickListener() { + @Override + public void onClick(View view) { + if (call != null) { + call.setAuthenticationTokenVerified(false); + if (encryption != null) { + encryption.setImageResource(R.drawable.security_ko); + } + } + ZRTPdialog.dismiss(); } - } - ZRTPdialog.dismiss(); - } - }); + }); - accept.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View view) { - call.setAuthenticationTokenVerified(true); - if (encryption != null) { - encryption.setImageResource(R.drawable.security_ok); - } - ZRTPdialog.dismiss(); - } - }); + accept.setOnClickListener( + new OnClickListener() { + @Override + public void onClick(View view) { + call.setAuthenticationTokenVerified(true); + if (encryption != null) { + encryption.setImageResource(R.drawable.security_ok); + } + ZRTPdialog.dismiss(); + } + }); ZRTPdialog.show(); } } diff --git a/app/src/main/java/org/linphone/history/HistoryAdapter.java b/app/src/main/java/org/linphone/history/HistoryAdapter.java index 520ac4622..84c2aaf0d 100644 --- a/app/src/main/java/org/linphone/history/HistoryAdapter.java +++ b/app/src/main/java/org/linphone/history/HistoryAdapter.java @@ -1,53 +1,55 @@ package org.linphone.history; /* - HistoryAdapter.java - Copyright (C) 2018 Belledonne Communications, Grenoble, France +HistoryAdapter.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 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. +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. - */ +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.annotation.SuppressLint; import android.content.Context; -import androidx.annotation.NonNull; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; - -import org.linphone.utils.LinphoneUtils; -import org.linphone.R; +import androidx.annotation.NonNull; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.List; import org.linphone.LinphoneActivity; +import org.linphone.R; import org.linphone.contacts.ContactsManager; import org.linphone.contacts.LinphoneContact; import org.linphone.core.Address; import org.linphone.core.Call; import org.linphone.core.CallLog; -import org.linphone.views.ContactAvatar; +import org.linphone.utils.LinphoneUtils; import org.linphone.utils.SelectableAdapter; import org.linphone.utils.SelectableHelper; - -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.List; +import org.linphone.views.ContactAvatar; public class HistoryAdapter extends SelectableAdapter { private List mLogs; private Context mContext; private HistoryViewHolder.ClickListener clickListener; - public HistoryAdapter(Context aContext, List logs, HistoryViewHolder.ClickListener listener, SelectableHelper helper) { + public HistoryAdapter( + Context aContext, + List logs, + HistoryViewHolder.ClickListener listener, + SelectableHelper helper) { super(helper); this.mLogs = logs; this.mContext = aContext; @@ -65,9 +67,10 @@ public class HistoryAdapter extends SelectableAdapter { @NonNull @Override public HistoryViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { - View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.history_cell, parent, false); + View v = + LayoutInflater.from(parent.getContext()) + .inflate(R.layout.history_cell, parent, false); return new HistoryViewHolder(v, clickListener); - } @Override @@ -130,18 +133,17 @@ public class HistoryAdapter extends SelectableAdapter { } holder.detail.setVisibility(isEditionEnabled() ? View.INVISIBLE : View.VISIBLE); - holder.detail.setOnClickListener(!isEditionEnabled() ? - new View.OnClickListener() { - @Override - public void onClick(View v) { - if (LinphoneActivity.isInstanciated()) { - LinphoneActivity.instance().displayHistoryDetail(sipUri, log); + holder.detail.setOnClickListener( + !isEditionEnabled() + ? new View.OnClickListener() { + @Override + public void onClick(View v) { + if (LinphoneActivity.isInstanciated()) { + LinphoneActivity.instance().displayHistoryDetail(sipUri, log); + } + } } - } - } - : - null - ); + : null); } @Override @@ -157,7 +159,9 @@ public class HistoryAdapter extends SelectableAdapter { } else if (isYesterday(cal)) { return mContext.getString(R.string.yesterday); } else { - dateFormat = new SimpleDateFormat(mContext.getResources().getString(R.string.history_date_format)); + dateFormat = + new SimpleDateFormat( + mContext.getResources().getString(R.string.history_date_format)); } return dateFormat.format(cal.getTime()); @@ -168,9 +172,9 @@ public class HistoryAdapter extends SelectableAdapter { return false; } - return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) && - cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && - cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR)); + return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) + && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) + && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR)); } private boolean isToday(Calendar cal) { @@ -182,4 +186,4 @@ public class HistoryAdapter extends SelectableAdapter { yesterday.roll(Calendar.DAY_OF_MONTH, -1); return isSameDay(cal, yesterday); } -} \ No newline at end of file +} diff --git a/app/src/main/java/org/linphone/history/HistoryDetailFragment.java b/app/src/main/java/org/linphone/history/HistoryDetailFragment.java index 4bd22f9f1..fcb9598c9 100644 --- a/app/src/main/java/org/linphone/history/HistoryDetailFragment.java +++ b/app/src/main/java/org/linphone/history/HistoryDetailFragment.java @@ -29,14 +29,9 @@ import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; - -import org.linphone.LinphoneManager; -import org.linphone.fragments.FragmentsAvailable; -import org.linphone.settings.LinphonePreferences; -import org.linphone.utils.ImageUtils; -import org.linphone.utils.LinphoneUtils; -import org.linphone.R; import org.linphone.LinphoneActivity; +import org.linphone.LinphoneManager; +import org.linphone.R; import org.linphone.contacts.ContactsManager; import org.linphone.contacts.LinphoneContact; import org.linphone.core.Address; @@ -47,6 +42,9 @@ import org.linphone.core.Factory; import org.linphone.core.ProxyConfig; import org.linphone.fragments.FragmentsAvailable; import org.linphone.mediastream.Log; +import org.linphone.settings.LinphonePreferences; +import org.linphone.utils.ImageUtils; +import org.linphone.utils.LinphoneUtils; public class HistoryDetailFragment extends Fragment implements OnClickListener { private ImageView dialBack, chat, addToContacts, goToContact, back; @@ -60,8 +58,8 @@ public class HistoryDetailFragment extends Fragment implements OnClickListener { private ChatRoomListenerStub mChatRoomCreationListener; @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { sipUri = getArguments().getString("SipUri"); displayName = getArguments().getString("DisplayName"); pictureUri = getArguments().getString("PictureUri"); @@ -107,19 +105,24 @@ public class HistoryDetailFragment extends Fragment implements OnClickListener { displayHistory(status, callTime, callDate); - mChatRoomCreationListener = new ChatRoomListenerStub() { - @Override - public void onStateChanged(ChatRoom cr, ChatRoom.State newState) { - if (newState == ChatRoom.State.Created) { - mWaitLayout.setVisibility(View.GONE); - LinphoneActivity.instance().goToChat(cr.getPeerAddress().asStringUriOnly(), null); - } else if (newState == ChatRoom.State.CreationFailed) { - mWaitLayout.setVisibility(View.GONE); - LinphoneActivity.instance().displayChatRoomError(); - Log.e("Group chat room for address " + cr.getPeerAddress() + " has failed !"); - } - } - }; + mChatRoomCreationListener = + new ChatRoomListenerStub() { + @Override + public void onStateChanged(ChatRoom cr, ChatRoom.State newState) { + if (newState == ChatRoom.State.Created) { + mWaitLayout.setVisibility(View.GONE); + LinphoneActivity.instance() + .goToChat(cr.getPeerAddress().asStringUriOnly(), null); + } else if (newState == ChatRoom.State.CreationFailed) { + mWaitLayout.setVisibility(View.GONE); + LinphoneActivity.instance().displayChatRoomError(); + Log.e( + "Group chat room for address " + + cr.getPeerAddress() + + " has failed !"); + } + } + }; return view; } @@ -143,7 +146,9 @@ public class HistoryDetailFragment extends Fragment implements OnClickListener { time.setText(callTime == null ? "" : callTime); Long longDate = Long.parseLong(callDate); - date.setText(LinphoneUtils.timestampToHumanDate(getActivity(), longDate, getString(R.string.history_detail_date_format))); + date.setText( + LinphoneUtils.timestampToHumanDate( + getActivity(), longDate, getString(R.string.history_detail_date_format))); Address lAddress = Factory.instance().createAddress(sipUri); @@ -152,22 +157,39 @@ public class HistoryDetailFragment extends Fragment implements OnClickListener { contact = ContactsManager.getInstance().findContactFromAddress(lAddress); if (contact != null) { contactName.setText(contact.getFullName()); - ImageUtils.setImagePictureFromUri(view.getContext(), contactPicture, contact.getPhotoUri(), contact.getThumbnailUri()); + ImageUtils.setImagePictureFromUri( + view.getContext(), + contactPicture, + contact.getPhotoUri(), + contact.getThumbnailUri()); addToContacts.setVisibility(View.GONE); goToContact.setVisibility(View.VISIBLE); } else { - contactName.setText(displayName == null ? LinphoneUtils.getAddressDisplayName(sipUri) : displayName); - contactPicture.setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap()); + contactName.setText( + displayName == null + ? LinphoneUtils.getAddressDisplayName(sipUri) + : displayName); + contactPicture.setImageBitmap( + ContactsManager.getInstance().getDefaultAvatarBitmap()); addToContacts.setVisibility(View.VISIBLE); goToContact.setVisibility(View.GONE); } } else { contactAddress.setText(sipUri); - contactName.setText(displayName == null ? LinphoneUtils.getAddressDisplayName(sipUri) : displayName); + contactName.setText( + displayName == null + ? LinphoneUtils.getAddressDisplayName(sipUri) + : displayName); } } - public void changeDisplayedHistory(String sipUri, String displayName, String pictureUri, String status, String callTime, String callDate) { + public void changeDisplayedHistory( + String sipUri, + String displayName, + String pictureUri, + String status, + String callTime, + String callDate) { if (displayName == null) { displayName = LinphoneUtils.getUsernameFromAddress(sipUri); } @@ -195,23 +217,32 @@ public class HistoryDetailFragment extends Fragment implements OnClickListener { getFragmentManager().popBackStackImmediate(); } if (id == R.id.call) { - LinphoneActivity.instance().setAddresGoToDialerAndCall(sipUri, displayName, pictureUri == null ? null : Uri.parse(pictureUri)); + LinphoneActivity.instance() + .setAddresGoToDialerAndCall( + sipUri, displayName, pictureUri == null ? null : Uri.parse(pictureUri)); } else if (id == R.id.chat) { Core lc = LinphoneManager.getLc(); Address participant = Factory.instance().createAddress(sipUri); - ChatRoom room = lc.findOneToOneChatRoom(lc.getDefaultProxyConfig().getContact(), participant, false); + ChatRoom room = + lc.findOneToOneChatRoom( + lc.getDefaultProxyConfig().getContact(), participant, false); if (room != null) { LinphoneActivity.instance().goToChat(room.getPeerAddress().asStringUriOnly(), null); } else { ProxyConfig lpc = lc.getDefaultProxyConfig(); - if (lpc != null && lpc.getConferenceFactoryUri() != null && !LinphonePreferences.instance().useBasicChatRoomFor1To1()) { + if (lpc != null + && lpc.getConferenceFactoryUri() != null + && !LinphonePreferences.instance().useBasicChatRoomFor1To1()) { mWaitLayout.setVisibility(View.VISIBLE); - mChatRoom = lc.createClientGroupChatRoom(getString(R.string.dummy_group_chat_subject), true); + mChatRoom = + lc.createClientGroupChatRoom( + getString(R.string.dummy_group_chat_subject), true); mChatRoom.addListener(mChatRoomCreationListener); mChatRoom.addParticipant(participant); } else { room = lc.getChatRoom(participant); - LinphoneActivity.instance().goToChat(room.getPeerAddress().asStringUriOnly(), null); + LinphoneActivity.instance() + .goToChat(room.getPeerAddress().asStringUriOnly(), null); } } } else if (id == R.id.add_contact) { diff --git a/app/src/main/java/org/linphone/history/HistoryListFragment.java b/app/src/main/java/org/linphone/history/HistoryListFragment.java index d076a84e2..ea17d397a 100644 --- a/app/src/main/java/org/linphone/history/HistoryListFragment.java +++ b/app/src/main/java/org/linphone/history/HistoryListFragment.java @@ -22,9 +22,6 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import android.app.Fragment; import android.content.Context; import android.os.Bundle; -import androidx.recyclerview.widget.DividerItemDecoration; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; @@ -33,24 +30,29 @@ import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ImageView; import android.widget.TextView; - +import androidx.recyclerview.widget.DividerItemDecoration; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.linphone.LinphoneActivity; import org.linphone.LinphoneManager; import org.linphone.R; -import org.linphone.LinphoneActivity; -import org.linphone.fragments.FragmentsAvailable; import org.linphone.contacts.ContactsManager; import org.linphone.contacts.ContactsUpdatedListener; import org.linphone.core.Address; import org.linphone.core.Call; import org.linphone.core.CallLog; +import org.linphone.fragments.FragmentsAvailable; import org.linphone.utils.SelectableHelper; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -public class HistoryListFragment extends Fragment implements OnClickListener, OnItemClickListener, HistoryViewHolder.ClickListener, ContactsUpdatedListener, SelectableHelper.DeleteListener { +public class HistoryListFragment extends Fragment + implements OnClickListener, + OnItemClickListener, + HistoryViewHolder.ClickListener, + ContactsUpdatedListener, + SelectableHelper.DeleteListener { private RecyclerView historyList; private TextView noCallHistory, noMissedCallHistory; private ImageView missedCalls, allCalls; @@ -63,8 +65,8 @@ public class HistoryListFragment extends Fragment implements OnClickListener, On private SelectableHelper mSelectionHelper; @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.history, container, false); mContext = getActivity().getApplicationContext(); mSelectionHelper = new SelectableHelper(view, this); @@ -76,9 +78,10 @@ public class HistoryListFragment extends Fragment implements OnClickListener, On mLayoutManager = new LinearLayoutManager(mContext); historyList.setLayoutManager(mLayoutManager); - //Divider between items - DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(historyList.getContext(), - mLayoutManager.getOrientation()); + // Divider between items + DividerItemDecoration dividerItemDecoration = + new DividerItemDecoration( + historyList.getContext(), mLayoutManager.getOrientation()); dividerItemDecoration.setDrawable(mContext.getResources().getDrawable(R.drawable.divider)); historyList.addItemDecoration(dividerItemDecoration); @@ -133,7 +136,7 @@ public class HistoryListFragment extends Fragment implements OnClickListener, On removeNotMissedCallsFromLogs(); noCallHistory.setVisibility(View.GONE); noMissedCallHistory.setVisibility(View.GONE); - + if (mLogs.isEmpty()) { if (mOnlyDisplayMissedCalls) { noMissedCallHistory.setVisibility(View.VISIBLE); @@ -160,7 +163,9 @@ public class HistoryListFragment extends Fragment implements OnClickListener, On mLogs = Arrays.asList(LinphoneManager.getLc().getCallLogs()); hideHistoryListAndDisplayMessageIfEmpty(); - mHistoryAdapter = new HistoryAdapter(getActivity().getApplicationContext(), mLogs, this, mSelectionHelper); + mHistoryAdapter = + new HistoryAdapter( + getActivity().getApplicationContext(), mLogs, this, mSelectionHelper); historyList.setAdapter(mHistoryAdapter); mSelectionHelper.setAdapter(mHistoryAdapter); mSelectionHelper.setDialogMessage(R.string.chat_room_delete_dialog); @@ -174,8 +179,9 @@ public class HistoryListFragment extends Fragment implements OnClickListener, On @Override public void onContactsUpdated() { - if (!LinphoneActivity.isInstanciated() || LinphoneActivity.instance().getCurrentFragment() != FragmentsAvailable.HISTORY_LIST) - return; + if (!LinphoneActivity.isInstanciated() + || LinphoneActivity.instance().getCurrentFragment() + != FragmentsAvailable.HISTORY_LIST) return; HistoryAdapter adapter = (HistoryAdapter) historyList.getAdapter(); if (adapter != null) { adapter.notifyDataSetChanged(); @@ -240,7 +246,9 @@ public class HistoryListFragment extends Fragment implements OnClickListener, On } else { address = log.getToAddress(); } - LinphoneActivity.instance().setAddresGoToDialerAndCall(address.asStringUriOnly(), address.getDisplayName(), null); + LinphoneActivity.instance() + .setAddresGoToDialerAndCall( + address.asStringUriOnly(), address.getDisplayName(), null); } } } @@ -253,4 +261,4 @@ public class HistoryListFragment extends Fragment implements OnClickListener, On mHistoryAdapter.toggleSelection(position); return true; } -} \ No newline at end of file +} diff --git a/app/src/main/java/org/linphone/history/HistoryViewHolder.java b/app/src/main/java/org/linphone/history/HistoryViewHolder.java index 5a21dfcea..d74fb5a61 100644 --- a/app/src/main/java/org/linphone/history/HistoryViewHolder.java +++ b/app/src/main/java/org/linphone/history/HistoryViewHolder.java @@ -1,35 +1,35 @@ package org.linphone.history; /* - HistoryViewHolder.java - Copyright (C) 2018 Belledonne Communications, Grenoble, France +HistoryViewHolder.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 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. +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. - */ +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 androidx.recyclerview.widget.RecyclerView; 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 HistoryViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener { +public class HistoryViewHolder extends RecyclerView.ViewHolder + implements View.OnClickListener, View.OnLongClickListener { public TextView contact; public ImageView detail; public CheckBox select; @@ -75,4 +75,4 @@ public class HistoryViewHolder extends RecyclerView.ViewHolder implements View.O boolean onItemLongClicked(int position); } -} \ No newline at end of file +} diff --git a/app/src/main/java/org/linphone/notifications/NotifiableMessage.java b/app/src/main/java/org/linphone/notifications/NotifiableMessage.java index 47b21e552..33579585b 100644 --- a/app/src/main/java/org/linphone/notifications/NotifiableMessage.java +++ b/app/src/main/java/org/linphone/notifications/NotifiableMessage.java @@ -30,7 +30,8 @@ public class NotifiableMessage { Uri mFilePath; String mFileMime; - public NotifiableMessage(String message, String sender, long time, Uri filePath, String fileMime) { + public NotifiableMessage( + String message, String sender, long time, Uri filePath, String fileMime) { mMessage = message; mSender = sender; mTime = time; diff --git a/app/src/main/java/org/linphone/notifications/NotificationBroadcastReceiver.java b/app/src/main/java/org/linphone/notifications/NotificationBroadcastReceiver.java index 4e9cc6151..d4c682874 100644 --- a/app/src/main/java/org/linphone/notifications/NotificationBroadcastReceiver.java +++ b/app/src/main/java/org/linphone/notifications/NotificationBroadcastReceiver.java @@ -26,11 +26,10 @@ import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; - +import org.linphone.LinphoneActivity; import org.linphone.LinphoneManager; import org.linphone.LinphoneService; import org.linphone.R; -import org.linphone.LinphoneActivity; import org.linphone.compatibility.Compatibility; import org.linphone.core.Address; import org.linphone.core.Call; @@ -38,7 +37,6 @@ import org.linphone.core.ChatMessage; import org.linphone.core.ChatMessageListenerStub; import org.linphone.core.ChatRoom; import org.linphone.core.Core; -import org.linphone.core.ProxyConfig; import org.linphone.mediastream.Log; public class NotificationBroadcastReceiver extends BroadcastReceiver { @@ -54,17 +52,20 @@ public class NotificationBroadcastReceiver extends BroadcastReceiver { onError(context, notifId); return; } - String remoteSipAddr = LinphoneService.instance().getNotificationManager().getSipUriForNotificationId(notifId); + String remoteSipAddr = + LinphoneService.instance() + .getNotificationManager() + .getSipUriForNotificationId(notifId); Core core = LinphoneManager.getLc(); - if (core == null) { + if (core == null) { Log.e("Couldn't get Core instance"); onError(context, notifId); return; } Address remoteAddr = core.interpretUrl(remoteSipAddr); - if (remoteAddr == null) { + if (remoteAddr == null) { Log.e("Couldn't interpret remote address " + remoteSipAddr); onError(context, notifId); return; @@ -78,33 +79,46 @@ public class NotificationBroadcastReceiver extends BroadcastReceiver { } ChatRoom room = core.findChatRoom(remoteAddr, localAddr); - if (room == null) { - Log.e("Couldn't find chat room for remote address " + remoteSipAddr + " and local address " + localyIdentity); + if (room == null) { + Log.e( + "Couldn't find chat room for remote address " + + remoteSipAddr + + " and local address " + + localyIdentity); onError(context, notifId); return; } room.markAsRead(); if (LinphoneActivity.isInstanciated()) { - LinphoneActivity.instance().displayMissedChats(LinphoneManager.getInstance().getUnreadMessageCount()); + LinphoneActivity.instance() + .displayMissedChats(LinphoneManager.getInstance().getUnreadMessageCount()); } ChatMessage msg = room.createMessage(reply); msg.send(); - msg.setListener(new ChatMessageListenerStub() { - @Override - public void onMsgStateChanged(ChatMessage msg, ChatMessage.State state) { - if (state == ChatMessage.State.Delivered) { - Notification replied = Compatibility.createRepliedNotification(context, reply); - LinphoneService.instance().getNotificationManager().sendNotification(notifId, replied); - } else if (state == ChatMessage.State.NotDelivered) { - Log.e("Couldn't send reply, message is not delivered"); - onError(context, notifId); - } - } - }); - } else if (intent.getAction() == Compatibility.INTENT_ANSWER_CALL_NOTIF_ACTION || intent.getAction() == Compatibility.INTENT_HANGUP_CALL_NOTIF_ACTION) { - String remoteAddr = LinphoneService.instance().getNotificationManager().getSipUriForCallNotificationId(notifId); + msg.setListener( + new ChatMessageListenerStub() { + @Override + public void onMsgStateChanged(ChatMessage msg, ChatMessage.State state) { + if (state == ChatMessage.State.Delivered) { + Notification replied = + Compatibility.createRepliedNotification(context, reply); + LinphoneService.instance() + .getNotificationManager() + .sendNotification(notifId, replied); + } else if (state == ChatMessage.State.NotDelivered) { + Log.e("Couldn't send reply, message is not delivered"); + onError(context, notifId); + } + } + }); + } else if (intent.getAction() == Compatibility.INTENT_ANSWER_CALL_NOTIF_ACTION + || intent.getAction() == Compatibility.INTENT_HANGUP_CALL_NOTIF_ACTION) { + String remoteAddr = + LinphoneService.instance() + .getNotificationManager() + .getSipUriForCallNotificationId(notifId); Core core = LinphoneManager.getLc(); if (core == null) { @@ -126,7 +140,8 @@ public class NotificationBroadcastReceiver extends BroadcastReceiver { } private void onError(Context context, int notifId) { - Notification replyError = Compatibility.createRepliedNotification(context, context.getString(R.string.error)); + Notification replyError = + Compatibility.createRepliedNotification(context, context.getString(R.string.error)); LinphoneService.instance().getNotificationManager().sendNotification(notifId, replyError); } diff --git a/app/src/main/java/org/linphone/notifications/NotificationsManager.java b/app/src/main/java/org/linphone/notifications/NotificationsManager.java index 092f43bc2..c765a7c36 100644 --- a/app/src/main/java/org/linphone/notifications/NotificationsManager.java +++ b/app/src/main/java/org/linphone/notifications/NotificationsManager.java @@ -19,6 +19,8 @@ along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ +import static android.content.Context.NOTIFICATION_SERVICE; + import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; @@ -27,24 +29,20 @@ import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; - -import org.linphone.LinphoneManager; -import org.linphone.settings.LinphonePreferences; -import org.linphone.LinphoneService; -import org.linphone.utils.ImageUtils; -import org.linphone.utils.LinphoneUtils; -import org.linphone.R; +import java.util.HashMap; import org.linphone.LinphoneActivity; +import org.linphone.LinphoneManager; +import org.linphone.LinphoneService; +import org.linphone.R; import org.linphone.compatibility.Compatibility; import org.linphone.contacts.ContactsManager; import org.linphone.contacts.LinphoneContact; import org.linphone.core.Address; import org.linphone.core.Call; import org.linphone.mediastream.Version; - -import java.util.HashMap; - -import static android.content.Context.NOTIFICATION_SERVICE; +import org.linphone.settings.LinphonePreferences; +import org.linphone.utils.ImageUtils; +import org.linphone.utils.LinphoneUtils; public class NotificationsManager { private static final int SERVICE_NOTIF_ID = 1; @@ -69,10 +67,11 @@ public class NotificationsManager { Compatibility.createNotificationChannels(mContext); - Intent notifIntent = new Intent(mContext, LinphoneService.instance().getIncomingReceivedActivity()); + Intent notifIntent = + new Intent(mContext, LinphoneService.instance().getIncomingReceivedActivity()); notifIntent.putExtra("Notification", true); - //Disable service notification for Android O + // Disable service notification for Android O if (Version.sdkAboveOrEqual(Version.API26_O_80)) { LinphonePreferences.instance().setServiceNotificationVisibility(false); } @@ -83,10 +82,20 @@ public class NotificationsManager { } catch (Exception e) { } - PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, notifIntent, PendingIntent.FLAG_UPDATE_CURRENT); - mServiceNotification = Compatibility.createNotification(mContext, mContext.getString(R.string.service_name), "", - R.drawable.linphone_notification_icon, R.mipmap.ic_launcher, bm, pendingIntent, true, - Notification.PRIORITY_MIN); + PendingIntent pendingIntent = + PendingIntent.getActivity( + mContext, 0, notifIntent, PendingIntent.FLAG_UPDATE_CURRENT); + mServiceNotification = + Compatibility.createNotification( + mContext, + mContext.getString(R.string.service_name), + "", + R.drawable.linphone_notification_icon, + R.mipmap.ic_launcher, + bm, + pendingIntent, + true, + Notification.PRIORITY_MIN); if (isServiceNotificationDisplayed()) { startForeground(); @@ -130,15 +139,27 @@ public class NotificationsManager { return null; } - public void displayGroupChatMessageNotification(String subject, String conferenceAddress, String fromName, Uri fromPictureUri, String message, Address localIdentity, long timestamp, Uri filePath, String fileMime) { + public void displayGroupChatMessageNotification( + String subject, + String conferenceAddress, + String fromName, + Uri fromPictureUri, + String message, + Address localIdentity, + long timestamp, + Uri filePath, + String fileMime) { Intent notifIntent = new Intent(mContext, LinphoneActivity.class); notifIntent.putExtra("GoToChat", true); notifIntent.putExtra("ChatContactSipUri", conferenceAddress); - PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, notifIntent, PendingIntent.FLAG_UPDATE_CURRENT); + PendingIntent pendingIntent = + PendingIntent.getActivity( + mContext, 0, notifIntent, PendingIntent.FLAG_UPDATE_CURRENT); Bitmap bm = ImageUtils.getRoundBitmapFromUri(mContext, fromPictureUri); Notifiable notif = mChatNotifMap.get(conferenceAddress); - NotifiableMessage notifMessage = new NotifiableMessage(message, fromName, timestamp, filePath, fileMime); + NotifiableMessage notifMessage = + new NotifiableMessage(message, fromName, timestamp, filePath, fileMime); if (notif == null) { notif = new Notifiable(mLastNotificationId); mLastNotificationId += 1; @@ -152,16 +173,34 @@ public class NotificationsManager { notif.setMyself(LinphoneUtils.getAddressDisplayName(localIdentity)); notif.setLocalIdentity(localIdentity.asString()); - Notification notification = Compatibility.createMessageNotification(mContext, notif, subject, - mContext.getString(R.string.group_chat_notif).replace("%1", fromName).replace("%2", message), bm, pendingIntent); + Notification notification = + Compatibility.createMessageNotification( + mContext, + notif, + subject, + mContext.getString(R.string.group_chat_notif) + .replace("%1", fromName) + .replace("%2", message), + bm, + pendingIntent); sendNotification(notif.getNotificationId(), notification); } - public void displayMessageNotification(String fromSipUri, String fromName, Uri fromPictureUri, String message, Address localIdentity, long timestamp, Uri filePath, String fileMime) { + public void displayMessageNotification( + String fromSipUri, + String fromName, + Uri fromPictureUri, + String message, + Address localIdentity, + long timestamp, + Uri filePath, + String fileMime) { Intent notifIntent = new Intent(mContext, LinphoneActivity.class); notifIntent.putExtra("GoToChat", true); notifIntent.putExtra("ChatContactSipUri", fromSipUri); - PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, notifIntent, PendingIntent.FLAG_UPDATE_CURRENT); + PendingIntent pendingIntent = + PendingIntent.getActivity( + mContext, 0, notifIntent, PendingIntent.FLAG_UPDATE_CURRENT); if (fromName == null) { fromName = fromSipUri; @@ -169,7 +208,8 @@ public class NotificationsManager { Bitmap bm = ImageUtils.getRoundBitmapFromUri(mContext, fromPictureUri); Notifiable notif = mChatNotifMap.get(fromSipUri); - NotifiableMessage notifMessage = new NotifiableMessage(message, fromName, timestamp, filePath, fileMime); + NotifiableMessage notifMessage = + new NotifiableMessage(message, fromName, timestamp, filePath, fileMime); if (notif == null) { notif = new Notifiable(mLastNotificationId); mLastNotificationId += 1; @@ -182,19 +222,26 @@ public class NotificationsManager { notif.setMyself(LinphoneUtils.getAddressDisplayName(localIdentity)); notif.setLocalIdentity(localIdentity.asString()); - Notification notification = Compatibility.createMessageNotification(mContext, notif, fromName, message, bm, pendingIntent); + Notification notification = + Compatibility.createMessageNotification( + mContext, notif, fromName, message, bm, pendingIntent); sendNotification(notif.getNotificationId(), notification); } public void displayMissedCallNotification(Call call) { Intent missedCallNotifIntent = new Intent(mContext, LinphoneActivity.class); missedCallNotifIntent.putExtra("GoToHistory", true); - PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, missedCallNotifIntent, PendingIntent.FLAG_UPDATE_CURRENT); + PendingIntent pendingIntent = + PendingIntent.getActivity( + mContext, 0, missedCallNotifIntent, PendingIntent.FLAG_UPDATE_CURRENT); - int missedCallCount = LinphoneManager.getLcIfManagerNotDestroyedOrNull().getMissedCallsCount(); + int missedCallCount = + LinphoneManager.getLcIfManagerNotDestroyedOrNull().getMissedCallsCount(); String body; if (missedCallCount > 1) { - body = mContext.getString(R.string.missed_calls_notif_body).replace("%i", String.valueOf(missedCallCount)); + body = + mContext.getString(R.string.missed_calls_notif_body) + .replace("%i", String.valueOf(missedCallCount)); } else { Address address = call.getRemoteAddress(); LinphoneContact c = ContactsManager.getInstance().findContactFromAddress(address); @@ -208,14 +255,22 @@ public class NotificationsManager { } } - Notification notif = Compatibility.createMissedCallNotification(mContext, mContext.getString(R.string.missed_calls_notif_title), body, pendingIntent); + Notification notif = + Compatibility.createMissedCallNotification( + mContext, + mContext.getString(R.string.missed_calls_notif_title), + body, + pendingIntent); sendNotification(MISSED_CALLS_NOTIF_ID, notif); } public void displayCallNotification(Call call) { if (call == null) return; - Intent callNotifIntent = new Intent(mContext, LinphoneService.instance().getIncomingReceivedActivity()); - PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, callNotifIntent, PendingIntent.FLAG_UPDATE_CURRENT); + Intent callNotifIntent = + new Intent(mContext, LinphoneService.instance().getIncomingReceivedActivity()); + PendingIntent pendingIntent = + PendingIntent.getActivity( + mContext, 0, callNotifIntent, PendingIntent.FLAG_UPDATE_CURRENT); Address address = call.getRemoteAddress(); String addressAsString = address.asStringUriOnly(); @@ -264,10 +319,20 @@ public class NotificationsManager { Bitmap bm = ImageUtils.getRoundBitmapFromUri(mContext, pictureUri); String name = LinphoneUtils.getAddressDisplayName(address); - boolean showAnswerAction = call.getState() == Call.State.IncomingReceived || call.getState() == Call.State.IncomingEarlyMedia; - Notification notification = Compatibility.createInCallNotification(mContext, notif.getNotificationId(), - showAnswerAction, mContext.getString(R.string.service_name), - mContext.getString(notificationTextId), iconId, bm, name, pendingIntent); + boolean showAnswerAction = + call.getState() == Call.State.IncomingReceived + || call.getState() == Call.State.IncomingEarlyMedia; + Notification notification = + Compatibility.createInCallNotification( + mContext, + notif.getNotificationId(), + showAnswerAction, + mContext.getString(R.string.service_name), + mContext.getString(notificationTextId), + iconId, + bm, + name, + pendingIntent); sendNotification(notif.getNotificationId(), notification); } @@ -283,9 +348,16 @@ public class NotificationsManager { public void displayInappNotification(String message) { Intent notifIntent = new Intent(mContext, LinphoneActivity.class); notifIntent.putExtra("GoToInapp", true); - PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, notifIntent, PendingIntent.FLAG_UPDATE_CURRENT); + PendingIntent pendingIntent = + PendingIntent.getActivity( + mContext, 0, notifIntent, PendingIntent.FLAG_UPDATE_CURRENT); - Notification notif = Compatibility.createSimpleNotification(mContext, mContext.getString(R.string.inapp_notification_title), message, pendingIntent); + Notification notif = + Compatibility.createSimpleNotification( + mContext, + mContext.getString(R.string.inapp_notification_title), + message, + pendingIntent); sendNotification(IN_APP_NOTIF_ID, notif); } } diff --git a/app/src/main/java/org/linphone/purchase/InAppPurchaseActivity.java b/app/src/main/java/org/linphone/purchase/InAppPurchaseActivity.java index f8434f6d5..73ff281a5 100644 --- a/app/src/main/java/org/linphone/purchase/InAppPurchaseActivity.java +++ b/app/src/main/java/org/linphone/purchase/InAppPurchaseActivity.java @@ -29,17 +29,16 @@ import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.Toast; - -import org.linphone.settings.LinphonePreferences; +import java.util.ArrayList; +import java.util.List; import org.linphone.R; import org.linphone.mediastream.Log; +import org.linphone.settings.LinphonePreferences; import org.linphone.xmlrpc.XmlRpcHelper; import org.linphone.xmlrpc.XmlRpcListenerBase; -import java.util.ArrayList; -import java.util.List; - -public class InAppPurchaseActivity extends Activity implements InAppPurchaseListener, OnClickListener { +public class InAppPurchaseActivity extends Activity + implements InAppPurchaseListener, OnClickListener { private static InAppPurchaseActivity instance; private InAppPurchaseHelper inAppPurchaseHelper; private ImageView cancel, back; @@ -49,6 +48,10 @@ public class InAppPurchaseActivity extends Activity implements InAppPurchaseList private Fragment fragment; private Handler mHandler = new Handler(); + public static InAppPurchaseActivity instance() { + return instance; + } + @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -92,12 +95,10 @@ public class InAppPurchaseActivity extends Activity implements InAppPurchaseList inAppPurchaseHelper.purchaseItemAsync(item.getId(), username); } - public String getGmailAccount() { return inAppPurchaseHelper.getGmailAccount(); } - @Override protected void onDestroy() { instance = null; @@ -122,22 +123,18 @@ public class InAppPurchaseActivity extends Activity implements InAppPurchaseList return null; } - public static InAppPurchaseActivity instance() { - return instance; - } - @Override public void onServiceAvailableForQueries() { - //email.setText(inAppPurchaseHelper.getGmailAccount()); - //email.setEnabled(false); + // email.setText(inAppPurchaseHelper.getGmailAccount()); + // email.setEnabled(false); - //inAppPurchaseHelper.getPurchasedItemsAsync(); + // inAppPurchaseHelper.getPurchasedItemsAsync(); inAppPurchaseHelper.getAvailableItemsForPurchaseAsync(); } @Override public void onAvailableItemsForPurchaseQueryFinished(ArrayList items) { - //purchasableItemsLayout.removeAllViews(); + // purchasableItemsLayout.removeAllViews(); inProgress.setVisibility(View.GONE); purchasedItems = new ArrayList<>(); for (Purchasable item : items) { @@ -154,8 +151,10 @@ public class InAppPurchaseActivity extends Activity implements InAppPurchaseList inAppPurchaseHelper.getAvailableItemsForPurchaseAsync(); } else { for (Purchasable purchasedItem : purchasedItems) { - Log.d("[In-app purchase] Found already bought item, expires " + purchasedItem.getExpireDate()); - //displayRecoverAccountButton(purchasedItem); + Log.d( + "[In-app purchase] Found already bought item, expires " + + purchasedItem.getExpireDate()); + // displayRecoverAccountButton(purchasedItem); } } } @@ -167,12 +166,18 @@ public class InAppPurchaseActivity extends Activity implements InAppPurchaseList Purchasable item = LinphonePreferences.instance().getInAppPurchasedItem(); - xmlRpcHelper.updateAccountExpireAsync(new XmlRpcListenerBase() { - @Override - public void onAccountExpireUpdated(String result) { - //TODO - } - }, LinphonePreferences.instance().getAccountUsername(0), LinphonePreferences.instance().getAccountHa1(0), getString(R.string.default_domain), item.getPayload(), item.getPayloadSignature()); + xmlRpcHelper.updateAccountExpireAsync( + new XmlRpcListenerBase() { + @Override + public void onAccountExpireUpdated(String result) { + // TODO + } + }, + LinphonePreferences.instance().getAccountUsername(0), + LinphonePreferences.instance().getAccountHa1(0), + getString(R.string.default_domain), + item.getPayload(), + item.getPayloadSignature()); } } @@ -193,19 +198,19 @@ public class InAppPurchaseActivity extends Activity implements InAppPurchaseList } @Override - public void onRecoverAccountSuccessful(boolean success) { - } + public void onRecoverAccountSuccessful(boolean success) {} @Override public void onError(final String error) { Log.e(error); - mHandler.post(new Runnable() { - @Override - public void run() { - inProgress.setVisibility(View.GONE); - Toast.makeText(InAppPurchaseActivity.this, error, Toast.LENGTH_LONG).show(); - } - }); + mHandler.post( + new Runnable() { + @Override + public void run() { + inProgress.setVisibility(View.GONE); + Toast.makeText(InAppPurchaseActivity.this, error, Toast.LENGTH_LONG).show(); + } + }); } @Override diff --git a/app/src/main/java/org/linphone/purchase/InAppPurchaseFragment.java b/app/src/main/java/org/linphone/purchase/InAppPurchaseFragment.java index dee280ac8..03dfd2b1d 100644 --- a/app/src/main/java/org/linphone/purchase/InAppPurchaseFragment.java +++ b/app/src/main/java/org/linphone/purchase/InAppPurchaseFragment.java @@ -29,13 +29,11 @@ import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; - +import java.util.Locale; import org.linphone.LinphoneManager; -import org.linphone.settings.LinphonePreferences; import org.linphone.R; import org.linphone.core.ProxyConfig; - -import java.util.Locale; +import org.linphone.settings.LinphonePreferences; public class InAppPurchaseFragment extends Fragment implements View.OnClickListener { private LinearLayout usernameLayout; @@ -47,8 +45,8 @@ public class InAppPurchaseFragment extends Fragment implements View.OnClickListe private Button buyItemButton; @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -61,13 +59,19 @@ public class InAppPurchaseFragment extends Fragment implements View.OnClickListe displayBuySubscriptionButton(item); defaultEmail = InAppPurchaseActivity.instance().getGmailAccount(); - defaultUsername = LinphonePreferences.instance().getAccountUsername(LinphonePreferences.instance().getDefaultAccountIndex()); + defaultUsername = + LinphonePreferences.instance() + .getAccountUsername( + LinphonePreferences.instance().getDefaultAccountIndex()); usernameLayout = view.findViewById(R.id.username_layout); username = view.findViewById(R.id.username); if (!getResources().getBoolean(R.bool.hide_username_in_inapp)) { usernameLayout.setVisibility(View.VISIBLE); - username.setText(LinphonePreferences.instance().getAccountUsername(LinphonePreferences.instance().getDefaultAccountIndex())); + username.setText( + LinphonePreferences.instance() + .getAccountUsername( + LinphonePreferences.instance().getDefaultAccountIndex())); addUsernameHandler(username, errorMessage); } else { @@ -90,27 +94,25 @@ public class InAppPurchaseFragment extends Fragment implements View.OnClickListe } private void addUsernameHandler(final EditText field, final TextView errorMessage) { - field.addTextChangedListener(new TextWatcher() { - public void afterTextChanged(Editable s) { + field.addTextChangedListener( + new TextWatcher() { + public void afterTextChanged(Editable s) {} - } + public void beforeTextChanged( + CharSequence s, int start, int count, int after) {} - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - - } - - public void onTextChanged(CharSequence s, int start, int count, int after) { - usernameOk = false; - String username = s.toString(); - if (isUsernameCorrect(username)) { - usernameOk = true; - errorMessage.setText(""); - } else { - errorMessage.setText(R.string.wizard_username_incorrect); - } - if (buyItemButton != null) buyItemButton.setEnabled(usernameOk); - } - }); + public void onTextChanged(CharSequence s, int start, int count, int after) { + usernameOk = false; + String username = s.toString(); + if (isUsernameCorrect(username)) { + usernameOk = true; + errorMessage.setText(""); + } else { + errorMessage.setText(R.string.wizard_username_incorrect); + } + if (buyItemButton != null) buyItemButton.setEnabled(usernameOk); + } + }); } private boolean isUsernameCorrect(String username) { @@ -137,4 +139,4 @@ public class InAppPurchaseFragment extends Fragment implements View.OnClickListe username = lpc.normalizePhoneNumber(username); return username.toLowerCase(Locale.getDefault()); } -} \ No newline at end of file +} diff --git a/app/src/main/java/org/linphone/purchase/InAppPurchaseHelper.java b/app/src/main/java/org/linphone/purchase/InAppPurchaseHelper.java index 739750f3d..47965ca98 100644 --- a/app/src/main/java/org/linphone/purchase/InAppPurchaseHelper.java +++ b/app/src/main/java/org/linphone/purchase/InAppPurchaseHelper.java @@ -32,18 +32,15 @@ import android.os.Handler; import android.os.IBinder; import android.os.RemoteException; import android.util.Patterns; - import com.android.vending.billing.IInAppBillingService; - -import org.json.JSONException; -import org.json.JSONObject; -import org.linphone.settings.LinphonePreferences; -import org.linphone.mediastream.Log; -import org.linphone.xmlrpc.XmlRpcHelper; -import org.linphone.xmlrpc.XmlRpcListenerBase; - import java.util.ArrayList; import java.util.regex.Pattern; +import org.json.JSONException; +import org.json.JSONObject; +import org.linphone.mediastream.Log; +import org.linphone.settings.LinphonePreferences; +import org.linphone.xmlrpc.XmlRpcHelper; +import org.linphone.xmlrpc.XmlRpcListenerBase; public class InAppPurchaseHelper { public static final int API_VERSION = 3; @@ -86,9 +83,12 @@ public class InAppPurchaseHelper { public static final String PURCHASE_DETAILS_PAYLOAD = "developerPayload"; public static final String PURCHASE_DETAILS_PURCHASE_TOKEN = "purchaseToken"; - public static final String CLIENT_ERROR_SUBSCRIPTION_PURCHASE_NOT_AVAILABLE = "SUBSCRIPTION_PURCHASE_NOT_AVAILABLE"; - public static final String CLIENT_ERROR_BIND_TO_BILLING_SERVICE_FAILED = "BIND_TO_BILLING_SERVICE_FAILED"; - public static final String CLIENT_ERROR_BILLING_SERVICE_UNAVAILABLE = "BILLING_SERVICE_UNAVAILABLE"; + public static final String CLIENT_ERROR_SUBSCRIPTION_PURCHASE_NOT_AVAILABLE = + "SUBSCRIPTION_PURCHASE_NOT_AVAILABLE"; + public static final String CLIENT_ERROR_BIND_TO_BILLING_SERVICE_FAILED = + "BIND_TO_BILLING_SERVICE_FAILED"; + public static final String CLIENT_ERROR_BILLING_SERVICE_UNAVAILABLE = + "BILLING_SERVICE_UNAVAILABLE"; private Context mContext; private InAppPurchaseListener mListener; @@ -97,6 +97,59 @@ public class InAppPurchaseHelper { private Handler mHandler = new Handler(); private String mGmailAccount; + public InAppPurchaseHelper(Activity context, InAppPurchaseListener listener) { + mContext = context; + mListener = listener; + mGmailAccount = getGmailAccount(); + + Log.d( + "[In-app purchase] creating InAppPurchaseHelper for context " + + context.getLocalClassName()); + + mServiceConn = + new ServiceConnection() { + @Override + public void onServiceDisconnected(ComponentName name) { + Log.d("[In-app purchase] onServiceDisconnected!"); + mService = null; + } + + @Override + public void onServiceConnected(ComponentName name, IBinder service) { + Log.d("[In-app purchase] onServiceConnected!"); + mService = IInAppBillingService.Stub.asInterface(service); + String packageName = mContext.getPackageName(); + try { + int response = + mService.isBillingSupported( + API_VERSION, packageName, ITEM_TYPE_SUBS); + if (response != RESPONSE_RESULT_OK || mGmailAccount == null) { + Log.e("[In-app purchase] Error: Subscriptions aren't supported!"); + mListener.onError(CLIENT_ERROR_SUBSCRIPTION_PURCHASE_NOT_AVAILABLE); + } else { + mListener.onServiceAvailableForQueries(); + } + } catch (RemoteException e) { + Log.e(e); + } + } + }; + + Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND"); + serviceIntent.setPackage("com.android.vending"); + if (!mContext.getPackageManager().queryIntentServices(serviceIntent, 0).isEmpty()) { + boolean ok = + mContext.bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE); + if (!ok) { + Log.e("[In-app purchase] Error: Bind service failed"); + mListener.onError(CLIENT_ERROR_BIND_TO_BILLING_SERVICE_FAILED); + } + } else { + Log.e("[In-app purchase] Error: Billing service unavailable on device."); + mListener.onError(CLIENT_ERROR_BILLING_SERVICE_UNAVAILABLE); + } + } + private String responseCodeToErrorMessage(int responseCode) { switch (responseCode) { case RESULT_USER_CANCELED: @@ -119,54 +172,6 @@ public class InAppPurchaseHelper { return "UNKNOWN_RESPONSE_CODE"; } - public InAppPurchaseHelper(Activity context, InAppPurchaseListener listener) { - mContext = context; - mListener = listener; - mGmailAccount = getGmailAccount(); - - - Log.d("[In-app purchase] creating InAppPurchaseHelper for context " + context.getLocalClassName()); - - mServiceConn = new ServiceConnection() { - @Override - public void onServiceDisconnected(ComponentName name) { - Log.d("[In-app purchase] onServiceDisconnected!"); - mService = null; - } - - @Override - public void onServiceConnected(ComponentName name, IBinder service) { - Log.d("[In-app purchase] onServiceConnected!"); - mService = IInAppBillingService.Stub.asInterface(service); - String packageName = mContext.getPackageName(); - try { - int response = mService.isBillingSupported(API_VERSION, packageName, ITEM_TYPE_SUBS); - if (response != RESPONSE_RESULT_OK || mGmailAccount == null) { - Log.e("[In-app purchase] Error: Subscriptions aren't supported!"); - mListener.onError(CLIENT_ERROR_SUBSCRIPTION_PURCHASE_NOT_AVAILABLE); - } else { - mListener.onServiceAvailableForQueries(); - } - } catch (RemoteException e) { - Log.e(e); - } - } - }; - - Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND"); - serviceIntent.setPackage("com.android.vending"); - if (!mContext.getPackageManager().queryIntentServices(serviceIntent, 0).isEmpty()) { - boolean ok = mContext.bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE); - if (!ok) { - Log.e("[In-app purchase] Error: Bind service failed"); - mListener.onError(CLIENT_ERROR_BIND_TO_BILLING_SERVICE_FAILED); - } - } else { - Log.e("[In-app purchase] Error: Billing service unavailable on device."); - mListener.onError(CLIENT_ERROR_BILLING_SERVICE_UNAVAILABLE); - } - } - private ArrayList getAvailableItemsForPurchase() { ArrayList products = new ArrayList<>(); ArrayList skuList = LinphonePreferences.instance().getInAppPurchasables(); @@ -175,7 +180,9 @@ public class InAppPurchaseHelper { Bundle skuDetails = null; try { - skuDetails = mService.getSkuDetails(API_VERSION, mContext.getPackageName(), ITEM_TYPE_SUBS, querySkus); + skuDetails = + mService.getSkuDetails( + API_VERSION, mContext.getPackageName(), ITEM_TYPE_SUBS, querySkus); } catch (RemoteException e) { Log.e(e); } @@ -192,7 +199,11 @@ public class InAppPurchaseHelper { String title = object.getString(SKU_DETAILS_TITLE); String desc = object.getString(SKU_DETAILS_DESC); - Purchasable purchasable = new Purchasable(id).setTitle(title).setDescription(desc).setPrice(price); + Purchasable purchasable = + new Purchasable(id) + .setTitle(title) + .setDescription(desc) + .setPrice(price); Log.w("Purchasable item " + purchasable.getDescription()); products.add(purchasable); } catch (JSONException e) { @@ -200,7 +211,9 @@ public class InAppPurchaseHelper { } } } else { - Log.e("[In-app purchase] Error: responde code is not ok: " + responseCodeToErrorMessage(response)); + Log.e( + "[In-app purchase] Error: responde code is not ok: " + + responseCodeToErrorMessage(response)); mListener.onError(responseCodeToErrorMessage(response)); } } @@ -209,21 +222,27 @@ public class InAppPurchaseHelper { } public void getAvailableItemsForPurchaseAsync() { - new Thread(new Runnable() { - public void run() { - final ArrayList items = getAvailableItemsForPurchase(); - if (mHandler != null && mListener != null) { - mHandler.post(new Runnable() { - public void run() { - mListener.onAvailableItemsForPurchaseQueryFinished(items); - } - }); - } - } - }).start(); + new Thread( + new Runnable() { + public void run() { + final ArrayList items = getAvailableItemsForPurchase(); + if (mHandler != null && mListener != null) { + mHandler.post( + new Runnable() { + public void run() { + mListener + .onAvailableItemsForPurchaseQueryFinished( + items); + } + }); + } + } + }) + .start(); } - public void parseAndVerifyPurchaseItemResultAsync(int requestCode, int resultCode, Intent data) { + public void parseAndVerifyPurchaseItemResultAsync( + int requestCode, int resultCode, Intent data) { if (requestCode == ACTIVITY_RESULT_CODE_PURCHASE_ITEM) { int responseCode = data.getIntExtra(RESPONSE_CODE, 0); @@ -236,12 +255,15 @@ public class InAppPurchaseHelper { LinphonePreferences.instance().setInAppPurchasedItem(item); XmlRpcHelper xmlRpcHelper = new XmlRpcHelper(); - xmlRpcHelper.verifySignatureAsync(new XmlRpcListenerBase() { - @Override - public void onSignatureVerified(boolean success) { - mListener.onPurchasedItemConfirmationQueryFinished(success); - } - }, payload, signature); + xmlRpcHelper.verifySignatureAsync( + new XmlRpcListenerBase() { + @Override + public void onSignatureVerified(boolean success) { + mListener.onPurchasedItemConfirmationQueryFinished(success); + } + }, + payload, + signature); } } } @@ -249,7 +271,13 @@ public class InAppPurchaseHelper { private void purchaseItem(String productId, String sipIdentity) { Bundle buyIntentBundle = null; try { - buyIntentBundle = mService.getBuyIntent(API_VERSION, mContext.getPackageName(), productId, ITEM_TYPE_SUBS, sipIdentity); + buyIntentBundle = + mService.getBuyIntent( + API_VERSION, + mContext.getPackageName(), + productId, + ITEM_TYPE_SUBS, + sipIdentity); } catch (RemoteException e) { Log.e(e); } @@ -258,7 +286,14 @@ public class InAppPurchaseHelper { PendingIntent pendingIntent = buyIntentBundle.getParcelable(RESPONSE_BUY_INTENT); if (pendingIntent != null) { try { - ((Activity) mContext).startIntentSenderForResult(pendingIntent.getIntentSender(), ACTIVITY_RESULT_CODE_PURCHASE_ITEM, new Intent(), 0, 0, 0); + ((Activity) mContext) + .startIntentSenderForResult( + pendingIntent.getIntentSender(), + ACTIVITY_RESULT_CODE_PURCHASE_ITEM, + new Intent(), + 0, + 0, + 0); } catch (SendIntentException e) { Log.e(e); } @@ -267,11 +302,13 @@ public class InAppPurchaseHelper { } public void purchaseItemAsync(final String productId, final String sipIdentity) { - new Thread(new Runnable() { - public void run() { - purchaseItem(productId, sipIdentity); - } - }).start(); + new Thread( + new Runnable() { + public void run() { + purchaseItem(productId, sipIdentity); + } + }) + .start(); } public void destroy() { @@ -298,18 +335,18 @@ public class InAppPurchaseHelper { private Purchasable verifySignature(String payload, String signature) { // TODO FIXME rework to be async - /*XmlRpcHelper helper = new XmlRpcHelper(); - if (helper.verifySignature(payload, signature)) { - try { - JSONObject json = new JSONObject(payload); - String productId = json.getString(PURCHASE_DETAILS_PRODUCT_ID); - Purchasable item = new Purchasable(productId); - item.setPayloadAndSignature(payload, signature); - return item; - } catch (JSONException e) { - Log.e(e); - } - }*/ + /*XmlRpcHelper helper = new XmlRpcHelper(); + if (helper.verifySignature(payload, signature)) { + try { + JSONObject json = new JSONObject(payload); + String productId = json.getString(PURCHASE_DETAILS_PRODUCT_ID); + Purchasable item = new Purchasable(productId); + item.setPayloadAndSignature(payload, signature); + return item; + } catch (JSONException e) { + Log.e(e); + } + }*/ return null; } diff --git a/app/src/main/java/org/linphone/purchase/InAppPurchaseListFragment.java b/app/src/main/java/org/linphone/purchase/InAppPurchaseListFragment.java index 683111136..00d8b5b36 100644 --- a/app/src/main/java/org/linphone/purchase/InAppPurchaseListFragment.java +++ b/app/src/main/java/org/linphone/purchase/InAppPurchaseListFragment.java @@ -28,10 +28,8 @@ import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; - -import org.linphone.R; - import java.util.List; +import org.linphone.R; public class InAppPurchaseListFragment extends Fragment implements AdapterView.OnItemClickListener { private ListView inappList; @@ -39,8 +37,8 @@ public class InAppPurchaseListFragment extends Fragment implements AdapterView.O private List mPurchasableItems; @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mInflater = inflater; View view = inflater.inflate(R.layout.in_app_list, container, false); @@ -54,9 +52,14 @@ public class InAppPurchaseListFragment extends Fragment implements AdapterView.O return view; } + @Override + public void onItemClick(AdapterView parent, View view, int position, long id) { + Purchasable item = (Purchasable) view.getTag(); + InAppPurchaseActivity.instance().displayPurchase(item); + } + class InAppListAdapter extends BaseAdapter { - InAppListAdapter() { - } + InAppListAdapter() {} public int getCount() { return mPurchasableItems.size(); @@ -92,11 +95,4 @@ public class InAppPurchaseListFragment extends Fragment implements AdapterView.O return view; } } - - - @Override - public void onItemClick(AdapterView parent, View view, int position, long id) { - Purchasable item = (Purchasable) view.getTag(); - InAppPurchaseActivity.instance().displayPurchase(item); - } } diff --git a/app/src/main/java/org/linphone/purchase/InAppPurchaseListener.java b/app/src/main/java/org/linphone/purchase/InAppPurchaseListener.java index deb3e9b9d..b2d42a05d 100644 --- a/app/src/main/java/org/linphone/purchase/InAppPurchaseListener.java +++ b/app/src/main/java/org/linphone/purchase/InAppPurchaseListener.java @@ -21,9 +21,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import java.util.ArrayList; public 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(); /** diff --git a/app/src/main/java/org/linphone/purchase/Purchasable.java b/app/src/main/java/org/linphone/purchase/Purchasable.java index 87256f113..fdb024c13 100644 --- a/app/src/main/java/org/linphone/purchase/Purchasable.java +++ b/app/src/main/java/org/linphone/purchase/Purchasable.java @@ -69,17 +69,17 @@ public class Purchasable { return expire; } + public Purchasable setExpire(long expire) { + this.expire = expire; + return this; + } + public String getExpireDate() { DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.getDefault()); Date date = new Date(expire); return dateFormat.format(date); } - public Purchasable setExpire(long expire) { - this.expire = expire; - return this; - } - public Purchasable setPayloadAndSignature(String payload, String signature) { this.purchasePayload = payload; this.purchasePayloadSignature = signature; @@ -94,12 +94,12 @@ public class Purchasable { return this.purchasePayloadSignature; } + public String getUserData() { + return this.userData; + } + public Purchasable setUserData(String data) { this.userData = data; return this; } - - public String getUserData() { - return this.userData; - } } diff --git a/app/src/main/java/org/linphone/receivers/AccountEnableReceiver.java b/app/src/main/java/org/linphone/receivers/AccountEnableReceiver.java index 431158444..7f856ee03 100644 --- a/app/src/main/java/org/linphone/receivers/AccountEnableReceiver.java +++ b/app/src/main/java/org/linphone/receivers/AccountEnableReceiver.java @@ -23,7 +23,6 @@ import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; - import org.linphone.settings.LinphonePreferences; public class AccountEnableReceiver extends BroadcastReceiver { @@ -35,10 +34,14 @@ public class AccountEnableReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { int prefsAccountIndex = (int) (long) intent.getLongExtra(FIELD_ID, -1); boolean enable = intent.getBooleanExtra(FIELD_ACTIVE, true); - Log.i(TAG, "Received broadcast for index=" + Integer.toString(prefsAccountIndex) + ",enable=" + Boolean.toString(enable)); - if (prefsAccountIndex < 0 || prefsAccountIndex >= LinphonePreferences.instance().getAccountCount()) - return; + Log.i( + TAG, + "Received broadcast for index=" + + Integer.toString(prefsAccountIndex) + + ",enable=" + + Boolean.toString(enable)); + if (prefsAccountIndex < 0 + || prefsAccountIndex >= LinphonePreferences.instance().getAccountCount()) return; LinphonePreferences.instance().setAccountEnabled(prefsAccountIndex, enable); } } - diff --git a/app/src/main/java/org/linphone/receivers/BluetoothManager.java b/app/src/main/java/org/linphone/receivers/BluetoothManager.java index 2b2f0cb76..f0307cf05 100644 --- a/app/src/main/java/org/linphone/receivers/BluetoothManager.java +++ b/app/src/main/java/org/linphone/receivers/BluetoothManager.java @@ -28,13 +28,11 @@ import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.media.AudioManager; - +import java.util.List; import org.linphone.LinphoneManager; import org.linphone.LinphoneService; import org.linphone.call.CallActivity; -import java.util.List; - public class BluetoothManager extends BroadcastReceiver { private static BluetoothManager instance; @@ -47,6 +45,16 @@ public class BluetoothManager extends BroadcastReceiver { private boolean isBluetoothConnected; private boolean isScoConnected; + public BluetoothManager() { + isBluetoothConnected = false; + if (!ensureInit()) { + android.util.Log.w( + "BluetoothManager", + "[Bluetooth] Manager tried to init but LinphoneService not ready yet..."); + } + instance = this; + } + public static BluetoothManager getInstance() { if (instance == null) { instance = new BluetoothManager(); @@ -54,22 +62,19 @@ public class BluetoothManager extends BroadcastReceiver { return instance; } - public BluetoothManager() { - isBluetoothConnected = false; - if (!ensureInit()) { - android.util.Log.w("BluetoothManager", "[Bluetooth] Manager tried to init but LinphoneService not ready yet..."); - } - instance = this; - } - public void initBluetooth() { if (!ensureInit()) { - android.util.Log.w("BluetoothManager", "[Bluetooth] Manager tried to init bluetooth but LinphoneService not ready yet..."); + android.util.Log.w( + "BluetoothManager", + "[Bluetooth] Manager tried to init bluetooth but LinphoneService not ready yet..."); return; } IntentFilter filter = new IntentFilter(); - filter.addCategory(BluetoothHeadset.VENDOR_SPECIFIC_HEADSET_EVENT_COMPANY_ID_CATEGORY + "." + BluetoothAssignedNumbers.PLANTRONICS); + filter.addCategory( + BluetoothHeadset.VENDOR_SPECIFIC_HEADSET_EVENT_COMPANY_ID_CATEGORY + + "." + + BluetoothAssignedNumbers.PLANTRONICS); filter.addAction(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED); filter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED); filter.addAction(BluetoothHeadset.ACTION_VENDOR_SPECIFIC_HEADSET_EVENT); @@ -89,29 +94,36 @@ public class BluetoothManager extends BroadcastReceiver { if (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) { if (mProfileListener != null) { - android.util.Log.w("BluetoothManager", "[Bluetooth] Headset profile was already opened, let's close it"); + android.util.Log.w( + "BluetoothManager", + "[Bluetooth] Headset profile was already opened, let's close it"); mBluetoothAdapter.closeProfileProxy(BluetoothProfile.HEADSET, mBluetoothHeadset); } - mProfileListener = new BluetoothProfile.ServiceListener() { - public void onServiceConnected(int profile, BluetoothProfile proxy) { - if (profile == BluetoothProfile.HEADSET) { - android.util.Log.d("BluetoothManager", "[Bluetooth] Headset connected"); - mBluetoothHeadset = (BluetoothHeadset) proxy; - isBluetoothConnected = true; - } - } + mProfileListener = + new BluetoothProfile.ServiceListener() { + public void onServiceConnected(int profile, BluetoothProfile proxy) { + if (profile == BluetoothProfile.HEADSET) { + android.util.Log.d( + "BluetoothManager", "[Bluetooth] Headset connected"); + mBluetoothHeadset = (BluetoothHeadset) proxy; + isBluetoothConnected = true; + } + } - public void onServiceDisconnected(int profile) { - if (profile == BluetoothProfile.HEADSET) { - mBluetoothHeadset = null; - isBluetoothConnected = false; - android.util.Log.d("BluetoothManager", "[Bluetooth] Headset disconnected"); - LinphoneManager.getInstance().routeAudioToReceiver(); - } - } - }; - boolean success = mBluetoothAdapter.getProfileProxy(mContext, mProfileListener, BluetoothProfile.HEADSET); + public void onServiceDisconnected(int profile) { + if (profile == BluetoothProfile.HEADSET) { + mBluetoothHeadset = null; + isBluetoothConnected = false; + android.util.Log.d( + "BluetoothManager", "[Bluetooth] Headset disconnected"); + LinphoneManager.getInstance().routeAudioToReceiver(); + } + } + }; + boolean success = + mBluetoothAdapter.getProfileProxy( + mContext, mProfileListener, BluetoothProfile.HEADSET); if (!success) { android.util.Log.e("BluetoothManager", "[Bluetooth] getProfileProxy failed !"); } @@ -146,7 +158,10 @@ public class BluetoothManager extends BroadcastReceiver { public boolean routeAudioToBluetooth() { ensureInit(); - if (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled() && mAudioManager != null && mAudioManager.isBluetoothScoAvailableOffCall()) { + if (mBluetoothAdapter != null + && mBluetoothAdapter.isEnabled() + && mAudioManager != null + && mAudioManager.isBluetoothScoAvailableOffCall()) { if (isBluetoothHeadsetAvailable()) { if (mAudioManager != null && !mAudioManager.isBluetoothScoOn()) { android.util.Log.d("BluetoothManager", "[Bluetooth] SCO off, let's start it"); @@ -177,7 +192,9 @@ public class BluetoothManager extends BroadcastReceiver { } if (ok) { if (retries > 0) { - android.util.Log.d("BluetoothManager", "[Bluetooth] Audio route ok after " + retries + " retries"); + android.util.Log.d( + "BluetoothManager", + "[Bluetooth] Audio route ok after " + retries + " retries"); } else { android.util.Log.d("BluetoothManager", "[Bluetooth] Audio route ok"); } @@ -192,24 +209,34 @@ public class BluetoothManager extends BroadcastReceiver { } public boolean isUsingBluetoothAudioRoute() { - return mBluetoothHeadset != null && mBluetoothHeadset.isAudioConnected(mBluetoothDevice) && isScoConnected; + return mBluetoothHeadset != null + && mBluetoothHeadset.isAudioConnected(mBluetoothDevice) + && isScoConnected; } public boolean isBluetoothHeadsetAvailable() { ensureInit(); - if (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled() && mAudioManager != null && mAudioManager.isBluetoothScoAvailableOffCall()) { + if (mBluetoothAdapter != null + && mBluetoothAdapter.isEnabled() + && mAudioManager != null + && mAudioManager.isBluetoothScoAvailableOffCall()) { boolean isHeadsetConnected = false; if (mBluetoothHeadset != null) { List devices = mBluetoothHeadset.getConnectedDevices(); mBluetoothDevice = null; for (final BluetoothDevice dev : devices) { - if (mBluetoothHeadset.getConnectionState(dev) == BluetoothHeadset.STATE_CONNECTED) { + if (mBluetoothHeadset.getConnectionState(dev) + == BluetoothHeadset.STATE_CONNECTED) { mBluetoothDevice = dev; isHeadsetConnected = true; break; } } - android.util.Log.d("BluetoothManager", isHeadsetConnected ? "[Bluetooth] Headset found, bluetooth audio route available" : "[Bluetooth] No headset found, bluetooth audio route unavailable"); + android.util.Log.d( + "BluetoothManager", + isHeadsetConnected + ? "[Bluetooth] Headset found, bluetooth audio route available" + : "[Bluetooth] No headset found, bluetooth audio route unavailable"); } return isHeadsetConnected; } @@ -275,30 +302,32 @@ public class BluetoothManager extends BroadcastReceiver { } public void onReceive(Context context, Intent intent) { - if (!LinphoneManager.isInstanciated()) - return; + if (!LinphoneManager.isInstanciated()) return; String action = intent.getAction(); if (AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED.equals(action)) { int state = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, 0); if (state == AudioManager.SCO_AUDIO_STATE_CONNECTED) { android.util.Log.d("BluetoothManager", "[Bluetooth] SCO state: connected"); -// LinphoneManager.getInstance().audioStateChanged(AudioState.BLUETOOTH); + // LinphoneManager.getInstance().audioStateChanged(AudioState.BLUETOOTH); isScoConnected = true; } else if (state == AudioManager.SCO_AUDIO_STATE_DISCONNECTED) { android.util.Log.d("BluetoothManager", "[Bluetooth] SCO state: disconnected"); -// LinphoneManager.getInstance().audioStateChanged(AudioState.SPEAKER); + // LinphoneManager.getInstance().audioStateChanged(AudioState.SPEAKER); isScoConnected = false; } else if (state == AudioManager.SCO_AUDIO_STATE_CONNECTING) { android.util.Log.d("BluetoothManager", "[Bluetooth] SCO state: connecting"); -// LinphoneManager.getInstance().audioStateChanged(AudioState.BLUETOOTH); + // LinphoneManager.getInstance().audioStateChanged(AudioState.BLUETOOTH); isScoConnected = true; } else { android.util.Log.d("BluetoothManager", "[Bluetooth] SCO state: " + state); } refreshCallView(); } else if (BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED.equals(action)) { - int state = intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE, BluetoothAdapter.STATE_DISCONNECTED); + int state = + intent.getIntExtra( + BluetoothAdapter.EXTRA_CONNECTION_STATE, + BluetoothAdapter.STATE_DISCONNECTED); if (state == 0) { android.util.Log.d("BluetoothManager", "[Bluetooth] State: disconnected"); stopBluetooth(); @@ -308,22 +337,41 @@ public class BluetoothManager extends BroadcastReceiver { } else { android.util.Log.d("BluetoothManager", "[Bluetooth] State: " + state); } - } else if (intent.getAction().equals(BluetoothHeadset.ACTION_VENDOR_SPECIFIC_HEADSET_EVENT)) { - String command = intent.getExtras().getString(BluetoothHeadset.EXTRA_VENDOR_SPECIFIC_HEADSET_EVENT_CMD); - //int type = intent.getExtras().getInt(BluetoothHeadset.EXTRA_VENDOR_SPECIFIC_HEADSET_EVENT_CMD_TYPE); + } else if (intent.getAction() + .equals(BluetoothHeadset.ACTION_VENDOR_SPECIFIC_HEADSET_EVENT)) { + String command = + intent.getExtras() + .getString(BluetoothHeadset.EXTRA_VENDOR_SPECIFIC_HEADSET_EVENT_CMD); + // int type = + // intent.getExtras().getInt(BluetoothHeadset.EXTRA_VENDOR_SPECIFIC_HEADSET_EVENT_CMD_TYPE); - Object[] args = (Object[]) intent.getExtras().get(BluetoothHeadset.EXTRA_VENDOR_SPECIFIC_HEADSET_EVENT_ARGS); + Object[] args = + (Object[]) + intent.getExtras() + .get(BluetoothHeadset.EXTRA_VENDOR_SPECIFIC_HEADSET_EVENT_ARGS); if (args.length <= 0) { - android.util.Log.d("BluetoothManager", "[Bluetooth] Event: " + command + ", no args"); + android.util.Log.d( + "BluetoothManager", "[Bluetooth] Event: " + command + ", no args"); return; } String eventName = (args[0]).toString(); if (eventName.equals("BUTTON") && args.length >= 3) { String buttonID = args[1].toString(); String mode = args[2].toString(); - android.util.Log.d("BluetoothManager", "[Bluetooth] Event: " + command + " : " + eventName + ", id = " + buttonID + " (" + mode + ")"); + android.util.Log.d( + "BluetoothManager", + "[Bluetooth] Event: " + + command + + " : " + + eventName + + ", id = " + + buttonID + + " (" + + mode + + ")"); } else { - android.util.Log.d("BluetoothManager", "[Bluetooth] Event: " + command + " : " + eventName); + android.util.Log.d( + "BluetoothManager", "[Bluetooth] Event: " + command + " : " + eventName); } } } diff --git a/app/src/main/java/org/linphone/receivers/BootReceiver.java b/app/src/main/java/org/linphone/receivers/BootReceiver.java index 8dc05ac08..e10cec238 100644 --- a/app/src/main/java/org/linphone/receivers/BootReceiver.java +++ b/app/src/main/java/org/linphone/receivers/BootReceiver.java @@ -22,11 +22,10 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; - import org.linphone.LinphoneManager; -import org.linphone.settings.LinphonePreferences; import org.linphone.LinphoneService; import org.linphone.compatibility.Compatibility; +import org.linphone.settings.LinphonePreferences; public class BootReceiver extends BroadcastReceiver { @@ -34,11 +33,14 @@ public class BootReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { LinphonePreferences.instance().setContext(context); if (intent.getAction().equalsIgnoreCase(Intent.ACTION_SHUTDOWN)) { - android.util.Log.d("LinphoneBootReceiver", "Device is shutting down, destroying Core to unregister"); + android.util.Log.d( + "LinphoneBootReceiver", + "Device is shutting down, destroying Core to unregister"); LinphoneManager.destroy(); } else { boolean autostart = LinphonePreferences.instance().isAutoStartEnabled(); - android.util.Log.i("LinphoneBootReceiver", "Device is starting, auto_start is " + autostart); + android.util.Log.i( + "LinphoneBootReceiver", "Device is starting, auto_start is " + autostart); if (autostart && !LinphoneService.isReady()) { Intent lLinphoneServiceIntent = new Intent(Intent.ACTION_MAIN); lLinphoneServiceIntent.setClass(context, LinphoneService.class); diff --git a/app/src/main/java/org/linphone/receivers/DozeReceiver.java b/app/src/main/java/org/linphone/receivers/DozeReceiver.java index 157e53a96..704ff0dd5 100644 --- a/app/src/main/java/org/linphone/receivers/DozeReceiver.java +++ b/app/src/main/java/org/linphone/receivers/DozeReceiver.java @@ -23,14 +23,13 @@ import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.PowerManager; - import org.linphone.LinphoneManager; -import org.linphone.settings.LinphonePreferences; import org.linphone.LinphoneService; -import org.linphone.utils.LinphoneUtils; import org.linphone.R; import org.linphone.core.Core; import org.linphone.mediastream.Log; +import org.linphone.settings.LinphonePreferences; +import org.linphone.utils.LinphoneUtils; /* * Purpose of this receiver is to disable keep alives when device is on idle diff --git a/app/src/main/java/org/linphone/receivers/HookReceiver.java b/app/src/main/java/org/linphone/receivers/HookReceiver.java index ac1f232c1..c42be6e83 100644 --- a/app/src/main/java/org/linphone/receivers/HookReceiver.java +++ b/app/src/main/java/org/linphone/receivers/HookReceiver.java @@ -23,27 +23,24 @@ import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; - import org.linphone.LinphoneManager; import org.linphone.mediastream.Log; public class HookReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { - if (isOrderedBroadcast()) - abortBroadcast(); + if (isOrderedBroadcast()) abortBroadcast(); Bundle extras = intent.getExtras(); boolean b = extras.getBoolean("hookoff"); if (b) { - //handset on + // handset on Log.i(" ======>>>>>> HookReceiver - handset ON"); LinphoneManager.getInstance().enableSpeaker(false); if (!LinphoneManager.getInstance().isHansetModeOn()) LinphoneManager.getInstance().setHandsetMode(true); - } else { - //handset off + // handset off Log.i(" ======>>>>>> HookReceiver - handset OFF"); LinphoneManager.getInstance().enableSpeaker(true); LinphoneManager.getInstance().setHandsetMode(false); diff --git a/app/src/main/java/org/linphone/receivers/KeepAliveReceiver.java b/app/src/main/java/org/linphone/receivers/KeepAliveReceiver.java index 897da851e..f4d301627 100644 --- a/app/src/main/java/org/linphone/receivers/KeepAliveReceiver.java +++ b/app/src/main/java/org/linphone/receivers/KeepAliveReceiver.java @@ -25,14 +25,13 @@ import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.SystemClock; - import org.linphone.LinphoneManager; -import org.linphone.settings.LinphonePreferences; import org.linphone.LinphoneService; -import org.linphone.utils.LinphoneUtils; import org.linphone.R; import org.linphone.core.Core; import org.linphone.mediastream.Log; +import org.linphone.settings.LinphonePreferences; +import org.linphone.utils.LinphoneUtils; /* * Purpose of this receiver is to disable keep alives when screen is off @@ -52,18 +51,25 @@ public class KeepAliveReceiver extends BroadcastReceiver { if (action == null) { Log.i("[KeepAlive] Refresh registers"); lc.refreshRegisters(); - //make sure iterate will have enough time, device will not sleep until exit from this method + // make sure iterate will have enough time, device will not sleep until exit from + // this method try { Thread.sleep(2000); } catch (InterruptedException e) { Log.e("Cannot sleep for 2s", e); } finally { - //make sure the application will at least wakes up every 10 mn + // make sure the application will at least wakes up every 10 mn Intent newIntent = new Intent(context, KeepAliveReceiver.class); - PendingIntent keepAlivePendingIntent = PendingIntent.getBroadcast(context, 0, newIntent, PendingIntent.FLAG_ONE_SHOT); + PendingIntent keepAlivePendingIntent = + PendingIntent.getBroadcast( + context, 0, newIntent, PendingIntent.FLAG_ONE_SHOT); - AlarmManager alarmManager = ((AlarmManager) context.getSystemService(Context.ALARM_SERVICE)); - alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 600000, keepAlivePendingIntent); + AlarmManager alarmManager = + ((AlarmManager) context.getSystemService(Context.ALARM_SERVICE)); + alarmManager.setExact( + AlarmManager.ELAPSED_REALTIME_WAKEUP, + SystemClock.elapsedRealtime() + 600000, + keepAlivePendingIntent); } } else if (action.equalsIgnoreCase(Intent.ACTION_SCREEN_ON)) { Log.i("[KeepAlive] Screen is on, enable"); diff --git a/app/src/main/java/org/linphone/receivers/NetworkManager.java b/app/src/main/java/org/linphone/receivers/NetworkManager.java index ca441e85a..388597cfa 100644 --- a/app/src/main/java/org/linphone/receivers/NetworkManager.java +++ b/app/src/main/java/org/linphone/receivers/NetworkManager.java @@ -23,21 +23,19 @@ import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; - import org.linphone.LinphoneManager; -/** - * Intercept network state changes and update linphone core through LinphoneManager. - */ +/** Intercept network state changes and update linphone core through LinphoneManager. */ public class NetworkManager extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { - ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); - Boolean lNoConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); + ConnectivityManager cm = + (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); + Boolean lNoConnectivity = + intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); if (LinphoneManager.isInstanciated()) { LinphoneManager.getInstance().connectivityChanged(cm, lNoConnectivity); } } - } diff --git a/app/src/main/java/org/linphone/receivers/OutgoingCallReceiver.java b/app/src/main/java/org/linphone/receivers/OutgoingCallReceiver.java index 655f0ff35..4fee37f8d 100644 --- a/app/src/main/java/org/linphone/receivers/OutgoingCallReceiver.java +++ b/app/src/main/java/org/linphone/receivers/OutgoingCallReceiver.java @@ -19,18 +19,16 @@ along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ +import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK; + import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; - import org.linphone.settings.LinphonePreferences; -import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK; - - public class OutgoingCallReceiver extends BroadcastReceiver { - private final static String TAG = "CallHandler"; + private static final String TAG = "CallHandler"; private final String ACTION_CALL_LINPHONE = "org.linphone.intent.action.CallLaunched"; private LinphonePreferences mPrefs; @@ -53,4 +51,4 @@ public class OutgoingCallReceiver extends BroadcastReceiver { } } } -} \ No newline at end of file +} diff --git a/app/src/main/java/org/linphone/receivers/PhoneStateChangedReceiver.java b/app/src/main/java/org/linphone/receivers/PhoneStateChangedReceiver.java index e43084b76..1e11c12c4 100644 --- a/app/src/main/java/org/linphone/receivers/PhoneStateChangedReceiver.java +++ b/app/src/main/java/org/linphone/receivers/PhoneStateChangedReceiver.java @@ -23,22 +23,19 @@ import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.telephony.TelephonyManager; - import org.linphone.LinphoneManager; import org.linphone.core.Core; -/** - * Pause current SIP calls when GSM phone rings or is active. - */ +/** Pause current SIP calls when GSM phone rings or is active. */ public class PhoneStateChangedReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { final String extraState = intent.getStringExtra(TelephonyManager.EXTRA_STATE); - if (!LinphoneManager.isInstanciated()) - return; + if (!LinphoneManager.isInstanciated()) return; - if (TelephonyManager.EXTRA_STATE_OFFHOOK.equals(extraState) || TelephonyManager.EXTRA_STATE_RINGING.equals(extraState)) { + if (TelephonyManager.EXTRA_STATE_OFFHOOK.equals(extraState) + || TelephonyManager.EXTRA_STATE_RINGING.equals(extraState)) { LinphoneManager.getInstance().setCallGsmON(true); Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull(); lc.pauseAllCalls(); diff --git a/app/src/main/java/org/linphone/recording/Recording.java b/app/src/main/java/org/linphone/recording/Recording.java index bb8d75514..d8776a8d5 100644 --- a/app/src/main/java/org/linphone/recording/Recording.java +++ b/app/src/main/java/org/linphone/recording/Recording.java @@ -22,20 +22,20 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import android.annotation.SuppressLint; import android.content.Context; import android.os.Handler; -import android.support.annotation.NonNull; - -import org.linphone.LinphoneManager; -import org.linphone.core.Player; -import org.linphone.core.PlayerListener; -import org.linphone.mediastream.Log; - +import androidx.annotation.NonNull; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.linphone.LinphoneManager; +import org.linphone.core.Player; +import org.linphone.core.PlayerListener; +import org.linphone.mediastream.Log; public class Recording implements PlayerListener, Comparable { + public static final Pattern RECORD_PATTERN = + Pattern.compile(".*/(.*)_(\\d{2}-\\d{2}-\\d{4}-\\d{2}-\\d{2}-\\d{2})\\..*"); private String recordPath, name; private Date recordDate; private Player player; @@ -43,8 +43,6 @@ public class Recording implements PlayerListener, Comparable { private Handler handler; private Runnable updateCurrentPositionTimer; - public static final Pattern RECORD_PATTERN = Pattern.compile(".*/(.*)_(\\d{2}-\\d{2}-\\d{4}-\\d{2}-\\d{2}-\\d{2})\\..*"); - @SuppressLint("SimpleDateFormat") public Recording(Context context, String recordPath) { this.recordPath = recordPath; @@ -61,13 +59,14 @@ public class Recording implements PlayerListener, Comparable { } handler = new Handler(context.getMainLooper()); - updateCurrentPositionTimer = new Runnable() { - @Override - public void run() { - if (listener != null) listener.currentPositionChanged(getCurrentPosition()); - if (isPlaying()) handler.postDelayed(updateCurrentPositionTimer, 20); - } - }; + updateCurrentPositionTimer = + new Runnable() { + @Override + public void run() { + if (listener != null) listener.currentPositionChanged(getCurrentPosition()); + if (isPlaying()) handler.postDelayed(updateCurrentPositionTimer, 20); + } + }; player = LinphoneManager.getLc().createLocalPlayer(null, null, null); player.setListener(this); diff --git a/app/src/main/java/org/linphone/recording/RecordingAdapter.java b/app/src/main/java/org/linphone/recording/RecordingAdapter.java index 3a62fc77a..91e8a6980 100644 --- a/app/src/main/java/org/linphone/recording/RecordingAdapter.java +++ b/app/src/main/java/org/linphone/recording/RecordingAdapter.java @@ -21,28 +21,30 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import android.annotation.SuppressLint; import android.content.Context; -import android.support.annotation.NonNull; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.SeekBar; - -import org.linphone.R; -import org.linphone.utils.SelectableAdapter; -import org.linphone.utils.SelectableHelper; - +import androidx.annotation.NonNull; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.concurrent.TimeUnit; +import org.linphone.R; +import org.linphone.utils.SelectableAdapter; +import org.linphone.utils.SelectableHelper; public class RecordingAdapter extends SelectableAdapter { private List recordings; private Context context; private RecordingViewHolder.ClickListener clickListener; - public RecordingAdapter(Context context, List recordings, RecordingViewHolder.ClickListener listener, SelectableHelper helper) { + public RecordingAdapter( + Context context, + List recordings, + RecordingViewHolder.ClickListener listener, + SelectableHelper helper) { super(helper); this.recordings = recordings; @@ -58,7 +60,9 @@ public class RecordingAdapter extends SelectableAdapter { @NonNull @Override public RecordingViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { - View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recording_cell, viewGroup, false); + View v = + LayoutInflater.from(viewGroup.getContext()) + .inflate(R.layout.recording_cell, viewGroup, false); return new RecordingViewHolder(v, clickListener); } @@ -95,87 +99,101 @@ public class RecordingAdapter extends SelectableAdapter { } else { viewHolder.playButton.setImageResource(R.drawable.record_play); } - viewHolder.playButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (record.isPaused()) { - record.play(); - viewHolder.playButton.setImageResource(R.drawable.record_pause); - } else { - record.pause(); - viewHolder.playButton.setImageResource(R.drawable.record_play); - } - } - }); + viewHolder.playButton.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View v) { + if (record.isPaused()) { + record.play(); + viewHolder.playButton.setImageResource(R.drawable.record_pause); + } else { + record.pause(); + viewHolder.playButton.setImageResource(R.drawable.record_play); + } + } + }); viewHolder.name.setText(record.getName()); viewHolder.date.setText(new SimpleDateFormat("HH:mm").format(record.getRecordDate())); int position = record.getCurrentPosition(); - viewHolder.currentPosition.setText(String.format("%02d:%02d", - TimeUnit.MILLISECONDS.toMinutes(position), - TimeUnit.MILLISECONDS.toSeconds(position) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(position)) - )); + viewHolder.currentPosition.setText( + String.format( + "%02d:%02d", + TimeUnit.MILLISECONDS.toMinutes(position), + TimeUnit.MILLISECONDS.toSeconds(position) + - TimeUnit.MINUTES.toSeconds( + TimeUnit.MILLISECONDS.toMinutes(position)))); int duration = record.getDuration(); - viewHolder.duration.setText(String.format("%02d:%02d", - TimeUnit.MILLISECONDS.toMinutes(duration), - TimeUnit.MILLISECONDS.toSeconds(duration) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration)) - )); + viewHolder.duration.setText( + String.format( + "%02d:%02d", + TimeUnit.MILLISECONDS.toMinutes(duration), + TimeUnit.MILLISECONDS.toSeconds(duration) + - TimeUnit.MINUTES.toSeconds( + TimeUnit.MILLISECONDS.toMinutes(duration)))); viewHolder.progressionBar.setMax(record.getDuration()); viewHolder.progressionBar.setProgress(0); - viewHolder.progressionBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - if (fromUser) { - int progressToSet = progress > 0 && progress < seekBar.getMax() ? progress : 0; + viewHolder.progressionBar.setOnSeekBarChangeListener( + new SeekBar.OnSeekBarChangeListener() { + @Override + public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { + if (fromUser) { + int progressToSet = + progress > 0 && progress < seekBar.getMax() ? progress : 0; - if (progress == seekBar.getMax()) { - if (record.isPlaying()) record.pause(); + if (progress == seekBar.getMax()) { + if (record.isPlaying()) record.pause(); + } + + record.seek(progressToSet); + seekBar.setProgress(progressToSet); + + int currentPosition = record.getCurrentPosition(); + viewHolder.currentPosition.setText( + String.format( + "%02d:%02d", + TimeUnit.MILLISECONDS.toMinutes(currentPosition), + TimeUnit.MILLISECONDS.toSeconds(currentPosition) + - TimeUnit.MINUTES.toSeconds( + TimeUnit.MILLISECONDS.toMinutes( + currentPosition)))); + } } - record.seek(progressToSet); - seekBar.setProgress(progressToSet); + @Override + public void onStartTrackingTouch(SeekBar seekBar) {} - int currentPosition = record.getCurrentPosition(); - viewHolder.currentPosition.setText(String.format("%02d:%02d", - TimeUnit.MILLISECONDS.toMinutes(currentPosition), - TimeUnit.MILLISECONDS.toSeconds(currentPosition) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(currentPosition)) - )); - } - } + @Override + public void onStopTrackingTouch(SeekBar seekBar) {} + }); - @Override - public void onStartTrackingTouch(SeekBar seekBar) { + record.setRecordingListener( + new RecordingListener() { + @Override + public void currentPositionChanged(int currentPosition) { + viewHolder.currentPosition.setText( + String.format( + "%02d:%02d", + TimeUnit.MILLISECONDS.toMinutes(currentPosition), + TimeUnit.MILLISECONDS.toSeconds(currentPosition) + - TimeUnit.MINUTES.toSeconds( + TimeUnit.MILLISECONDS.toMinutes( + currentPosition)))); + viewHolder.progressionBar.setProgress(currentPosition); + } - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - - } - }); - - record.setRecordingListener(new RecordingListener() { - @Override - public void currentPositionChanged(int currentPosition) { - viewHolder.currentPosition.setText(String.format("%02d:%02d", - TimeUnit.MILLISECONDS.toMinutes(currentPosition), - TimeUnit.MILLISECONDS.toSeconds(currentPosition) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(currentPosition)) - )); - viewHolder.progressionBar.setProgress(currentPosition); - } - - @Override - public void endOfRecordReached() { - record.pause(); - record.seek(0); - viewHolder.progressionBar.setProgress(0); - viewHolder.currentPosition.setText("00:00"); - viewHolder.playButton.setImageResource(R.drawable.record_play); - } - }); + @Override + public void endOfRecordReached() { + record.pause(); + record.seek(0); + viewHolder.progressionBar.setProgress(0); + viewHolder.currentPosition.setText("00:00"); + viewHolder.playButton.setImageResource(R.drawable.record_play); + } + }); } @Override @@ -191,7 +209,9 @@ public class RecordingAdapter extends SelectableAdapter { } else if (isYesterday(cal)) { return context.getString(R.string.yesterday); } else { - dateFormat = new SimpleDateFormat(context.getResources().getString(R.string.history_date_format)); + dateFormat = + new SimpleDateFormat( + context.getResources().getString(R.string.history_date_format)); } return dateFormat.format(cal.getTime()); @@ -202,9 +222,9 @@ public class RecordingAdapter extends SelectableAdapter { return false; } - return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) && - cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && - cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR)); + return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) + && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) + && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR)); } private boolean isToday(Calendar cal) { diff --git a/app/src/main/java/org/linphone/recording/RecordingListFragment.java b/app/src/main/java/org/linphone/recording/RecordingListFragment.java index 040008e80..0213dc4a6 100644 --- a/app/src/main/java/org/linphone/recording/RecordingListFragment.java +++ b/app/src/main/java/org/linphone/recording/RecordingListFragment.java @@ -22,15 +22,18 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import android.app.Fragment; import android.content.Context; import android.os.Bundle; -import android.support.v7.widget.DividerItemDecoration; -import android.support.v7.widget.LinearLayoutManager; -import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.TextView; - +import androidx.recyclerview.widget.DividerItemDecoration; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import java.io.File; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import org.linphone.LinphoneActivity; import org.linphone.LinphoneManager; import org.linphone.R; @@ -38,12 +41,10 @@ import org.linphone.fragments.FragmentsAvailable; import org.linphone.utils.FileUtils; import org.linphone.utils.SelectableHelper; -import java.io.File; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -public class RecordingListFragment extends Fragment implements AdapterView.OnItemClickListener, RecordingViewHolder.ClickListener, SelectableHelper.DeleteListener { +public class RecordingListFragment extends Fragment + implements AdapterView.OnItemClickListener, + RecordingViewHolder.ClickListener, + SelectableHelper.DeleteListener { private RecyclerView recordingList; private List recordings; private TextView noRecordings; @@ -53,8 +54,8 @@ public class RecordingListFragment extends Fragment implements AdapterView.OnIte private SelectableHelper selectableHelper; @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.recordings_list, container, false); context = getActivity().getApplicationContext(); @@ -66,9 +67,10 @@ public class RecordingListFragment extends Fragment implements AdapterView.OnIte layoutManager = new LinearLayoutManager(context); recordingList.setLayoutManager(layoutManager); - //Divider between items - DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recordingList.getContext(), - layoutManager.getOrientation()); + // Divider between items + DividerItemDecoration dividerItemDecoration = + new DividerItemDecoration( + recordingList.getContext(), layoutManager.getOrientation()); dividerItemDecoration.setDrawable(context.getResources().getDrawable(R.drawable.divider)); recordingList.addItemDecoration(dividerItemDecoration); @@ -94,9 +96,9 @@ public class RecordingListFragment extends Fragment implements AdapterView.OnIte if (directory.exists() && directory.isDirectory()) { File[] existingRecordings = directory.listFiles(); - for(Recording r : recordings) { + for (Recording r : recordings) { boolean exists = false; - for(File f : existingRecordings) { + for (File f : existingRecordings) { if (f.getPath().equals(r.getRecordPath())) { exists = true; break; @@ -117,9 +119,9 @@ public class RecordingListFragment extends Fragment implements AdapterView.OnIte if (directory.exists() && directory.isDirectory()) { File[] existingRecordings = directory.listFiles(); - for(File f : existingRecordings) { + for (File f : existingRecordings) { boolean exists = false; - for(Recording r : recordings) { + for (Recording r : recordings) { if (r.getRecordPath().equals(f.getPath())) { exists = true; break; @@ -141,7 +143,8 @@ public class RecordingListFragment extends Fragment implements AdapterView.OnIte public void onResume() { super.onResume(); - // This is necessary, without it you won't be able to remove recordings as you won't be allowed to. + // This is necessary, without it you won't be able to remove recordings as you won't be + // allowed to. LinphoneActivity.instance().checkAndRequestExternalStoragePermission(); LinphoneManager.getInstance().setAudioManagerModeNormal(); @@ -155,7 +158,9 @@ public class RecordingListFragment extends Fragment implements AdapterView.OnIte searchForRecordings(); hideRecordingListAndDisplayMessageIfEmpty(); - recordingAdapter = new RecordingAdapter(getActivity().getApplicationContext(), recordings, this, selectableHelper); + recordingAdapter = + new RecordingAdapter( + getActivity().getApplicationContext(), recordings, this, selectableHelper); recordingList.setAdapter(recordingAdapter); selectableHelper.setAdapter(recordingAdapter); selectableHelper.setDialogMessage(R.string.recordings_delete_dialog); diff --git a/app/src/main/java/org/linphone/recording/RecordingViewHolder.java b/app/src/main/java/org/linphone/recording/RecordingViewHolder.java index 7e3389038..838692da7 100644 --- a/app/src/main/java/org/linphone/recording/RecordingViewHolder.java +++ b/app/src/main/java/org/linphone/recording/RecordingViewHolder.java @@ -1,36 +1,35 @@ package org.linphone.recording; - /* - RecordingViewHolder.java - Copyright (C) 2018 Belledonne Communications, Grenoble, France +RecordingViewHolder.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 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. +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. - */ +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.support.v7.widget.RecyclerView; import android.view.View; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.SeekBar; import android.widget.TextView; - +import androidx.recyclerview.widget.RecyclerView; import org.linphone.R; -public class RecordingViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener { +public class RecordingViewHolder extends RecyclerView.ViewHolder + implements View.OnClickListener, View.OnLongClickListener { public ImageView playButton; public TextView name, date, currentPosition, duration; public SeekBar progressionBar; diff --git a/app/src/main/java/org/linphone/settings/AccountPreferencesFragment.java b/app/src/main/java/org/linphone/settings/AccountPreferencesFragment.java index 63f31c2db..aec9539f1 100644 --- a/app/src/main/java/org/linphone/settings/AccountPreferencesFragment.java +++ b/app/src/main/java/org/linphone/settings/AccountPreferencesFragment.java @@ -30,12 +30,11 @@ import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceCategory; import android.preference.PreferenceScreen; import android.view.WindowManager; - -import org.linphone.LinphoneManager; -import org.linphone.settings.LinphonePreferences.AccountBuilder; -import org.linphone.utils.LinphoneUtils; -import org.linphone.R; +import java.util.ArrayList; +import java.util.List; import org.linphone.LinphoneActivity; +import org.linphone.LinphoneManager; +import org.linphone.R; import org.linphone.assistant.AssistantActivity; import org.linphone.core.AccountCreator; import org.linphone.core.AccountCreatorListener; @@ -44,17 +43,276 @@ import org.linphone.core.NatPolicy; import org.linphone.core.ProxyConfig; import org.linphone.fragments.FragmentsAvailable; import org.linphone.mediastream.Log; +import org.linphone.settings.LinphonePreferences.AccountBuilder; +import org.linphone.utils.LinphoneUtils; -import java.util.ArrayList; -import java.util.List; - -public class AccountPreferencesFragment extends PreferencesListFragment implements AccountCreatorListener { +public class AccountPreferencesFragment extends PreferencesListFragment + implements AccountCreatorListener { private int n; + OnPreferenceClickListener linkAccountListener = + new OnPreferenceClickListener() { + @Override + public boolean onPreferenceClick(Preference preference) { + Intent assistant = new Intent(); + assistant.setClass(LinphoneActivity.instance(), AssistantActivity.class); + assistant.putExtra("LinkPhoneNumber", true); + assistant.putExtra("FromPref", true); + assistant.putExtra("AccountNumber", n); + startActivity(assistant); + return true; + } + }; private boolean isNewAccount = false; private LinphonePreferences mPrefs; + OnPreferenceChangeListener avpfRRIntervalChangedListener = + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange(Preference preference, Object newValue) { + String value = newValue.toString(); + try { + int intValue = Integer.parseInt(value); + if ((intValue < 1) || (intValue > 5)) { + return false; + } + } catch (NumberFormatException nfe) { + } + if (isNewAccount) { + // TODO + } else { + mPrefs.setAvpfRrInterval(n, value); + } + preference.setSummary(value); + return true; + } + }; + OnPreferenceChangeListener escapeChangedListener = + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange(Preference preference, Object newValue) { + boolean value = (Boolean) newValue; + if (isNewAccount) { + // TODO + } else { + mPrefs.setReplacePlusByZeroZero(n, value); + } + return true; + } + }; + OnPreferenceChangeListener pushNotificationListener = + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange(Preference preference, Object newValue) { + boolean value = (Boolean) newValue; + if (isNewAccount) { + // TODO + } else { + mPrefs.enablePushNotifForProxy(n, value); + } + return true; + } + }; + OnPreferenceChangeListener iceChangedListener = + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange(Preference preference, Object newValue) { + boolean value = (Boolean) newValue; + if (isNewAccount) { + } else { + mPrefs.setAccountIce(n, value); + ((CheckBoxPreference) preference).setChecked(mPrefs.getAccountIce(n)); + } + return true; + } + }; + OnPreferenceChangeListener stunTurnChangedListener = + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange(Preference preference, Object newValue) { + String value = newValue.toString(); + if (isNewAccount) { + } else { + mPrefs.setAccountStunServer(n, value); + preference.setSummary(value); + } + return true; + } + }; private EditTextPreference mProxyPreference; + OnPreferenceChangeListener transportChangedListener = + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange(Preference preference, Object newValue) { + String key = newValue.toString(); + if (isNewAccount) { + // TODO + // builder.setTransport(transport); + } else { + mPrefs.setAccountTransport(n, key); + preference.setSummary(mPrefs.getAccountTransportString(n)); + preference.setDefaultValue(mPrefs.getAccountTransportKey(n)); + if (mProxyPreference != null) { + String newProxy = mPrefs.getAccountProxy(n); + mProxyPreference.setSummary(newProxy); + mProxyPreference.setText(newProxy); + } + } + return true; + } + }; private ListPreference mTransportPreference; private AccountBuilder builder; + OnPreferenceChangeListener usernameChangedListener = + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange(Preference preference, Object newValue) { + if (isEditTextEmpty(newValue.toString())) return false; + if (isNewAccount) { + builder.setUsername(newValue.toString()); + } else { + mPrefs.setAccountUsername(n, newValue.toString()); + } + preference.setSummary(newValue.toString()); + return true; + } + }; + OnPreferenceChangeListener useridChangedListener = + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange(Preference preference, Object newValue) { + if (isNewAccount) { + builder.setUserid(newValue.toString()); + } else { + mPrefs.setAccountUserId(n, newValue.toString()); + } + preference.setSummary(newValue.toString()); + return true; + } + }; + OnPreferenceChangeListener passwordChangedListener = + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange(Preference preference, Object newValue) { + if (isEditTextEmpty(newValue.toString())) return false; + if (isNewAccount) { + builder.setPassword(newValue.toString()); + } else { + mPrefs.setAccountPassword(n, newValue.toString()); + } + return true; + } + }; + OnPreferenceChangeListener domainChangedListener = + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange(Preference preference, Object newValue) { + if (isEditTextEmpty(newValue.toString())) return false; + if (isNewAccount) { + builder.setDomain(newValue.toString()); + } else { + mPrefs.setAccountDomain(n, newValue.toString()); + } + preference.setSummary(newValue.toString()); + return true; + } + }; + OnPreferenceChangeListener displayNameChangedListener = + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange(Preference preference, Object newValue) { + if (isNewAccount) { + builder.setDisplayName(newValue.toString()); + } else { + mPrefs.setAccountDisplayName(n, newValue.toString()); + } + preference.setSummary(newValue.toString()); + return true; + } + }; + OnPreferenceChangeListener proxyChangedListener = + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange(Preference preference, Object newValue) { + String value = newValue.toString(); + if (isNewAccount) { + builder.setServerAddr(newValue.toString()); + preference.setSummary(newValue.toString()); + } else { + mPrefs.setAccountProxy(n, value); + preference.setSummary(mPrefs.getAccountProxy(n)); + + if (mTransportPreference != null) { + mTransportPreference.setSummary(mPrefs.getAccountTransportString(n)); + mTransportPreference.setValue(mPrefs.getAccountTransportKey(n)); + } + } + return true; + } + }; + OnPreferenceChangeListener outboundProxyChangedListener = + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange(Preference preference, Object newValue) { + if (isNewAccount) { + builder.setOutboundProxyEnabled((Boolean) newValue); + } else { + mPrefs.setAccountOutboundProxyEnabled(n, (Boolean) newValue); + } + return true; + } + }; + OnPreferenceChangeListener expiresChangedListener = + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange(Preference preference, Object newValue) { + if (isNewAccount) { + builder.setExpires(newValue.toString()); + } else { + mPrefs.setExpires(n, newValue.toString()); + } + preference.setSummary(newValue.toString()); + return true; + } + }; + OnPreferenceChangeListener prefixChangedListener = + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange(Preference preference, Object newValue) { + String value = newValue.toString(); + preference.setSummary(value); + if (isNewAccount) { + builder.setPrefix(value); + } else { + mPrefs.setPrefix(n, value); + } + return true; + } + }; + OnPreferenceChangeListener avpfChangedListener = + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange(Preference preference, Object newValue) { + boolean value = (Boolean) newValue; + if (isNewAccount) { + builder.setAvpfEnabled(value); + } else { + mPrefs.setAvpfMode(n, value); + } + return true; + } + }; + OnPreferenceChangeListener disableChangedListener = + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange(Preference preference, Object newValue) { + boolean value = (Boolean) newValue; + if (isNewAccount) { + builder.setEnabled(!value); + } else { + mPrefs.setAccountEnabled(n, !value); + } + return true; + } + }; private AccountCreator accountCreator; private ProgressDialog progress; @@ -63,6 +321,20 @@ public class AccountPreferencesFragment extends PreferencesListFragment implemen mPrefs = LinphonePreferences.instance(); } + public static boolean isEditTextEmpty(String s) { + return s.equals(""); // really empty. + } + + private static void setListPreferenceValues( + ListPreference pref, List entries, List values) { + CharSequence[] contents = new CharSequence[entries.size()]; + entries.toArray(contents); + pref.setEntries(contents); + contents = new CharSequence[values.size()]; + values.toArray(contents); + pref.setEntryValues(contents); + } + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -75,263 +347,17 @@ public class AccountPreferencesFragment extends PreferencesListFragment implemen initAccountPreferencesFields(screen); // Force hide keyboard - getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + getActivity() + .getWindow() + .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); } - public static boolean isEditTextEmpty(String s) { - return s.equals(""); // really empty. - } - - OnPreferenceChangeListener usernameChangedListener = new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - if (isEditTextEmpty(newValue.toString())) return false; - if (isNewAccount) { - builder.setUsername(newValue.toString()); - } else { - mPrefs.setAccountUsername(n, newValue.toString()); - } - preference.setSummary(newValue.toString()); - return true; - } - }; - OnPreferenceChangeListener useridChangedListener = new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - if (isNewAccount) { - builder.setUserid(newValue.toString()); - } else { - mPrefs.setAccountUserId(n, newValue.toString()); - } - preference.setSummary(newValue.toString()); - return true; - } - }; - OnPreferenceChangeListener passwordChangedListener = new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - if (isEditTextEmpty(newValue.toString())) return false; - if (isNewAccount) { - builder.setPassword(newValue.toString()); - } else { - mPrefs.setAccountPassword(n, newValue.toString()); - } - return true; - } - }; - OnPreferenceChangeListener domainChangedListener = new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - if (isEditTextEmpty(newValue.toString())) return false; - if (isNewAccount) { - builder.setDomain(newValue.toString()); - } else { - mPrefs.setAccountDomain(n, newValue.toString()); - } - preference.setSummary(newValue.toString()); - return true; - } - }; - OnPreferenceChangeListener displayNameChangedListener = new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - if (isNewAccount) { - builder.setDisplayName(newValue.toString()); - } else { - mPrefs.setAccountDisplayName(n, newValue.toString()); - } - preference.setSummary(newValue.toString()); - return true; - } - }; - OnPreferenceChangeListener proxyChangedListener = new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - String value = newValue.toString(); - if (isNewAccount) { - builder.setServerAddr(newValue.toString()); - preference.setSummary(newValue.toString()); - } else { - mPrefs.setAccountProxy(n, value); - preference.setSummary(mPrefs.getAccountProxy(n)); - - if (mTransportPreference != null) { - mTransportPreference.setSummary(mPrefs.getAccountTransportString(n)); - mTransportPreference.setValue(mPrefs.getAccountTransportKey(n)); - } - } - return true; - } - }; - OnPreferenceChangeListener outboundProxyChangedListener = new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - if (isNewAccount) { - builder.setOutboundProxyEnabled((Boolean) newValue); - } else { - mPrefs.setAccountOutboundProxyEnabled(n, (Boolean) newValue); - } - return true; - } - }; - OnPreferenceChangeListener expiresChangedListener = new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - if (isNewAccount) { - builder.setExpires(newValue.toString()); - } else { - mPrefs.setExpires(n, newValue.toString()); - } - preference.setSummary(newValue.toString()); - return true; - } - }; - OnPreferenceChangeListener prefixChangedListener = new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - String value = newValue.toString(); - preference.setSummary(value); - if (isNewAccount) { - builder.setPrefix(value); - } else { - mPrefs.setPrefix(n, value); - } - return true; - } - }; - OnPreferenceChangeListener avpfChangedListener = new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - boolean value = (Boolean) newValue; - if (isNewAccount) { - builder.setAvpfEnabled(value); - } else { - mPrefs.setAvpfMode(n, value); - } - return true; - } - }; - OnPreferenceChangeListener avpfRRIntervalChangedListener = new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - String value = newValue.toString(); - try { - int intValue = Integer.parseInt(value); - if ((intValue < 1) || (intValue > 5)) { - return false; - } - } catch (NumberFormatException nfe) { - } - if (isNewAccount) { - //TODO - } else { - mPrefs.setAvpfRrInterval(n, value); - } - preference.setSummary(value); - return true; - } - }; - OnPreferenceChangeListener escapeChangedListener = new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - boolean value = (Boolean) newValue; - if (isNewAccount) { - //TODO - } else { - mPrefs.setReplacePlusByZeroZero(n, value); - } - return true; - } - }; - OnPreferenceClickListener linkAccountListener = new OnPreferenceClickListener() { - @Override - public boolean onPreferenceClick(Preference preference) { - Intent assistant = new Intent(); - assistant.setClass(LinphoneActivity.instance(), AssistantActivity.class); - assistant.putExtra("LinkPhoneNumber", true); - assistant.putExtra("FromPref", true); - assistant.putExtra("AccountNumber", n); - startActivity(assistant); - return true; - } - }; - OnPreferenceChangeListener pushNotificationListener = new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - boolean value = (Boolean) newValue; - if (isNewAccount) { - //TODO - } else { - mPrefs.enablePushNotifForProxy(n, value); - } - return true; - } - }; - OnPreferenceChangeListener disableChangedListener = new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - boolean value = (Boolean) newValue; - if (isNewAccount) { - builder.setEnabled(!value); - } else { - mPrefs.setAccountEnabled(n, !value); - } - return true; - } - }; - OnPreferenceChangeListener transportChangedListener = new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - String key = newValue.toString(); - if (isNewAccount) { - //TODO - //builder.setTransport(transport); - } else { - mPrefs.setAccountTransport(n, key); - preference.setSummary(mPrefs.getAccountTransportString(n)); - preference.setDefaultValue(mPrefs.getAccountTransportKey(n)); - if (mProxyPreference != null) { - String newProxy = mPrefs.getAccountProxy(n); - mProxyPreference.setSummary(newProxy); - mProxyPreference.setText(newProxy); - } - } - return true; - } - }; - - OnPreferenceChangeListener iceChangedListener = new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - boolean value = (Boolean) newValue; - if (isNewAccount) { - } else { - mPrefs.setAccountIce(n, value); - ((CheckBoxPreference) preference).setChecked(mPrefs.getAccountIce(n)); - } - return true; - } - }; - - OnPreferenceChangeListener stunTurnChangedListener = new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - String value = newValue.toString(); - if (isNewAccount) { - } else { - mPrefs.setAccountStunServer(n, value); - preference.setSummary(value); - } - return true; - } - }; - private void initAccountPreferencesFields(PreferenceScreen parent) { boolean isDefaultAccount = mPrefs.getDefaultAccountIndex() == n; NatPolicy natPolicy = null; - if (LinphoneManager.getLcIfManagerNotDestroyedOrNull() != null && - LinphoneManager.getLc().getProxyConfigList() != null && - LinphoneManager.getLc().getProxyConfigList().length > n) { + if (LinphoneManager.getLcIfManagerNotDestroyedOrNull() != null + && LinphoneManager.getLc().getProxyConfigList() != null + && LinphoneManager.getLc().getProxyConfigList().length > n) { ProxyConfig proxy = LinphoneManager.getLc().getProxyConfigList()[n]; natPolicy = proxy.getNatPolicy(); if (natPolicy == null) { @@ -342,10 +368,15 @@ public class AccountPreferencesFragment extends PreferencesListFragment implemen } } - accountCreator = LinphoneManager.getLc().createAccountCreator(LinphonePreferences.instance().getXmlrpcUrl()); + accountCreator = + LinphoneManager.getLc() + .createAccountCreator(LinphonePreferences.instance().getXmlrpcUrl()); accountCreator.setListener(this); - final PreferenceCategory account = (PreferenceCategory) getPreferenceScreen().findPreference(getString(R.string.pref_sipaccount_key)); + final PreferenceCategory account = + (PreferenceCategory) + getPreferenceScreen() + .findPreference(getString(R.string.pref_sipaccount_key)); EditTextPreference username = (EditTextPreference) account.getPreference(0); username.setOnPreferenceChangeListener(usernameChangedListener); if (!isNewAccount) { @@ -380,7 +411,9 @@ public class AccountPreferencesFragment extends PreferencesListFragment implemen displayName.setSummary(displayName.getText()); } - PreferenceCategory advanced = (PreferenceCategory) getPreferenceScreen().findPreference(getString(R.string.pref_advanced_key)); + PreferenceCategory advanced = + (PreferenceCategory) + getPreferenceScreen().findPreference(getString(R.string.pref_advanced_key)); mTransportPreference = (ListPreference) advanced.getPreference(0); initializeTransportPreference(mTransportPreference); mTransportPreference.setOnPreferenceChangeListener(transportChangedListener); @@ -390,8 +423,7 @@ public class AccountPreferencesFragment extends PreferencesListFragment implemen CheckBoxPreference ice = (CheckBoxPreference) advanced.getPreference(1); ice.setOnPreferenceChangeListener(iceChangedListener); - if (natPolicy != null) - ice.setChecked(natPolicy.iceEnabled()); + if (natPolicy != null) ice.setChecked(natPolicy.iceEnabled()); EditTextPreference stunTurn = (EditTextPreference) advanced.getPreference(2); stunTurn.setOnPreferenceChangeListener(stunTurnChangedListener); @@ -404,7 +436,10 @@ public class AccountPreferencesFragment extends PreferencesListFragment implemen mProxyPreference.setOnPreferenceChangeListener(proxyChangedListener); if (!isNewAccount) { mProxyPreference.setText(mPrefs.getAccountProxy(n)); - mProxyPreference.setSummary("".equals(mProxyPreference.getText()) || (mProxyPreference.getText() == null) ? getString(R.string.pref_help_proxy) : mProxyPreference.getText()); + mProxyPreference.setSummary( + "".equals(mProxyPreference.getText()) || (mProxyPreference.getText() == null) + ? getString(R.string.pref_help_proxy) + : mProxyPreference.getText()); } CheckBoxPreference outboundProxy = (CheckBoxPreference) advanced.getPreference(4); @@ -456,7 +491,9 @@ public class AccountPreferencesFragment extends PreferencesListFragment implemen pushNotif.setChecked(mPrefs.isPushNotifEnabledForProxy(n)); } - PreferenceCategory manage = (PreferenceCategory) getPreferenceScreen().findPreference(getString(R.string.pref_manage_key)); + PreferenceCategory manage = + (PreferenceCategory) + getPreferenceScreen().findPreference(getString(R.string.pref_manage_key)); final CheckBoxPreference disable = (CheckBoxPreference) manage.getPreference(0); disable.setEnabled(true); disable.setOnPreferenceChangeListener(disableChangedListener); @@ -467,15 +504,16 @@ public class AccountPreferencesFragment extends PreferencesListFragment implemen CheckBoxPreference mainAccount = (CheckBoxPreference) manage.getPreference(1); mainAccount.setChecked(isDefaultAccount); mainAccount.setEnabled(!mainAccount.isChecked()); - mainAccount.setOnPreferenceClickListener(new OnPreferenceClickListener() { - public boolean onPreferenceClick(Preference preference) { - mPrefs.setDefaultAccount(n); - disable.setEnabled(false); - disable.setChecked(false); - preference.setEnabled(false); - return true; - } - }); + mainAccount.setOnPreferenceClickListener( + new OnPreferenceClickListener() { + public boolean onPreferenceClick(Preference preference) { + mPrefs.setDefaultAccount(n); + disable.setEnabled(false); + disable.setChecked(false); + preference.setEnabled(false); + return true; + } + }); if (!isNewAccount) { mainAccount.setEnabled(!mainAccount.isChecked()); } @@ -485,14 +523,15 @@ public class AccountPreferencesFragment extends PreferencesListFragment implemen final Preference delete = manage.getPreference(3); delete.setEnabled(!isNewAccount); - delete.setOnPreferenceClickListener(new OnPreferenceClickListener() { - public boolean onPreferenceClick(Preference preference) { - mPrefs.deleteAccount(n); - LinphoneActivity.instance().displaySettings(); - LinphoneActivity.instance().refreshAccounts(); - return true; - } - }); + delete.setOnPreferenceClickListener( + new OnPreferenceClickListener() { + public boolean onPreferenceClick(Preference preference) { + mPrefs.deleteAccount(n); + LinphoneActivity.instance().displaySettings(); + LinphoneActivity.instance().refreshAccounts(); + return true; + } + }); } private void initializeTransportPreference(ListPreference pref) { @@ -521,15 +560,6 @@ public class AccountPreferencesFragment extends PreferencesListFragment implemen } } - private static void setListPreferenceValues(ListPreference pref, List entries, List values) { - CharSequence[] contents = new CharSequence[entries.size()]; - entries.toArray(contents); - pref.setEntries(contents); - contents = new CharSequence[values.size()]; - values.toArray(contents); - pref.setEntryValues(contents); - } - @Override public void onResume() { super.onResume(); @@ -557,58 +587,57 @@ public class AccountPreferencesFragment extends PreferencesListFragment implemen } @Override - public void onUpdateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { + public void onUpdateAccount( + AccountCreator accountCreator, AccountCreator.Status status, String resp) { if (progress != null) progress.dismiss(); if (status.equals(AccountCreator.Status.RequestOk)) { mPrefs.setAccountPassword(n, accountCreator.getPassword()); - PreferenceCategory account = (PreferenceCategory) getPreferenceScreen().findPreference(getString(R.string.pref_sipaccount_key)); + PreferenceCategory account = + (PreferenceCategory) + getPreferenceScreen() + .findPreference(getString(R.string.pref_sipaccount_key)); ((EditTextPreference) account.getPreference(2)).setText(mPrefs.getAccountPassword(n)); - LinphoneUtils.displayErrorAlert(getString(R.string.pref_password_changed), LinphoneActivity.instance()); + LinphoneUtils.displayErrorAlert( + getString(R.string.pref_password_changed), LinphoneActivity.instance()); } else { - LinphoneUtils.displayErrorAlert(LinphoneUtils.errorForStatus(status), LinphoneActivity.instance()); + LinphoneUtils.displayErrorAlert( + LinphoneUtils.errorForStatus(status), LinphoneActivity.instance()); } } @Override - public void onIsAccountExist(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - } + public void onIsAccountExist( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onCreateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - - } + public void onCreateAccount( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onActivateAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - - } + public void onActivateAccount( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onLinkAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - - } + public void onLinkAccount( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onActivateAlias(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - - } + public void onActivateAlias( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onIsAccountActivated(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - - } + public void onIsAccountActivated( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onRecoverAccount(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - - } + public void onRecoverAccount( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onIsAccountLinked(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - - } + public void onIsAccountLinked( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} @Override - public void onIsAliasUsed(AccountCreator accountCreator, AccountCreator.Status status, String resp) { - } + public void onIsAliasUsed( + AccountCreator accountCreator, AccountCreator.Status status, String resp) {} } diff --git a/app/src/main/java/org/linphone/settings/LinphonePreferences.java b/app/src/main/java/org/linphone/settings/LinphonePreferences.java index 103c30d41..c58ca3a42 100644 --- a/app/src/main/java/org/linphone/settings/LinphonePreferences.java +++ b/app/src/main/java/org/linphone/settings/LinphonePreferences.java @@ -22,9 +22,13 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; - +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.ArrayList; import org.linphone.LinphoneManager; -import org.linphone.utils.LinphoneUtils; import org.linphone.R; import org.linphone.core.AVPFMode; import org.linphone.core.Address; @@ -44,19 +48,17 @@ import org.linphone.core.TunnelConfig; import org.linphone.core.VideoActivationPolicy; import org.linphone.mediastream.Log; import org.linphone.purchase.Purchasable; - -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.ArrayList; +import org.linphone.utils.LinphoneUtils; public class LinphonePreferences { private static final int LINPHONE_CORE_RANDOM_PORT = -1; private static LinphonePreferences instance; private Context mContext; private String basePath; + // Tunnel settings + private TunnelConfig tunnelConfig = null; + + private LinphonePreferences() {} public static final synchronized LinphonePreferences instance() { if (instance == null) { @@ -65,10 +67,6 @@ public class LinphonePreferences { return instance; } - private LinphonePreferences() { - - } - public void setContext(Context c) { mContext = c; basePath = mContext.getFilesDir().getAbsolutePath(); @@ -83,8 +81,7 @@ public class LinphonePreferences { } private Core getLc() { - if (!LinphoneManager.isInstanciated()) - return null; + if (!LinphoneManager.isInstanciated()) return null; return LinphoneManager.getLcIfManagerNotDestroyedOrNull(); } @@ -100,7 +97,8 @@ public class LinphonePreferences { if (linphonerc.exists()) { return Factory.instance().createConfig(linphonerc.getAbsolutePath()); } else if (mContext != null) { - InputStream inputStream = mContext.getResources().openRawResource(R.raw.linphonerc_default); + InputStream inputStream = + mContext.getResources().openRawResource(R.raw.linphonerc_default); InputStreamReader inputreader = new InputStreamReader(inputStream); BufferedReader buffreader = new BufferedReader(inputreader); StringBuilder text = new StringBuilder(); @@ -136,27 +134,24 @@ public class LinphonePreferences { public String getRingtone(String defaultRingtone) { String ringtone = getConfig().getString("app", "ringtone", defaultRingtone); - if (ringtone == null || ringtone.length() == 0) - ringtone = defaultRingtone; + if (ringtone == null || ringtone.length() == 0) ringtone = defaultRingtone; return ringtone; } public void setRingtone(String ringtonePath) { getConfig().setString("app", "ringtone", ringtonePath); - - } - - public boolean shouldAutomaticallyAcceptFriendsRequests() { - return false; //TODO } // End of app settings + public boolean shouldAutomaticallyAcceptFriendsRequests() { + return false; // TODO + } + // Accounts settings private ProxyConfig getProxyConfig(int n) { if (getLc() == null) return null; ProxyConfig[] prxCfgs = getLc().getProxyConfigList(); - if (n < 0 || n >= prxCfgs.length) - return null; + if (n < 0 || n >= prxCfgs.length) return null; return prxCfgs[n]; } @@ -169,29 +164,1329 @@ public class LinphonePreferences { } /** - * Removes a authInfo from the core and returns a copy of it. - * Useful to edit a authInfo (you should call saveAuthInfo after the modifications to save them). + * Removes a authInfo from the core and returns a copy of it. Useful to edit a authInfo (you + * should call saveAuthInfo after the modifications to save them). */ private AuthInfo getClonedAuthInfo(int n) { if (getLc() == null) return null; AuthInfo authInfo = getAuthInfo(n); - if (authInfo == null) - return null; + if (authInfo == null) return null; AuthInfo cloneAuthInfo = authInfo.clone(); getLc().removeAuthInfo(authInfo); return cloneAuthInfo; } - /** - * Saves a authInfo into the core. - * Useful to save the changes made to a cloned authInfo. - */ + /** Saves a authInfo into the core. Useful to save the changes made to a cloned authInfo. */ private void saveAuthInfo(AuthInfo authInfo) { if (getLc() == null) return; getLc().addAuthInfo(authInfo); } + public void setAccountTransport(int n, String transport) { + ProxyConfig proxyConfig = getProxyConfig(n); + + if (proxyConfig != null && transport != null) { + Address proxyAddr; + proxyAddr = Factory.instance().createAddress(proxyConfig.getServerAddr()); + int port = 0; + if (transport.equals(getString(R.string.pref_transport_udp_key))) { + proxyAddr.setTransport(TransportType.Udp); + + } else if (transport.equals(getString(R.string.pref_transport_tcp_key))) { + proxyAddr.setTransport(TransportType.Tcp); + } else if (transport.equals(getString(R.string.pref_transport_tls_key))) { + proxyAddr.setTransport(TransportType.Tls); + port = 5223; + } + + /* 3G mobile firewall might block random TLS port, so we force use of 5223. + * However we must NOT use this port when changing to TCP/UDP because otherwise + * REGISTER (and everything actually) will fail... + * */ + if ("sip.linphone.org".equals(proxyConfig.getDomain())) { + proxyAddr.setPort(port); + } + + ProxyConfig prxCfg = getProxyConfig(n); + prxCfg.edit(); + prxCfg.setServerAddr(proxyAddr.asStringUriOnly()); + prxCfg.done(); + + if (isAccountOutboundProxySet(n)) { + setAccountOutboundProxyEnabled(n, true); + } + } + } + + public TransportType getAccountTransport(int n) { + TransportType transport = null; + ProxyConfig proxyConfig = getProxyConfig(n); + + if (proxyConfig != null) { + Address proxyAddr; + proxyAddr = Factory.instance().createAddress(proxyConfig.getServerAddr()); + transport = proxyAddr.getTransport(); + } + + return transport; + } + + public String getAccountTransportKey(int n) { + TransportType transport = getAccountTransport(n); + String key = getString(R.string.pref_transport_udp_key); + + if (transport != null && transport == TransportType.Tcp) + key = getString(R.string.pref_transport_tcp_key); + else if (transport != null && transport == TransportType.Tls) + key = getString(R.string.pref_transport_tls_key); + + return key; + } + + public String getAccountTransportString(int n) { + TransportType transport = getAccountTransport(n); + + if (transport != null && transport == TransportType.Tcp) + return getString(R.string.pref_transport_tcp); + else if (transport != null && transport == TransportType.Tls) + return getString(R.string.pref_transport_tls); + + return getString(R.string.pref_transport_udp); + } + + public void setAccountUsername(int n, String username) { + String identity = "sip:" + username + "@" + getAccountDomain(n); + AuthInfo old_info = getAuthInfo(n); + ProxyConfig prxCfg = getProxyConfig(n); + if (prxCfg == null) { + Log.e("Error, no proxy config at index " + n); + return; + } + prxCfg.edit(); + prxCfg.setIdentityAddress(Factory.instance().createAddress(identity)); + prxCfg.enableRegister(true); + prxCfg.done(); + + if (old_info != null) { + // We have to remove the previous auth info after otherwise we can't unregister the + // previous proxy config + AuthInfo new_info = old_info.clone(); + getLc().removeAuthInfo(old_info); + new_info.setUsername(username); + saveAuthInfo(new_info); + } + } + + public String getAccountUsername(int n) { + AuthInfo authInfo = getAuthInfo(n); + return authInfo == null ? null : authInfo.getUsername(); + } + + public void setAccountDisplayName(int n, String displayName) { + try { + ProxyConfig prxCfg = getProxyConfig(n); + Address addr = prxCfg.getIdentityAddress(); + addr.setDisplayName(displayName); + prxCfg.edit(); + prxCfg.setIdentityAddress(addr); + prxCfg.done(); + } catch (Exception e) { + Log.e(e); + } + } + + public String getAccountDisplayName(int n) { + if (getProxyConfig(n) == null || getProxyConfig(n).getIdentityAddress() == null) + return null; + return getProxyConfig(n).getIdentityAddress().getDisplayName(); + } + + public void setAccountUserId(int n, String userId) { + AuthInfo info = getClonedAuthInfo(n); + if (info != null) { + info.setUserid(userId); + saveAuthInfo(info); + } + } + + public String getAccountUserId(int n) { + AuthInfo authInfo = getAuthInfo(n); + return authInfo == null ? null : authInfo.getUserid(); + } + + public String getAccountRealm(int n) { + AuthInfo authInfo = getAuthInfo(n); + return authInfo == null ? null : authInfo.getRealm(); + } + + public void setAccountPassword(int n, String password) { + setAccountPassword(n, password, null); + } + + public void setAccountHa1(int n, String ha1) { + setAccountPassword(n, null, ha1); + } + + private void setAccountPassword(int n, String password, String ha1) { + if (getLc() == null) return; + String user = getAccountUsername(n); + String domain = getAccountDomain(n); + String userid = null; + String realm = null; + if (user != null && domain != null) { + if (LinphoneManager.getLc().getAuthInfoList().length > n + && LinphoneManager.getLc().getAuthInfoList()[n] != null) { + userid = getAccountUserId(n); + realm = getAccountRealm(n); + LinphoneManager.getLc() + .removeAuthInfo(LinphoneManager.getLc().getAuthInfoList()[n]); + } + AuthInfo authInfo = + Factory.instance().createAuthInfo(user, userid, password, ha1, realm, domain); + LinphoneManager.getLc().addAuthInfo(authInfo); + } + } + + public String getAccountPassword(int n) { + AuthInfo authInfo = getAuthInfo(n); + return authInfo == null ? null : authInfo.getPassword(); + } + + public String getAccountHa1(int n) { + AuthInfo authInfo = getAuthInfo(n); + return authInfo == null ? null : authInfo.getHa1(); + } + + public void setAccountIce(int n, boolean ice) { + try { + ProxyConfig prxCfg = getProxyConfig(n); + prxCfg.edit(); + prxCfg.getNatPolicy().enableIce(ice); + prxCfg.getNatPolicy().enableStun(ice); + prxCfg.done(); + } catch (Exception e) { + Log.e(e); + } + } + + public boolean getAccountIce(int n) { + if (getProxyConfig(n) == null || getProxyConfig(n).getNatPolicy() == null) return false; + return getProxyConfig(n).getNatPolicy().iceEnabled(); + } + + public void setAccountStunServer(int n, String stun) { + try { + ProxyConfig prxCfg = getProxyConfig(n); + prxCfg.edit(); + NatPolicy np = prxCfg.getNatPolicy(); + np.setStunServer(stun); + prxCfg.done(); + } catch (Exception e) { + Log.e(e); + } + } + + public String getAccountStunServer(int n) { + if (getProxyConfig(n) == null || getProxyConfig(n).getNatPolicy() == null) return ""; + return getProxyConfig(n).getNatPolicy().getStunServer(); + } + + public void setAccountDomain(int n, String domain) { + String identity = "sip:" + getAccountUsername(n) + "@" + domain; + AuthInfo old_info = getAuthInfo(n); + ProxyConfig prxCfg = getProxyConfig(n); + prxCfg.edit(); + prxCfg.setIdentityAddress(Factory.instance().createAddress(identity)); + prxCfg.enableRegister(true); + prxCfg.done(); + + if (old_info != null) { + // We have to remove the previous auth info after otherwise we can't unregister the + // previous proxy config + AuthInfo new_info = old_info.clone(); + getLc().removeAuthInfo(old_info); + new_info.setDomain(domain); + saveAuthInfo(new_info); + } + } + + public String getAccountDomain(int n) { + ProxyConfig proxyConf = getProxyConfig(n); + return (proxyConf != null) ? proxyConf.getDomain() : ""; + } + + public void setAccountProxy(int n, String proxy) { + if (proxy == null || proxy.length() <= 0) { + proxy = getAccountDomain(n); + } + + if (!proxy.contains("sip:")) { + proxy = "sip:" + proxy; + } + + Address proxyAddr = Factory.instance().createAddress(proxy); + if (proxyAddr == null) return; + + if (!proxy.contains("transport=")) { + proxyAddr.setTransport(getAccountTransport(n)); + } + + ProxyConfig prxCfg = getProxyConfig(n); + prxCfg.edit(); + prxCfg.setServerAddr(proxyAddr.asStringUriOnly()); + prxCfg.done(); + + if (isAccountOutboundProxySet(n)) { + setAccountOutboundProxyEnabled(n, true); + } + } + + public String getAccountProxy(int n) { + String proxy = getProxyConfig(n).getServerAddr(); + return proxy; + } + + public void setAccountOutboundProxyEnabled(int n, boolean enabled) { + ProxyConfig prxCfg = getProxyConfig(n); + prxCfg.edit(); + if (enabled) { + String route = prxCfg.getServerAddr(); + prxCfg.setRoute(route); + } else { + prxCfg.setRoute(null); + } + prxCfg.done(); + } + + public boolean isAccountOutboundProxySet(int n) { + return getProxyConfig(n).getRoute() != null; + } + + public void setAccountContactParameters(int n, String contactParams) { + ProxyConfig prxCfg = getProxyConfig(n); + prxCfg.edit(); + prxCfg.setContactUriParameters(contactParams); + prxCfg.done(); + } + + public String getExpires(int n) { + return String.valueOf(getProxyConfig(n).getExpires()); + } + + public void setExpires(int n, String expire) { + try { + ProxyConfig prxCfg = getProxyConfig(n); + prxCfg.edit(); + prxCfg.setExpires(Integer.parseInt(expire)); + prxCfg.done(); + } catch (NumberFormatException nfe) { + } + } + + public String getPrefix(int n) { + return getProxyConfig(n).getDialPrefix(); + } + + public void setPrefix(int n, String prefix) { + ProxyConfig prxCfg = getProxyConfig(n); + prxCfg.edit(); + prxCfg.setDialPrefix(prefix); + prxCfg.done(); + } + + public boolean avpfEnabled(int n) { + return getProxyConfig(n).avpfEnabled(); + } + + public void setAvpfMode(int n, boolean enable) { + ProxyConfig prxCfg = getProxyConfig(n); + prxCfg.edit(); + prxCfg.setAvpfMode(enable ? AVPFMode.Enabled : AVPFMode.Disabled); + prxCfg.done(); + } + + public String getAvpfRrInterval(int n) { + return String.valueOf(getProxyConfig(n).getAvpfRrInterval()); + } + + public void setAvpfRrInterval(int n, String interval) { + try { + ProxyConfig prxCfg = getProxyConfig(n); + prxCfg.edit(); + prxCfg.setAvpfRrInterval(Integer.parseInt(interval)); + prxCfg.done(); + } catch (NumberFormatException nfe) { + } + } + + public boolean getReplacePlusByZeroZero(int n) { + return getProxyConfig(n).getDialEscapePlus(); + } + + public void setReplacePlusByZeroZero(int n, boolean replace) { + ProxyConfig prxCfg = getProxyConfig(n); + prxCfg.edit(); + prxCfg.setDialEscapePlus(replace); + prxCfg.done(); + } + + public void enablePushNotifForProxy(int n, boolean enable) { + ProxyConfig prxCfg = getProxyConfig(n); + prxCfg.edit(); + prxCfg.setPushNotificationAllowed(enable); + prxCfg.done(); + + setPushNotificationEnabled(isPushNotificationEnabled()); + } + + public boolean isPushNotifEnabledForProxy(int n) { + ProxyConfig prxCfg = getProxyConfig(n); + return prxCfg.isPushNotificationAllowed(); + } + + public boolean isFriendlistsubscriptionEnabled() { + return getConfig().getBool("app", "friendlist_subscription_enabled", false); + } + + public void enabledFriendlistSubscription(boolean enabled) { + getConfig().setBool("app", "friendlist_subscription_enabled", enabled); + } + + public void setDefaultAccount(int accountIndex) { + if (getLc() == null) return; + ProxyConfig[] prxCfgs = getLc().getProxyConfigList(); + if (accountIndex >= 0 && accountIndex < prxCfgs.length) + getLc().setDefaultProxyConfig(prxCfgs[accountIndex]); + } + + public int getDefaultAccountIndex() { + if (getLc() == null) return -1; + ProxyConfig defaultPrxCfg = getLc().getDefaultProxyConfig(); + if (defaultPrxCfg == null) return -1; + + ProxyConfig[] prxCfgs = getLc().getProxyConfigList(); + for (int i = 0; i < prxCfgs.length; i++) { + if (defaultPrxCfg.getIdentityAddress().equals(prxCfgs[i].getIdentityAddress())) { + return i; + } + } + return -1; + } + + public int getAccountCount() { + if (getLc() == null || getLc().getProxyConfigList() == null) return 0; + + return getLc().getProxyConfigList().length; + } + + public void setAccountEnabled(int n, boolean enabled) { + if (getLc() == null) return; + ProxyConfig prxCfg = getProxyConfig(n); + if (prxCfg == null) { + LinphoneUtils.displayErrorAlert(getString(R.string.error), mContext); + return; + } + prxCfg.edit(); + prxCfg.enableRegister(enabled); + prxCfg.done(); + + // If default proxy config is disabled, try to set another one as default proxy + if (!enabled + && getLc().getDefaultProxyConfig() + .getIdentityAddress() + .equals(prxCfg.getIdentityAddress())) { + int count = getLc().getProxyConfigList().length; + if (count > 1) { + for (int i = 0; i < count; i++) { + if (isAccountEnabled(i)) { + getLc().setDefaultProxyConfig(getProxyConfig(i)); + break; + } + } + } + } + } + + public boolean isAccountEnabled(int n) { + return getProxyConfig(n).registerEnabled(); + } + + public void resetDefaultProxyConfig() { + if (getLc() == null) return; + int count = getLc().getProxyConfigList().length; + for (int i = 0; i < count; i++) { + if (isAccountEnabled(i)) { + getLc().setDefaultProxyConfig(getProxyConfig(i)); + break; + } + } + + if (getLc().getDefaultProxyConfig() == null) { + getLc().setDefaultProxyConfig(getProxyConfig(0)); + } + } + + public void deleteAccount(int n) { + if (getLc() == null) return; + ProxyConfig proxyCfg = getProxyConfig(n); + if (proxyCfg != null) getLc().removeProxyConfig(proxyCfg); + if (getLc().getProxyConfigList().length != 0) { + resetDefaultProxyConfig(); + } else { + getLc().setDefaultProxyConfig(null); + } + + AuthInfo authInfo = getAuthInfo(n); + if (authInfo != null) { + getLc().removeAuthInfo(authInfo); + } + + getLc().refreshRegisters(); + } + // End of accounts settings + + // Audio settings + public void setEchoCancellation(boolean enable) { + if (getLc() == null) return; + getLc().enableEchoCancellation(enable); + } + + public boolean echoCancellationEnabled() { + if (getLc() == null) return false; + return getLc().echoCancellationEnabled(); + } + + public int getEchoCalibration() { + return getConfig().getInt("sound", "ec_delay", -1); + } + + public boolean isEchoConfigurationUpdated() { + return getConfig().getBool("app", "ec_updated", false); + } + + public void echoConfigurationUpdated() { + getConfig().setBool("app", "ec_updated", true); + } + // End of audio settings + + // Video settings + public boolean useFrontCam() { + return getConfig().getBool("app", "front_camera_default", true); + } + + public void setFrontCamAsDefault(boolean frontcam) { + getConfig().setBool("app", "front_camera_default", frontcam); + } + + public boolean isVideoEnabled() { + if (getLc() == null) return false; + return getLc().videoSupported() && getLc().videoEnabled(); + } + + public void enableVideo(boolean enable) { + if (getLc() == null) return; + getLc().enableVideoCapture(enable); + getLc().enableVideoDisplay(enable); + } + + public boolean shouldInitiateVideoCall() { + if (getLc() == null) return false; + return getLc().getVideoActivationPolicy().getAutomaticallyInitiate(); + } + + public void setInitiateVideoCall(boolean initiate) { + if (getLc() == null) return; + VideoActivationPolicy vap = getLc().getVideoActivationPolicy(); + vap.setAutomaticallyInitiate(initiate); + getLc().setVideoActivationPolicy(vap); + } + + public boolean shouldAutomaticallyAcceptVideoRequests() { + if (getLc() == null) return false; + VideoActivationPolicy vap = getLc().getVideoActivationPolicy(); + return vap.getAutomaticallyAccept(); + } + + public void setAutomaticallyAcceptVideoRequests(boolean accept) { + if (getLc() == null) return; + VideoActivationPolicy vap = getLc().getVideoActivationPolicy(); + vap.setAutomaticallyAccept(accept); + getLc().setVideoActivationPolicy(vap); + } + + public String getVideoPreset() { + if (getLc() == null) return null; + String preset = getLc().getVideoPreset(); + if (preset == null) preset = "default"; + return preset; + } + + public void setVideoPreset(String preset) { + if (getLc() == null) return; + if (preset.equals("default")) preset = null; + getLc().setVideoPreset(preset); + preset = getVideoPreset(); + if (!preset.equals("custom")) { + getLc().setPreferredFramerate(0); + } + setPreferredVideoSize(getPreferredVideoSize()); // Apply the bandwidth limit + } + + public String getPreferredVideoSize() { + // Core can only return video size (width and height), not the name + return getConfig().getString("video", "size", "qvga"); + } + + public void setPreferredVideoSize(String preferredVideoSize) { + if (getLc() == null) return; + getLc().setPreferredVideoSizeByName(preferredVideoSize); + } + + public int getPreferredVideoFps() { + if (getLc() == null) return 0; + return (int) getLc().getPreferredFramerate(); + } + + public void setPreferredVideoFps(int fps) { + if (getLc() == null) return; + getLc().setPreferredFramerate(fps); + } + + public int getBandwidthLimit() { + if (getLc() == null) return 0; + return getLc().getDownloadBandwidth(); + } + + public void setBandwidthLimit(int bandwidth) { + if (getLc() == null) return; + getLc().setUploadBandwidth(bandwidth); + getLc().setDownloadBandwidth(bandwidth); + } + // End of video settings + + // Call settings + public boolean useRfc2833Dtmfs() { + if (getLc() == null) return false; + return getLc().getUseRfc2833ForDtmf(); + } + + public void sendDtmfsAsRfc2833(boolean use) { + if (getLc() == null) return; + getLc().setUseRfc2833ForDtmf(use); + } + + public boolean useSipInfoDtmfs() { + if (getLc() == null) return false; + return getLc().getUseInfoForDtmf(); + } + + public void sendDTMFsAsSipInfo(boolean use) { + if (getLc() == null) return; + getLc().setUseInfoForDtmf(use); + } + + public int getIncTimeout() { + if (getLc() == null) return 0; + return getLc().getIncTimeout(); + } + + public void setIncTimeout(int timeout) { + if (getLc() == null) return; + getLc().setIncTimeout(timeout); + } + + public int getInCallTimeout() { + if (getLc() == null) return 0; + return getLc().getInCallTimeout(); + } + + public void setInCallTimeout(int timeout) { + if (getLc() == null) return; + getLc().setInCallTimeout(timeout); + } + + public String getVoiceMailUri() { + return getConfig().getString("app", "voice_mail", null); + } + + public void setVoiceMailUri(String uri) { + getConfig().setString("app", "voice_mail", uri); + } + + public boolean getNativeDialerCall() { + return getConfig().getBool("app", "native_dialer_call", false); + } + + public void setNativeDialerCall(boolean use) { + getConfig().setBool("app", "native_dialer_call", use); + } + // End of call settings + + public boolean isWifiOnlyEnabled() { + return getConfig().getBool("app", "wifi_only", false); + } + + // Network settings + public void setWifiOnlyEnabled(Boolean enable) { + getConfig().setBool("app", "wifi_only", enable); + } + + public void useRandomPort(boolean enabled) { + useRandomPort(enabled, true); + } + + public void useRandomPort(boolean enabled, boolean apply) { + getConfig().setBool("app", "random_port", enabled); + if (apply) { + if (enabled) { + setSipPort(LINPHONE_CORE_RANDOM_PORT); + } else { + setSipPort(5060); + } + } + } + + public boolean isUsingRandomPort() { + return getConfig().getBool("app", "random_port", true); + } + + public String getSipPort() { + if (getLc() == null) return null; + Transports transports = getLc().getTransports(); + int port; + if (transports.getUdpPort() > 0) port = transports.getUdpPort(); + else port = transports.getTcpPort(); + return String.valueOf(port); + } + + public void setSipPort(int port) { + if (getLc() == null) return; + Transports transports = getLc().getTransports(); + transports.setUdpPort(port); + transports.setTcpPort(port); + transports.setTlsPort(LINPHONE_CORE_RANDOM_PORT); + getLc().setTransports(transports); + } + + private NatPolicy getOrCreateNatPolicy() { + if (getLc() == null) return null; + NatPolicy nat = getLc().getNatPolicy(); + if (nat == null) { + nat = getLc().createNatPolicy(); + } + return nat; + } + + public String getStunServer() { + NatPolicy nat = getOrCreateNatPolicy(); + return nat.getStunServer(); + } + + public void setStunServer(String stun) { + if (getLc() == null) return; + NatPolicy nat = getOrCreateNatPolicy(); + nat.setStunServer(stun); + + if (stun != null && !stun.isEmpty()) {} + getLc().setNatPolicy(nat); + } + + public boolean isUpnpEnabled() { + NatPolicy nat = getOrCreateNatPolicy(); + return nat.upnpEnabled(); + } + + public void setUpnpEnabled(boolean enabled) { + if (getLc() == null) return; + NatPolicy nat = getOrCreateNatPolicy(); + nat.enableUpnp(enabled); + getLc().setNatPolicy(nat); + } + + public boolean isIceEnabled() { + NatPolicy nat = getOrCreateNatPolicy(); + return nat.iceEnabled(); + } + + public void setIceEnabled(boolean enabled) { + if (getLc() == null) return; + NatPolicy nat = getOrCreateNatPolicy(); + nat.enableIce(enabled); + nat.enableStun(enabled); + getLc().setNatPolicy(nat); + } + + public boolean isTurnEnabled() { + NatPolicy nat = getOrCreateNatPolicy(); + return nat.turnEnabled(); + } + + public void setTurnEnabled(boolean enabled) { + if (getLc() == null) return; + NatPolicy nat = getOrCreateNatPolicy(); + nat.enableTurn(enabled); + getLc().setNatPolicy(nat); + } + + public String getTurnUsername() { + NatPolicy nat = getOrCreateNatPolicy(); + return nat.getStunServerUsername(); + } + + public void setTurnUsername(String username) { + if (getLc() == null) return; + NatPolicy nat = getOrCreateNatPolicy(); + AuthInfo authInfo = getLc().findAuthInfo(null, nat.getStunServerUsername(), null); + + if (authInfo != null) { + AuthInfo cloneAuthInfo = authInfo.clone(); + getLc().removeAuthInfo(authInfo); + cloneAuthInfo.setUsername(username); + cloneAuthInfo.setUserid(username); + getLc().addAuthInfo(cloneAuthInfo); + } else { + authInfo = + Factory.instance().createAuthInfo(username, username, null, null, null, null); + getLc().addAuthInfo(authInfo); + } + nat.setStunServerUsername(username); + getLc().setNatPolicy(nat); + } + + public void setTurnPassword(String password) { + if (getLc() == null) return; + NatPolicy nat = getOrCreateNatPolicy(); + AuthInfo authInfo = getLc().findAuthInfo(null, nat.getStunServerUsername(), null); + + if (authInfo != null) { + AuthInfo cloneAuthInfo = authInfo.clone(); + getLc().removeAuthInfo(authInfo); + cloneAuthInfo.setPassword(password); + getLc().addAuthInfo(cloneAuthInfo); + } else { + authInfo = + Factory.instance() + .createAuthInfo( + nat.getStunServerUsername(), + nat.getStunServerUsername(), + password, + null, + null, + null); + getLc().addAuthInfo(authInfo); + } + } + + public MediaEncryption getMediaEncryption() { + if (getLc() == null) return null; + return getLc().getMediaEncryption(); + } + + public void setMediaEncryption(MediaEncryption menc) { + if (getLc() == null) return; + if (menc == null) return; + + getLc().setMediaEncryption(menc); + } + + public boolean isPushNotificationEnabled() { + return getConfig().getBool("app", "push_notification", true); + } + + public void setPushNotificationEnabled(boolean enable) { + getConfig().setBool("app", "push_notification", enable); + + Core lc = getLc(); + if (lc == null) { + return; + } + + if (enable) { + // Add push infos to exisiting proxy configs + String regId = getPushNotificationRegistrationID(); + String appId = getString(R.string.push_sender_id); + if (regId != null && lc.getProxyConfigList().length > 0) { + for (ProxyConfig lpc : lc.getProxyConfigList()) { + if (lpc == null) continue; + if (!lpc.isPushNotificationAllowed()) { + lpc.edit(); + lpc.setContactUriParameters(null); + lpc.done(); + if (lpc.getIdentityAddress() != null) + Log.d( + "[Push Notification] infos removed from proxy config " + + lpc.getIdentityAddress().asStringUriOnly()); + } else { + String contactInfos = + "app-id=" + + appId + + ";pn-type=" + + getString(R.string.push_type) + + ";pn-tok=" + + regId + + ";pn-silent=1"; + String prevContactParams = lpc.getContactParameters(); + if (prevContactParams == null + || prevContactParams.compareTo(contactInfos) != 0) { + lpc.edit(); + lpc.setContactUriParameters(contactInfos); + lpc.done(); + if (lpc.getIdentityAddress() != null) + Log.d( + "[Push Notification] infos added to proxy config " + + lpc.getIdentityAddress().asStringUriOnly()); + } + } + } + Log.i( + "[Push Notification] Refreshing registers to ensure token is up to date: " + + regId); + lc.refreshRegisters(); + } + } else { + if (lc.getProxyConfigList().length > 0) { + for (ProxyConfig lpc : lc.getProxyConfigList()) { + lpc.edit(); + lpc.setContactUriParameters(null); + lpc.done(); + if (lpc.getIdentityAddress() != null) + Log.d( + "[Push Notification] infos removed from proxy config " + + lpc.getIdentityAddress().asStringUriOnly()); + } + lc.refreshRegisters(); + } + } + } + + public String getPushNotificationRegistrationID() { + return getConfig().getString("app", "push_notification_regid", null); + } + + public void setPushNotificationRegistrationID(String regId) { + if (getConfig() == null) return; + Log.i("[Push Notification] New token received: " + regId); + getConfig().setString("app", "push_notification_regid", (regId != null) ? regId : ""); + setPushNotificationEnabled(isPushNotificationEnabled()); + } + + public void useIpv6(Boolean enable) { + if (getLc() == null) return; + getLc().enableIpv6(enable); + } + + public boolean isUsingIpv6() { + if (getLc() == null) return false; + return getLc().ipv6Enabled(); + } + // End of network settings + + public boolean isDebugEnabled() { + return getConfig().getBool("app", "debug", false); + } + + // Advanced settings + public void setDebugEnabled(boolean enabled) { + getConfig().setBool("app", "debug", enabled); + LinphoneUtils.initLoggingService(enabled, mContext.getString(R.string.app_name)); + } + + public void setJavaLogger(boolean enabled) { + getConfig().setBool("app", "java_logger", enabled); + LinphoneUtils.initLoggingService(isDebugEnabled(), mContext.getString(R.string.app_name)); + } + + public boolean useJavaLogger() { + return getConfig().getBool("app", "java_logger", false); + } + + public boolean isBackgroundModeEnabled() { + return getConfig().getBool("app", "background_mode", true); + } + + public void setBackgroundModeEnabled(boolean enabled) { + getConfig().setBool("app", "background_mode", enabled); + } + + public boolean isAutoStartEnabled() { + return getConfig().getBool("app", "auto_start", false); + } + + public void setAutoStart(boolean autoStartEnabled) { + getConfig().setBool("app", "auto_start", autoStartEnabled); + } + + public String getSharingPictureServerUrl() { + if (getLc() == null) return null; + return getLc().getFileTransferServer(); + } + + public void setSharingPictureServerUrl(String url) { + if (getLc() == null) return; + getLc().setFileTransferServer(url); + } + + public String getRemoteProvisioningUrl() { + if (getLc() == null) return null; + return getLc().getProvisioningUri(); + } + + public void setRemoteProvisioningUrl(String url) { + if (getLc() == null) return; + if (url != null && url.length() == 0) { + url = null; + } + getLc().setProvisioningUri(url); + } + + public String getDefaultDisplayName() { + if (getLc() == null) return null; + return getLc().getPrimaryContactParsed().getDisplayName(); + } + + public void setDefaultDisplayName(String displayName) { + if (getLc() == null) return; + Address primary = getLc().getPrimaryContactParsed(); + primary.setDisplayName(displayName); + getLc().setPrimaryContact(primary.asString()); + } + + public String getDefaultUsername() { + if (getLc() == null) return null; + return getLc().getPrimaryContactParsed().getUsername(); + } + + public void setDefaultUsername(String username) { + if (getLc() == null) return; + Address primary = getLc().getPrimaryContactParsed(); + primary.setUsername(username); + getLc().setPrimaryContact(primary.asString()); + } + // End of advanced settings + + public TunnelConfig getTunnelConfig() { + if (getLc() == null) return null; + if (getLc().tunnelAvailable()) { + Tunnel tunnel = getLc().getTunnel(); + if (tunnelConfig == null) { + TunnelConfig servers[] = tunnel.getServers(); + if (servers.length > 0) { + tunnelConfig = servers[0]; + } else { + tunnelConfig = Factory.instance().createTunnelConfig(); + } + } + return tunnelConfig; + } else { + return null; + } + } + + public String getTunnelHost() { + TunnelConfig config = getTunnelConfig(); + if (config != null) { + return config.getHost(); + } else { + return null; + } + } + + public void setTunnelHost(String host) { + TunnelConfig config = getTunnelConfig(); + if (config != null) { + config.setHost(host); + LinphoneManager.getInstance().initTunnelFromConf(); + } + } + + public int getTunnelPort() { + TunnelConfig config = getTunnelConfig(); + if (config != null) { + return config.getPort(); + } else { + return -1; + } + } + + public void setTunnelPort(int port) { + TunnelConfig config = getTunnelConfig(); + if (config != null) { + config.setPort(port); + LinphoneManager.getInstance().initTunnelFromConf(); + } + } + + public String getTunnelMode() { + return getConfig().getString("app", "tunnel", null); + } + + public void setTunnelMode(String mode) { + getConfig().setString("app", "tunnel", mode); + LinphoneManager.getInstance().initTunnelFromConf(); + } + + public boolean isProvisioningLoginViewEnabled() { + + return (getConfig() != null) ? getConfig().getBool("app", "show_login_view", false) : false; + } + // End of tunnel settings + + public void disableProvisioningLoginView() { + if (isProvisioningLoginViewEnabled()) { // Only do it if it was previously enabled + getConfig().setBool("app", "show_login_view", false); + } else { + Log.w("Remote provisioning login view wasn't enabled, ignoring"); + } + } + + public void firstRemoteProvisioningSuccessful() { + getConfig().setBool("app", "first_remote_provisioning", false); + } + + public boolean isFirstRemoteProvisioning() { + return getConfig().getBool("app", "first_remote_provisioning", true); + } + + public boolean adaptiveRateControlEnabled() { + if (getLc() == null) return false; + return getLc().adaptiveRateControlEnabled(); + } + + public void enableAdaptiveRateControl(boolean enabled) { + if (getLc() == null) return; + getLc().enableAdaptiveRateControl(enabled); + } + + public int getCodecBitrateLimit() { + return getConfig().getInt("audio", "codec_bitrate_limit", 36); + } + + public void setCodecBitrateLimit(int bitrate) { + getConfig().setInt("audio", "codec_bitrate_limit", bitrate); + } + + public void contactsMigrationDone() { + getConfig().setBool("app", "contacts_migration_done", true); + } + + public boolean isContactsMigrationDone() { + return getConfig().getBool("app", "contacts_migration_done", false); + } + + public String getInAppPurchaseValidatingServerUrl() { + return getConfig().getString("in-app-purchase", "server_url", null); + } + + public Purchasable getInAppPurchasedItem() { + String id = getConfig().getString("in-app-purchase", "purchase_item_id", null); + String payload = getConfig().getString("in-app-purchase", "purchase_item_payload", null); + String signature = + getConfig().getString("in-app-purchase", "purchase_item_signature", null); + String username = getConfig().getString("in-app-purchase", "purchase_item_username", null); + + Purchasable item = + new Purchasable(id) + .setPayloadAndSignature(payload, signature) + .setUserData(username); + return item; + } + + public void setInAppPurchasedItem(Purchasable item) { + if (item == null) return; + + getConfig().setString("in-app-purchase", "purchase_item_id", item.getId()); + getConfig().setString("in-app-purchase", "purchase_item_payload", item.getPayload()); + getConfig() + .setString( + "in-app-purchase", "purchase_item_signature", item.getPayloadSignature()); + getConfig().setString("in-app-purchase", "purchase_item_username", item.getUserData()); + } + + public ArrayList getInAppPurchasables() { + ArrayList purchasables = new ArrayList(); + String list = getConfig().getString("in-app-purchase", "purchasable_items_ids", null); + if (list != null) { + for (String purchasable : list.split(";")) { + if (purchasable.length() > 0) { + purchasables.add(purchasable); + } + } + } + return purchasables; + } + + public String getXmlrpcUrl() { + return getConfig().getString("assistant", "xmlrpc_url", null); + } + + public void setXmlrpcUrl(String url) { + getConfig().setString("assistant", "xmlrpc_url", url); + } + + public String getInappPopupTime() { + return getConfig().getString("app", "inapp_popup_time", null); + } + + public void setInappPopupTime(String date) { + getConfig().setString("app", "inapp_popup_time", date); + } + + public String getLinkPopupTime() { + return getConfig().getString("app", "link_popup_time", null); + } + + public void setLinkPopupTime(String date) { + getConfig().setString("app", "link_popup_time", date); + } + + public boolean isLinkPopupEnabled() { + return getConfig().getBool("app", "link_popup_enabled", true); + } + + public void enableLinkPopup(boolean enable) { + getConfig().setBool("app", "link_popup_enabled", enable); + } + + public boolean isLimeSecurityPopupEnabled() { + return getConfig().getBool("app", "lime_security_popup_enabled", true); + } + + public void enableLimeSecurityPopup(boolean enable) { + getConfig().setBool("app", "lime_security_popup_enabled", enable); + } + + public String getDebugPopupAddress() { + return getConfig().getString("app", "debug_popup_magic", null); + } + + public String getActivityToLaunchOnIncomingReceived() { + return getConfig() + .getString("app", "incoming_call_activity", "org.linphone.LinphoneActivity"); + } + + public void setActivityToLaunchOnIncomingReceived(String name) { + getConfig().setString("app", "incoming_call_activity", name); + } + + public boolean getServiceNotificationVisibility() { + return getConfig().getBool("app", "show_service_notification", false); + } + + public void setServiceNotificationVisibility(boolean enable) { + getConfig().setBool("app", "show_service_notification", enable); + } + + public boolean isOverlayEnabled() { + return getConfig().getBool("app", "display_overlay", false); + } + + public void enableOverlay(boolean enable) { + getConfig().setBool("app", "display_overlay", enable); + } + + public LimeState limeEnabled() { + if (getLc() == null) return LimeState.Disabled; + return getLc().limeEnabled(); + } + + public void enableLime(LimeState lime) { + if (getLc() == null) return; + getLc().enableLime(lime); + } + + public boolean firstTimeAskingForPermission(String permission) { + return firstTimeAskingForPermission(permission, true); + } + + public boolean firstTimeAskingForPermission(String permission, boolean toggle) { + boolean firstTime = getConfig().getBool("app", permission, true); + if (toggle) { + permissionHasBeenAsked(permission); + } + return firstTime; + } + + public void permissionHasBeenAsked(String permission) { + getConfig().setBool("app", permission, false); + } + + public boolean isDeviceRingtoneEnabled() { + int readExternalStorage = + mContext.getPackageManager() + .checkPermission( + Manifest.permission.READ_EXTERNAL_STORAGE, + mContext.getPackageName()); + return getConfig().getBool("app", "device_ringtone", true) + && readExternalStorage == PackageManager.PERMISSION_GRANTED; + } + + public void enableDeviceRingtone(boolean enable) { + getConfig().setBool("app", "device_ringtone", enable); + } + + public boolean isIncomingCallVibrationEnabled() { + return getConfig().getBool("app", "incoming_call_vibration", true); + } + + public void enableIncomingCallVibration(boolean enable) { + getConfig().setBool("app", "incoming_call_vibration", enable); + } + + public boolean isBisFeatureEnabled() { + return getConfig().getBool("app", "bis_feature", true); + } + + public void enableBisFeature(boolean enable) { + getConfig().setBool("app", "bis_feature", enable); + } + + public boolean isAutoAnswerEnabled() { + return getConfig().getBool("app", "auto_answer", false); + } + + public void enableAutoAnswer(boolean enable) { + getConfig().setBool("app", "auto_answer", enable); + } + + public int getAutoAnswerTime() { + return getConfig().getInt("app", "auto_answer_delay", 0); + } + + public void setAutoAnswerTime(int time) { + getConfig().setInt("app", "auto_answer_delay", time); + } + + public int getCodeLength() { + return getConfig().getInt("app", "activation_code_length", 0); + } + + public void disableFriendsStorage() { + getConfig().setBool("misc", "store_friends", false); + } + + public void enableFriendsStorage() { + getConfig().setBool("misc", "store_friends", true); + } + + public boolean isFriendsStorageEnabled() { + return getConfig().getBool("misc", "store_friends", true); + } + + public boolean useBasicChatRoomFor1To1() { + return getConfig().getBool("app", "prefer_basic_chat_room", false); + } + + // 0 is download all, -1 is disable feature, else size is bytes + public int getAutoDownloadFileMaxSize() { + return getLc().getMaxSizeForAutoDownloadIncomingFiles(); + } + + // 0 is download all, -1 is disable feature, else size is bytes + public void setAutoDownloadFileMaxSize(int size) { + getLc().setMaxSizeForAutoDownloadIncomingFiles(size); + } + public static class AccountBuilder { private Core lc; private String tempUsername; @@ -215,7 +1510,6 @@ public class LinphonePreferences { private boolean tempEnabled = true; private boolean tempNoDefault = false; - public AccountBuilder(Core lc) { this.lc = lc; } @@ -327,7 +1621,10 @@ public class LinphonePreferences { */ public void saveNewAccount() throws CoreException { - if (tempUsername == null || tempUsername.length() < 1 || tempDomain == null || tempDomain.length() < 1) { + if (tempUsername == null + || tempUsername.length() < 1 + || tempDomain == null + || tempDomain.length() < 1) { Log.w("Skipping account save: username or domain not provided"); return; } @@ -337,8 +1634,10 @@ public class LinphonePreferences { if (tempProxy == null) { proxy += tempDomain; } else { - if (!tempProxy.startsWith("sip:") && !tempProxy.startsWith(" n && LinphoneManager.getLc().getAuthInfoList()[n] != null) { - userid = getAccountUserId(n); - realm = getAccountRealm(n); - LinphoneManager.getLc().removeAuthInfo(LinphoneManager.getLc().getAuthInfoList()[n]); - } - AuthInfo authInfo = Factory.instance().createAuthInfo( - user, userid, password, ha1, realm, domain); - LinphoneManager.getLc().addAuthInfo(authInfo); - } - } - - public String getAccountPassword(int n) { - AuthInfo authInfo = getAuthInfo(n); - return authInfo == null ? null : authInfo.getPassword(); - } - - public String getAccountHa1(int n) { - AuthInfo authInfo = getAuthInfo(n); - return authInfo == null ? null : authInfo.getHa1(); - } - - public void setAccountIce(int n, boolean ice) { - try { - ProxyConfig prxCfg = getProxyConfig(n); - prxCfg.edit(); - prxCfg.getNatPolicy().enableIce(ice); - prxCfg.getNatPolicy().enableStun(ice); - prxCfg.done(); - } catch (Exception e) { - Log.e(e); - } - } - - public boolean getAccountIce(int n) { - if (getProxyConfig(n) == null || getProxyConfig(n).getNatPolicy() == null) return false; - return getProxyConfig(n).getNatPolicy().iceEnabled(); - } - - public void setAccountStunServer(int n, String stun) { - try { - ProxyConfig prxCfg = getProxyConfig(n); - prxCfg.edit(); - NatPolicy np = prxCfg.getNatPolicy(); - np.setStunServer(stun); - prxCfg.done(); - } catch (Exception e) { - Log.e(e); - } - } - - public String getAccountStunServer(int n) { - if (getProxyConfig(n) == null || getProxyConfig(n).getNatPolicy() == null) return ""; - return getProxyConfig(n).getNatPolicy().getStunServer(); - } - - public void setAccountDomain(int n, String domain) { - String identity = "sip:" + getAccountUsername(n) + "@" + domain; - AuthInfo old_info = getAuthInfo(n); - ProxyConfig prxCfg = getProxyConfig(n); - prxCfg.edit(); - prxCfg.setIdentityAddress(Factory.instance().createAddress(identity)); - prxCfg.enableRegister(true); - prxCfg.done(); - - if (old_info != null) { - // We have to remove the previous auth info after otherwise we can't unregister the previous proxy config - AuthInfo new_info = old_info.clone(); - getLc().removeAuthInfo(old_info); - new_info.setDomain(domain); - saveAuthInfo(new_info); - } - } - - public String getAccountDomain(int n) { - ProxyConfig proxyConf = getProxyConfig(n); - return (proxyConf != null) ? proxyConf.getDomain() : ""; - } - - public void setAccountProxy(int n, String proxy) { - if (proxy == null || proxy.length() <= 0) { - proxy = getAccountDomain(n); - } - - if (!proxy.contains("sip:")) { - proxy = "sip:" + proxy; - } - - Address proxyAddr = Factory.instance().createAddress(proxy); - if (proxyAddr == null) return; - - if (!proxy.contains("transport=")) { - proxyAddr.setTransport(getAccountTransport(n)); - } - - ProxyConfig prxCfg = getProxyConfig(n); - prxCfg.edit(); - prxCfg.setServerAddr(proxyAddr.asStringUriOnly()); - prxCfg.done(); - - if (isAccountOutboundProxySet(n)) { - setAccountOutboundProxyEnabled(n, true); - } - } - - public String getAccountProxy(int n) { - String proxy = getProxyConfig(n).getServerAddr(); - return proxy; - } - - - public void setAccountOutboundProxyEnabled(int n, boolean enabled) { - ProxyConfig prxCfg = getProxyConfig(n); - prxCfg.edit(); - if (enabled) { - String route = prxCfg.getServerAddr(); - prxCfg.setRoute(route); - } else { - prxCfg.setRoute(null); - } - prxCfg.done(); - } - - public boolean isAccountOutboundProxySet(int n) { - return getProxyConfig(n).getRoute() != null; - } - - public void setAccountContactParameters(int n, String contactParams) { - ProxyConfig prxCfg = getProxyConfig(n); - prxCfg.edit(); - prxCfg.setContactUriParameters(contactParams); - prxCfg.done(); - } - - public String getExpires(int n) { - return String.valueOf(getProxyConfig(n).getExpires()); - } - - public void setExpires(int n, String expire) { - try { - ProxyConfig prxCfg = getProxyConfig(n); - prxCfg.edit(); - prxCfg.setExpires(Integer.parseInt(expire)); - prxCfg.done(); - } catch (NumberFormatException nfe) { - } - } - - public String getPrefix(int n) { - return getProxyConfig(n).getDialPrefix(); - } - - public void setPrefix(int n, String prefix) { - ProxyConfig prxCfg = getProxyConfig(n); - prxCfg.edit(); - prxCfg.setDialPrefix(prefix); - prxCfg.done(); - } - - public boolean avpfEnabled(int n) { - return getProxyConfig(n).avpfEnabled(); - } - - public void setAvpfMode(int n, boolean enable) { - ProxyConfig prxCfg = getProxyConfig(n); - prxCfg.edit(); - prxCfg.setAvpfMode(enable ? AVPFMode.Enabled : AVPFMode.Disabled); - prxCfg.done(); - } - - public String getAvpfRrInterval(int n) { - return String.valueOf(getProxyConfig(n).getAvpfRrInterval()); - } - - public void setAvpfRrInterval(int n, String interval) { - try { - ProxyConfig prxCfg = getProxyConfig(n); - prxCfg.edit(); - prxCfg.setAvpfRrInterval(Integer.parseInt(interval)); - prxCfg.done(); - } catch (NumberFormatException nfe) { - } - } - - public boolean getReplacePlusByZeroZero(int n) { - return getProxyConfig(n).getDialEscapePlus(); - } - - public void setReplacePlusByZeroZero(int n, boolean replace) { - ProxyConfig prxCfg = getProxyConfig(n); - prxCfg.edit(); - prxCfg.setDialEscapePlus(replace); - prxCfg.done(); - } - - public void enablePushNotifForProxy(int n, boolean enable) { - ProxyConfig prxCfg = getProxyConfig(n); - prxCfg.edit(); - prxCfg.setPushNotificationAllowed(enable); - prxCfg.done(); - - setPushNotificationEnabled(isPushNotificationEnabled()); - } - - public boolean isPushNotifEnabledForProxy(int n) { - ProxyConfig prxCfg = getProxyConfig(n); - return prxCfg.isPushNotificationAllowed(); - } - - public boolean isFriendlistsubscriptionEnabled() { - return getConfig().getBool("app", "friendlist_subscription_enabled", false); - } - - public void enabledFriendlistSubscription(boolean enabled) { - getConfig().setBool("app", "friendlist_subscription_enabled", enabled); - - } - - public void setDefaultAccount(int accountIndex) { - if (getLc() == null) return; - ProxyConfig[] prxCfgs = getLc().getProxyConfigList(); - if (accountIndex >= 0 && accountIndex < prxCfgs.length) - getLc().setDefaultProxyConfig(prxCfgs[accountIndex]); - } - - public int getDefaultAccountIndex() { - if (getLc() == null) - return -1; - ProxyConfig defaultPrxCfg = getLc().getDefaultProxyConfig(); - if (defaultPrxCfg == null) - return -1; - - ProxyConfig[] prxCfgs = getLc().getProxyConfigList(); - for (int i = 0; i < prxCfgs.length; i++) { - if (defaultPrxCfg.getIdentityAddress().equals(prxCfgs[i].getIdentityAddress())) { - return i; - } - } - return -1; - } - - public int getAccountCount() { - if (getLc() == null || getLc().getProxyConfigList() == null) - return 0; - - return getLc().getProxyConfigList().length; - } - - public void setAccountEnabled(int n, boolean enabled) { - if (getLc() == null) return; - ProxyConfig prxCfg = getProxyConfig(n); - if (prxCfg == null) { - LinphoneUtils.displayErrorAlert(getString(R.string.error), mContext); - return; - } - prxCfg.edit(); - prxCfg.enableRegister(enabled); - prxCfg.done(); - - // If default proxy config is disabled, try to set another one as default proxy - if (!enabled && getLc().getDefaultProxyConfig().getIdentityAddress().equals(prxCfg.getIdentityAddress())) { - int count = getLc().getProxyConfigList().length; - if (count > 1) { - for (int i = 0; i < count; i++) { - if (isAccountEnabled(i)) { - getLc().setDefaultProxyConfig(getProxyConfig(i)); - break; - } - } - } - } - } - - public boolean isAccountEnabled(int n) { - return getProxyConfig(n).registerEnabled(); - } - - public void resetDefaultProxyConfig() { - if (getLc() == null) return; - int count = getLc().getProxyConfigList().length; - for (int i = 0; i < count; i++) { - if (isAccountEnabled(i)) { - getLc().setDefaultProxyConfig(getProxyConfig(i)); - break; - } - } - - if (getLc().getDefaultProxyConfig() == null) { - getLc().setDefaultProxyConfig(getProxyConfig(0)); - } - } - - public void deleteAccount(int n) { - if (getLc() == null) return; - ProxyConfig proxyCfg = getProxyConfig(n); - if (proxyCfg != null) - getLc().removeProxyConfig(proxyCfg); - if (getLc().getProxyConfigList().length != 0) { - resetDefaultProxyConfig(); - } else { - getLc().setDefaultProxyConfig(null); - } - - AuthInfo authInfo = getAuthInfo(n); - if (authInfo != null) { - getLc().removeAuthInfo(authInfo); - } - - getLc().refreshRegisters(); - } - // End of accounts settings - - // Audio settings - public void setEchoCancellation(boolean enable) { - if (getLc() == null) return; - getLc().enableEchoCancellation(enable); - } - - public boolean echoCancellationEnabled() { - if (getLc() == null) return false; - return getLc().echoCancellationEnabled(); - } - - public int getEchoCalibration() { - return getConfig().getInt("sound", "ec_delay", -1); - } - - public boolean isEchoConfigurationUpdated() { - return getConfig().getBool("app", "ec_updated", false); - } - - public void echoConfigurationUpdated() { - getConfig().setBool("app", "ec_updated", true); - } - // End of audio settings - - // Video settings - public boolean useFrontCam() { - return getConfig().getBool("app", "front_camera_default", true); - } - - public void setFrontCamAsDefault(boolean frontcam) { - getConfig().setBool("app", "front_camera_default", frontcam); - } - - public boolean isVideoEnabled() { - if (getLc() == null) return false; - return getLc().videoSupported() && getLc().videoEnabled(); - } - - public void enableVideo(boolean enable) { - if (getLc() == null) return; - getLc().enableVideoCapture(enable); - getLc().enableVideoDisplay(enable); - } - - public boolean shouldInitiateVideoCall() { - if (getLc() == null) return false; - return getLc().getVideoActivationPolicy().getAutomaticallyInitiate(); - } - - public void setInitiateVideoCall(boolean initiate) { - if (getLc() == null) return; - VideoActivationPolicy vap = getLc().getVideoActivationPolicy(); - vap.setAutomaticallyInitiate(initiate); - getLc().setVideoActivationPolicy(vap); - } - - public boolean shouldAutomaticallyAcceptVideoRequests() { - if (getLc() == null) return false; - VideoActivationPolicy vap = getLc().getVideoActivationPolicy(); - return vap.getAutomaticallyAccept(); - } - - public void setAutomaticallyAcceptVideoRequests(boolean accept) { - if (getLc() == null) return; - VideoActivationPolicy vap = getLc().getVideoActivationPolicy(); - vap.setAutomaticallyAccept(accept); - getLc().setVideoActivationPolicy(vap); - } - - public String getVideoPreset() { - if (getLc() == null) return null; - String preset = getLc().getVideoPreset(); - if (preset == null) preset = "default"; - return preset; - } - - public void setVideoPreset(String preset) { - if (getLc() == null) return; - if (preset.equals("default")) preset = null; - getLc().setVideoPreset(preset); - preset = getVideoPreset(); - if (!preset.equals("custom")) { - getLc().setPreferredFramerate(0); - } - setPreferredVideoSize(getPreferredVideoSize()); // Apply the bandwidth limit - } - - public String getPreferredVideoSize() { - //Core can only return video size (width and height), not the name - return getConfig().getString("video", "size", "qvga"); - } - - public void setPreferredVideoSize(String preferredVideoSize) { - if (getLc() == null) return; - getLc().setPreferredVideoSizeByName(preferredVideoSize); - } - - public int getPreferredVideoFps() { - if (getLc() == null) return 0; - return (int) getLc().getPreferredFramerate(); - } - - public void setPreferredVideoFps(int fps) { - if (getLc() == null) return; - getLc().setPreferredFramerate(fps); - } - - public int getBandwidthLimit() { - if (getLc() == null) return 0; - return getLc().getDownloadBandwidth(); - } - - public void setBandwidthLimit(int bandwidth) { - if (getLc() == null) return; - getLc().setUploadBandwidth(bandwidth); - getLc().setDownloadBandwidth(bandwidth); - } - // End of video settings - - // Call settings - public boolean useRfc2833Dtmfs() { - if (getLc() == null) return false; - return getLc().getUseRfc2833ForDtmf(); - } - - public void sendDtmfsAsRfc2833(boolean use) { - if (getLc() == null) return; - getLc().setUseRfc2833ForDtmf(use); - } - - public boolean useSipInfoDtmfs() { - if (getLc() == null) return false; - return getLc().getUseInfoForDtmf(); - } - - public void sendDTMFsAsSipInfo(boolean use) { - if (getLc() == null) return; - getLc().setUseInfoForDtmf(use); - } - - public int getIncTimeout() { - if (getLc() == null) return 0; - return getLc().getIncTimeout(); - } - - public void setIncTimeout(int timeout) { - if (getLc() == null) return; - getLc().setIncTimeout(timeout); - } - - public int getInCallTimeout() { - if (getLc() == null) return 0; - return getLc().getInCallTimeout(); - } - - public void setInCallTimeout(int timeout) { - if (getLc() == null) return; - getLc().setInCallTimeout(timeout); - } - - public String getVoiceMailUri() { - return getConfig().getString("app", "voice_mail", null); - } - - public void setVoiceMailUri(String uri) { - getConfig().setString("app", "voice_mail", uri); - } - - public boolean getNativeDialerCall() { - return getConfig().getBool("app", "native_dialer_call", false); - } - - public void setNativeDialerCall(boolean use) { - getConfig().setBool("app", "native_dialer_call", use); - } -// End of call settings - - // Network settings - public void setWifiOnlyEnabled(Boolean enable) { - getConfig().setBool("app", "wifi_only", enable); - } - - public boolean isWifiOnlyEnabled() { - return getConfig().getBool("app", "wifi_only", false); - } - - public void useRandomPort(boolean enabled) { - useRandomPort(enabled, true); - } - - public void useRandomPort(boolean enabled, boolean apply) { - getConfig().setBool("app", "random_port", enabled); - if (apply) { - if (enabled) { - setSipPort(LINPHONE_CORE_RANDOM_PORT); - } else { - setSipPort(5060); - } - } - } - - public boolean isUsingRandomPort() { - return getConfig().getBool("app", "random_port", true); - } - - public String getSipPort() { - if (getLc() == null) return null; - Transports transports = getLc().getTransports(); - int port; - if (transports.getUdpPort() > 0) - port = transports.getUdpPort(); - else - port = transports.getTcpPort(); - return String.valueOf(port); - } - - public void setSipPort(int port) { - if (getLc() == null) return; - Transports transports = getLc().getTransports(); - transports.setUdpPort(port); - transports.setTcpPort(port); - transports.setTlsPort(LINPHONE_CORE_RANDOM_PORT); - getLc().setTransports(transports); - } - - private NatPolicy getOrCreateNatPolicy() { - if (getLc() == null) return null; - NatPolicy nat = getLc().getNatPolicy(); - if (nat == null) { - nat = getLc().createNatPolicy(); - } - return nat; - } - - public String getStunServer() { - NatPolicy nat = getOrCreateNatPolicy(); - return nat.getStunServer(); - } - - public void setStunServer(String stun) { - if (getLc() == null) return; - NatPolicy nat = getOrCreateNatPolicy(); - nat.setStunServer(stun); - - if (stun != null && !stun.isEmpty()) { - } - getLc().setNatPolicy(nat); - } - - public void setIceEnabled(boolean enabled) { - if (getLc() == null) return; - NatPolicy nat = getOrCreateNatPolicy(); - nat.enableIce(enabled); - nat.enableStun(enabled); - getLc().setNatPolicy(nat); - } - - public void setTurnEnabled(boolean enabled) { - if (getLc() == null) return; - NatPolicy nat = getOrCreateNatPolicy(); - nat.enableTurn(enabled); - getLc().setNatPolicy(nat); - } - - public void setUpnpEnabled(boolean enabled) { - if (getLc() == null) return; - NatPolicy nat = getOrCreateNatPolicy(); - nat.enableUpnp(enabled); - getLc().setNatPolicy(nat); - } - - public boolean isUpnpEnabled() { - NatPolicy nat = getOrCreateNatPolicy(); - return nat.upnpEnabled(); - } - - public boolean isIceEnabled() { - NatPolicy nat = getOrCreateNatPolicy(); - return nat.iceEnabled(); - } - - public boolean isTurnEnabled() { - NatPolicy nat = getOrCreateNatPolicy(); - return nat.turnEnabled(); - } - - public String getTurnUsername() { - NatPolicy nat = getOrCreateNatPolicy(); - return nat.getStunServerUsername(); - } - - public void setTurnUsername(String username) { - if (getLc() == null) return; - NatPolicy nat = getOrCreateNatPolicy(); - AuthInfo authInfo = getLc().findAuthInfo(null, nat.getStunServerUsername(), null); - - if (authInfo != null) { - AuthInfo cloneAuthInfo = authInfo.clone(); - getLc().removeAuthInfo(authInfo); - cloneAuthInfo.setUsername(username); - cloneAuthInfo.setUserid(username); - getLc().addAuthInfo(cloneAuthInfo); - } else { - authInfo = Factory.instance().createAuthInfo(username, username, null, null, null, null); - getLc().addAuthInfo(authInfo); - } - nat.setStunServerUsername(username); - getLc().setNatPolicy(nat); - } - - public void setTurnPassword(String password) { - if (getLc() == null) return; - NatPolicy nat = getOrCreateNatPolicy(); - AuthInfo authInfo = getLc().findAuthInfo(null, nat.getStunServerUsername(), null); - - if (authInfo != null) { - AuthInfo cloneAuthInfo = authInfo.clone(); - getLc().removeAuthInfo(authInfo); - cloneAuthInfo.setPassword(password); - getLc().addAuthInfo(cloneAuthInfo); - } else { - authInfo = Factory.instance().createAuthInfo(nat.getStunServerUsername(), nat.getStunServerUsername(), password, null, null, null); - getLc().addAuthInfo(authInfo); - } - } - - public MediaEncryption getMediaEncryption() { - if (getLc() == null) return null; - return getLc().getMediaEncryption(); - } - - public void setMediaEncryption(MediaEncryption menc) { - if (getLc() == null) return; - if (menc == null) - return; - - getLc().setMediaEncryption(menc); - } - - public void setPushNotificationEnabled(boolean enable) { - getConfig().setBool("app", "push_notification", enable); - - Core lc = getLc(); - if (lc == null) { - return; - } - - if (enable) { - // Add push infos to exisiting proxy configs - String regId = getPushNotificationRegistrationID(); - String appId = getString(R.string.push_sender_id); - if (regId != null && lc.getProxyConfigList().length > 0) { - for (ProxyConfig lpc : lc.getProxyConfigList()) { - if (lpc == null) continue; - if (!lpc.isPushNotificationAllowed()) { - lpc.edit(); - lpc.setContactUriParameters(null); - lpc.done(); - if (lpc.getIdentityAddress() != null) - Log.d("[Push Notification] infos removed from proxy config " + lpc.getIdentityAddress().asStringUriOnly()); - } else { - String contactInfos = "app-id=" + appId + ";pn-type=" + getString(R.string.push_type) + ";pn-tok=" + regId + ";pn-silent=1"; - String prevContactParams = lpc.getContactParameters(); - if (prevContactParams == null || prevContactParams.compareTo(contactInfos) != 0) { - lpc.edit(); - lpc.setContactUriParameters(contactInfos); - lpc.done(); - if (lpc.getIdentityAddress() != null) - Log.d("[Push Notification] infos added to proxy config " + lpc.getIdentityAddress().asStringUriOnly()); - } - } - } - Log.i("[Push Notification] Refreshing registers to ensure token is up to date: " + regId); - lc.refreshRegisters(); - } - } else { - if (lc.getProxyConfigList().length > 0) { - for (ProxyConfig lpc : lc.getProxyConfigList()) { - lpc.edit(); - lpc.setContactUriParameters(null); - lpc.done(); - if (lpc.getIdentityAddress() != null) - Log.d("[Push Notification] infos removed from proxy config " + lpc.getIdentityAddress().asStringUriOnly()); - } - lc.refreshRegisters(); - } - } - } - - public boolean isPushNotificationEnabled() { - return getConfig().getBool("app", "push_notification", true); - } - - public void setPushNotificationRegistrationID(String regId) { - if (getConfig() == null) return; - Log.i("[Push Notification] New token received: " + regId); - getConfig().setString("app", "push_notification_regid", (regId != null) ? regId : ""); - setPushNotificationEnabled(isPushNotificationEnabled()); - } - - public String getPushNotificationRegistrationID() { - return getConfig().getString("app", "push_notification_regid", null); - } - - public void useIpv6(Boolean enable) { - if (getLc() == null) return; - getLc().enableIpv6(enable); - } - - public boolean isUsingIpv6() { - if (getLc() == null) return false; - return getLc().ipv6Enabled(); - } - // End of network settings - - // Advanced settings - public void setDebugEnabled(boolean enabled) { - getConfig().setBool("app", "debug", enabled); - LinphoneUtils.initLoggingService(enabled, mContext.getString(R.string.app_name)); - } - - public boolean isDebugEnabled() { - return getConfig().getBool("app", "debug", false); - } - - public void setJavaLogger(boolean enabled) { - getConfig().setBool("app", "java_logger", enabled); - LinphoneUtils.initLoggingService(isDebugEnabled(), mContext.getString(R.string.app_name)); - } - - public boolean useJavaLogger() { - return getConfig().getBool("app", "java_logger", false); - } - - public void setBackgroundModeEnabled(boolean enabled) { - getConfig().setBool("app", "background_mode", enabled); - } - - public boolean isBackgroundModeEnabled() { - return getConfig().getBool("app", "background_mode", true); - } - - public boolean isAutoStartEnabled() { - return getConfig().getBool("app", "auto_start", false); - } - - public void setAutoStart(boolean autoStartEnabled) { - getConfig().setBool("app", "auto_start", autoStartEnabled); - } - - public String getSharingPictureServerUrl() { - if (getLc() == null) return null; - return getLc().getFileTransferServer(); - } - - public void setSharingPictureServerUrl(String url) { - if (getLc() == null) return; - getLc().setFileTransferServer(url); - } - - public void setRemoteProvisioningUrl(String url) { - if (getLc() == null) return; - if (url != null && url.length() == 0) { - url = null; - } - getLc().setProvisioningUri(url); - } - - public String getRemoteProvisioningUrl() { - if (getLc() == null) return null; - return getLc().getProvisioningUri(); - } - - public void setDefaultDisplayName(String displayName) { - if (getLc() == null) return; - Address primary = getLc().getPrimaryContactParsed(); - primary.setDisplayName(displayName); - getLc().setPrimaryContact(primary.asString()); - } - - public String getDefaultDisplayName() { - if (getLc() == null) return null; - return getLc().getPrimaryContactParsed().getDisplayName(); - } - - public void setDefaultUsername(String username) { - if (getLc() == null) return; - Address primary = getLc().getPrimaryContactParsed(); - primary.setUsername(username); - getLc().setPrimaryContact(primary.asString()); - } - - public String getDefaultUsername() { - if (getLc() == null) return null; - return getLc().getPrimaryContactParsed().getUsername(); - } - // End of advanced settings - - // Tunnel settings - private TunnelConfig tunnelConfig = null; - - public TunnelConfig getTunnelConfig() { - if (getLc() == null) return null; - if (getLc().tunnelAvailable()) { - Tunnel tunnel = getLc().getTunnel(); - if (tunnelConfig == null) { - TunnelConfig servers[] = tunnel.getServers(); - if (servers.length > 0) { - tunnelConfig = servers[0]; - } else { - tunnelConfig = Factory.instance().createTunnelConfig(); - } - } - return tunnelConfig; - } else { - return null; - } - } - - public String getTunnelHost() { - TunnelConfig config = getTunnelConfig(); - if (config != null) { - return config.getHost(); - } else { - return null; - } - } - - public void setTunnelHost(String host) { - TunnelConfig config = getTunnelConfig(); - if (config != null) { - config.setHost(host); - LinphoneManager.getInstance().initTunnelFromConf(); - } - } - - public int getTunnelPort() { - TunnelConfig config = getTunnelConfig(); - if (config != null) { - return config.getPort(); - } else { - return -1; - } - } - - public void setTunnelPort(int port) { - TunnelConfig config = getTunnelConfig(); - if (config != null) { - config.setPort(port); - LinphoneManager.getInstance().initTunnelFromConf(); - } - } - - public String getTunnelMode() { - return getConfig().getString("app", "tunnel", null); - } - - public void setTunnelMode(String mode) { - getConfig().setString("app", "tunnel", mode); - LinphoneManager.getInstance().initTunnelFromConf(); - } - // End of tunnel settings - - public boolean isProvisioningLoginViewEnabled() { - - return (getConfig() != null) ? getConfig().getBool("app", "show_login_view", false) : false; - } - - public void disableProvisioningLoginView() { - if (isProvisioningLoginViewEnabled()) { // Only do it if it was previously enabled - getConfig().setBool("app", "show_login_view", false); - } else { - Log.w("Remote provisioning login view wasn't enabled, ignoring"); - } - } - - public void firstRemoteProvisioningSuccessful() { - getConfig().setBool("app", "first_remote_provisioning", false); - } - - public boolean isFirstRemoteProvisioning() { - return getConfig().getBool("app", "first_remote_provisioning", true); - } - - public boolean adaptiveRateControlEnabled() { - if (getLc() == null) return false; - return getLc().adaptiveRateControlEnabled(); - } - - public void enableAdaptiveRateControl(boolean enabled) { - if (getLc() == null) return; - getLc().enableAdaptiveRateControl(enabled); - } - - public int getCodecBitrateLimit() { - return getConfig().getInt("audio", "codec_bitrate_limit", 36); - } - - public void setCodecBitrateLimit(int bitrate) { - getConfig().setInt("audio", "codec_bitrate_limit", bitrate); - } - - public void contactsMigrationDone() { - getConfig().setBool("app", "contacts_migration_done", true); - } - - public boolean isContactsMigrationDone() { - return getConfig().getBool("app", "contacts_migration_done", false); - } - - public String getInAppPurchaseValidatingServerUrl() { - return getConfig().getString("in-app-purchase", "server_url", null); - } - - public Purchasable getInAppPurchasedItem() { - String id = getConfig().getString("in-app-purchase", "purchase_item_id", null); - String payload = getConfig().getString("in-app-purchase", "purchase_item_payload", null); - String signature = getConfig().getString("in-app-purchase", "purchase_item_signature", null); - String username = getConfig().getString("in-app-purchase", "purchase_item_username", null); - - Purchasable item = new Purchasable(id).setPayloadAndSignature(payload, signature).setUserData(username); - return item; - } - - public void setInAppPurchasedItem(Purchasable item) { - if (item == null) - return; - - getConfig().setString("in-app-purchase", "purchase_item_id", item.getId()); - getConfig().setString("in-app-purchase", "purchase_item_payload", item.getPayload()); - getConfig().setString("in-app-purchase", "purchase_item_signature", item.getPayloadSignature()); - getConfig().setString("in-app-purchase", "purchase_item_username", item.getUserData()); - } - - public ArrayList getInAppPurchasables() { - ArrayList purchasables = new ArrayList(); - String list = getConfig().getString("in-app-purchase", "purchasable_items_ids", null); - if (list != null) { - for (String purchasable : list.split(";")) { - if (purchasable.length() > 0) { - purchasables.add(purchasable); - } - } - } - return purchasables; - } - - public String getXmlrpcUrl() { - return getConfig().getString("assistant", "xmlrpc_url", null); - } - - public void setXmlrpcUrl(String url) { - getConfig().setString("assistant", "xmlrpc_url", url); - } - - public String getInappPopupTime() { - return getConfig().getString("app", "inapp_popup_time", null); - } - - public void setInappPopupTime(String date) { - getConfig().setString("app", "inapp_popup_time", date); - } - - public void setLinkPopupTime(String date) { - getConfig().setString("app", "link_popup_time", date); - } - - public String getLinkPopupTime() { - return getConfig().getString("app", "link_popup_time", null); - } - - public boolean isLinkPopupEnabled() { - return getConfig().getBool("app", "link_popup_enabled", true); - } - - public void enableLinkPopup(boolean enable) { - getConfig().setBool("app", "link_popup_enabled", enable); - } - - public boolean isLimeSecurityPopupEnabled() { - return getConfig().getBool("app", "lime_security_popup_enabled", true); - } - - public void enableLimeSecurityPopup(boolean enable) { - getConfig().setBool("app", "lime_security_popup_enabled", enable); - } - - public String getDebugPopupAddress() { - return getConfig().getString("app", "debug_popup_magic", null); - } - - public String getActivityToLaunchOnIncomingReceived() { - return getConfig().getString("app", "incoming_call_activity", "org.linphone.LinphoneActivity"); - } - - public void setActivityToLaunchOnIncomingReceived(String name) { - getConfig().setString("app", "incoming_call_activity", name); - } - - public boolean getServiceNotificationVisibility() { - return getConfig().getBool("app", "show_service_notification", false); - } - - public void setServiceNotificationVisibility(boolean enable) { - getConfig().setBool("app", "show_service_notification", enable); - } - - public boolean isOverlayEnabled() { - return getConfig().getBool("app", "display_overlay", false); - } - - public void enableOverlay(boolean enable) { - getConfig().setBool("app", "display_overlay", enable); - } - - public LimeState limeEnabled() { - if (getLc() == null) return LimeState.Disabled; - return getLc().limeEnabled(); - } - - public void enableLime(LimeState lime) { - if (getLc() == null) return; - getLc().enableLime(lime); - } - - public boolean firstTimeAskingForPermission(String permission) { - return firstTimeAskingForPermission(permission, true); - } - - public boolean firstTimeAskingForPermission(String permission, boolean toggle) { - boolean firstTime = getConfig().getBool("app", permission, true); - if (toggle) { - permissionHasBeenAsked(permission); - } - return firstTime; - } - - public void permissionHasBeenAsked(String permission) { - getConfig().setBool("app", permission, false); - } - - public boolean isDeviceRingtoneEnabled() { - int readExternalStorage = mContext.getPackageManager().checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE, mContext.getPackageName()); - return getConfig().getBool("app", "device_ringtone", true) && readExternalStorage == PackageManager.PERMISSION_GRANTED; - } - - public void enableDeviceRingtone(boolean enable) { - getConfig().setBool("app", "device_ringtone", enable); - } - - public boolean isIncomingCallVibrationEnabled() { - return getConfig().getBool("app", "incoming_call_vibration", true); - } - - public void enableIncomingCallVibration(boolean enable) { - getConfig().setBool("app", "incoming_call_vibration", enable); - } - - public boolean isBisFeatureEnabled() { - return getConfig().getBool("app", "bis_feature", true); - } - - public void enableBisFeature(boolean enable) { - getConfig().setBool("app", "bis_feature", enable); - } - - public boolean isAutoAnswerEnabled() { - return getConfig().getBool("app", "auto_answer", false); - } - - public void enableAutoAnswer(boolean enable) { - getConfig().setBool("app", "auto_answer", enable); - } - - public void setAutoAnswerTime(int time) { - getConfig().setInt("app", "auto_answer_delay", time); - } - - public int getAutoAnswerTime() { - return getConfig().getInt("app", "auto_answer_delay", 0); - } - - public int getCodeLength() { - return getConfig().getInt("app", "activation_code_length", 0); - } - - public void disableFriendsStorage() { - getConfig().setBool("misc", "store_friends", false); - } - - public void enableFriendsStorage() { - getConfig().setBool("misc", "store_friends", true); - } - - public boolean isFriendsStorageEnabled() { - return getConfig().getBool("misc", "store_friends", true); - } - - public boolean useBasicChatRoomFor1To1() { - return getConfig().getBool("app", "prefer_basic_chat_room", false); - } - - // 0 is download all, -1 is disable feature, else size is bytes - public int getAutoDownloadFileMaxSize() { - return getLc().getMaxSizeForAutoDownloadIncomingFiles(); - } - - // 0 is download all, -1 is disable feature, else size is bytes - public void setAutoDownloadFileMaxSize(int size) { - getLc().setMaxSizeForAutoDownloadIncomingFiles(size); - } } diff --git a/app/src/main/java/org/linphone/settings/PreferencesListFragment.java b/app/src/main/java/org/linphone/settings/PreferencesListFragment.java index 7c2f9cc03..bb743b5ef 100644 --- a/app/src/main/java/org/linphone/settings/PreferencesListFragment.java +++ b/app/src/main/java/org/linphone/settings/PreferencesListFragment.java @@ -37,34 +37,30 @@ import android.view.ViewGroup; import android.view.ViewParent; import android.widget.ListView; import android.widget.RelativeLayout; - +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; import org.linphone.R; import org.linphone.mediastream.Log; -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; - @SuppressLint("ValidFragment") public class PreferencesListFragment extends ListFragment { - private PreferenceManager mPreferenceManager; - - /** - * The starting request code given out to preference framework. - */ + /** The starting request code given out to preference framework. */ private static final int FIRST_REQUEST_CODE = 100; - private static final int MSG_BIND_PREFERENCES = 0; - private Handler mHandler = new Handler() { - @Override - public void handleMessage(Message msg) { - switch (msg.what) { - case MSG_BIND_PREFERENCES: - bindPreferences(); - break; - } - } - }; + private static final int MSG_BIND_PREFERENCES = 0; + private PreferenceManager mPreferenceManager; private ListView preferencesList; + private Handler mHandler = + new Handler() { + @Override + public void handleMessage(Message msg) { + switch (msg.what) { + case MSG_BIND_PREFERENCES: + bindPreferences(); + break; + } + } + }; private int xmlResID; public PreferencesListFragment(int xmlId) { @@ -72,9 +68,7 @@ public class PreferencesListFragment extends ListFragment { } // Must be provided - public PreferencesListFragment() { - - } + public PreferencesListFragment() {} @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle b) { @@ -111,7 +105,10 @@ public class PreferencesListFragment extends ListFragment { } mPreferenceManager = onCreatePreferenceManager(); - preferencesList = (ListView) LayoutInflater.from(getActivity()).inflate(R.layout.preference_list_content, null); + preferencesList = + (ListView) + LayoutInflater.from(getActivity()) + .inflate(R.layout.preference_list_content, null); preferencesList.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); addPreferencesFromResource(xmlResID); postBindPreferences(); @@ -152,7 +149,9 @@ public class PreferencesListFragment extends ListFragment { public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); try { - Method m = PreferenceManager.class.getDeclaredMethod("dispatchActivityResult", int.class, int.class, Intent.class); + Method m = + PreferenceManager.class.getDeclaredMethod( + "dispatchActivityResult", int.class, int.class, Intent.class); m.setAccessible(true); m.invoke(mPreferenceManager, requestCode, resultCode, data); } catch (Exception e) { @@ -162,9 +161,9 @@ public class PreferencesListFragment extends ListFragment { /** * Posts a message to bind the preferences to the list view. - *

        - * Binding late is preferred as any custom preference types created in - * {@link #onCreate(Bundle)} are able to have their views recycled. + * + *

        Binding late is preferred as any custom preference types created in {@link + * #onCreate(Bundle)} are able to have their views recycled. */ private void postBindPreferences() { if (mHandler.hasMessages(MSG_BIND_PREFERENCES)) return; @@ -185,9 +184,11 @@ public class PreferencesListFragment extends ListFragment { */ private PreferenceManager onCreatePreferenceManager() { try { - Constructor c = PreferenceManager.class.getDeclaredConstructor(Activity.class, int.class); + Constructor c = + PreferenceManager.class.getDeclaredConstructor(Activity.class, int.class); c.setAccessible(true); - PreferenceManager preferenceManager = c.newInstance(this.getActivity(), FIRST_REQUEST_CODE); + PreferenceManager preferenceManager = + c.newInstance(this.getActivity(), FIRST_REQUEST_CODE); return preferenceManager; } catch (Exception e) { Log.e("[PreferencesListFragment] onCreatePreferenceManager " + e); @@ -204,29 +205,10 @@ public class PreferencesListFragment extends ListFragment { return mPreferenceManager; } - /** - * Sets the root of the preference hierarchy that this activity is showing. - * - * @param preferenceScreen The root {@link PreferenceScreen} of the preference hierarchy. - */ - public void setPreferenceScreen(PreferenceScreen preferenceScreen) { - try { - Method m = PreferenceManager.class.getDeclaredMethod("setPreferences", PreferenceScreen.class); - m.setAccessible(true); - boolean result = (Boolean) m.invoke(mPreferenceManager, preferenceScreen); - if (result && preferenceScreen != null) { - postBindPreferences(); - } - } catch (Exception e) { - Log.e("[PreferencesListFragment] setPreferenceScreen " + e); - } - } - /** * Gets the root of the preference hierarchy that this activity is showing. * - * @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() { try { @@ -241,16 +223,47 @@ public class PreferencesListFragment extends ListFragment { } /** - * Inflates the given XML resource and adds the preference hierarchy to the current - * preference hierarchy. + * Sets the root of the preference hierarchy that this activity is showing. + * + * @param preferenceScreen The root {@link PreferenceScreen} of the preference hierarchy. + */ + public void setPreferenceScreen(PreferenceScreen preferenceScreen) { + try { + Method m = + PreferenceManager.class.getDeclaredMethod( + "setPreferences", PreferenceScreen.class); + m.setAccessible(true); + boolean result = (Boolean) m.invoke(mPreferenceManager, preferenceScreen); + if (result && preferenceScreen != null) { + postBindPreferences(); + } + } catch (Exception e) { + Log.e("[PreferencesListFragment] setPreferenceScreen " + e); + } + } + + /** + * Inflates the given XML resource and adds the preference hierarchy to the current preference + * hierarchy. * * @param preferencesResId The XML resource ID to inflate. */ public void addPreferencesFromResource(int preferencesResId) { try { - Method m = PreferenceManager.class.getDeclaredMethod("inflateFromResource", Context.class, int.class, PreferenceScreen.class); + Method m = + PreferenceManager.class.getDeclaredMethod( + "inflateFromResource", + Context.class, + int.class, + PreferenceScreen.class); m.setAccessible(true); - PreferenceScreen prefScreen = (PreferenceScreen) m.invoke(mPreferenceManager, getActivity(), preferencesResId, getPreferenceScreen()); + PreferenceScreen prefScreen = + (PreferenceScreen) + m.invoke( + mPreferenceManager, + getActivity(), + preferencesResId, + getPreferenceScreen()); setPreferenceScreen(prefScreen); } catch (Exception e) { Log.e("[PreferencesListFragment] addPreferencesFromResource " + e); @@ -271,4 +284,4 @@ public class PreferencesListFragment extends ListFragment { } return mPreferenceManager.findPreference(key); } -} \ No newline at end of file +} diff --git a/app/src/main/java/org/linphone/settings/SettingsFragment.java b/app/src/main/java/org/linphone/settings/SettingsFragment.java index 686e20025..3dbbba8dc 100644 --- a/app/src/main/java/org/linphone/settings/SettingsFragment.java +++ b/app/src/main/java/org/linphone/settings/SettingsFragment.java @@ -39,13 +39,13 @@ import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceCategory; import android.preference.PreferenceScreen; import android.provider.Settings; - +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import org.linphone.LinphoneActivity; import org.linphone.LinphoneManager; import org.linphone.LinphoneService; -import org.linphone.utils.FileUtils; -import org.linphone.utils.LinphoneUtils; import org.linphone.R; -import org.linphone.LinphoneActivity; import org.linphone.core.Address; import org.linphone.core.Core; import org.linphone.core.CoreException; @@ -63,29 +63,38 @@ import org.linphone.fragments.FragmentsAvailable; import org.linphone.mediastream.Log; import org.linphone.mediastream.Version; import org.linphone.mediastream.video.capture.hwconf.AndroidCameraConfiguration; +import org.linphone.utils.FileUtils; +import org.linphone.utils.LinphoneUtils; import org.linphone.views.LedPreference; -import java.io.File; -import java.util.ArrayList; -import java.util.List; - public class SettingsFragment extends PreferencesListFragment { private LinphonePreferences mPrefs; private Handler mHandler = new Handler(); private CoreListenerStub mListener; private PreferenceScreen currentPreferenceScreen; - private Preference.OnPreferenceClickListener prefClickListener = new Preference.OnPreferenceClickListener() { - @Override - public boolean onPreferenceClick(Preference preference) { - currentPreferenceScreen = (PreferenceScreen) preference; - return false; - } - }; + private Preference.OnPreferenceClickListener prefClickListener = + new Preference.OnPreferenceClickListener() { + @Override + public boolean onPreferenceClick(Preference preference) { + currentPreferenceScreen = (PreferenceScreen) preference; + return false; + } + }; public SettingsFragment() { super(R.xml.preferences); } + private static void setListPreferenceValues( + ListPreference pref, List entries, List values) { + CharSequence[] contents = new CharSequence[entries.size()]; + entries.toArray(contents); + pref.setEntries(contents); + contents = new CharSequence[values.size()]; + values.toArray(contents); + pref.setEntryValues(contents); + } + public void closePreferenceScreen() { if (currentPreferenceScreen != null && currentPreferenceScreen.getDialog() != null) { currentPreferenceScreen.getDialog().dismiss(); @@ -100,36 +109,49 @@ public class SettingsFragment extends PreferencesListFragment { mPrefs = LinphonePreferences.instance(); removePreviousPreferencesFile(); // Required when updating the preferences order - mListener = new CoreListenerStub() { - @Override - public void onEcCalibrationResult(Core lc, EcCalibratorStatus status, int delayMs) { - lc.removeListener(mListener); - LinphoneManager.getInstance().routeAudioToReceiver(); + mListener = + new CoreListenerStub() { + @Override + public void onEcCalibrationResult( + Core lc, EcCalibratorStatus status, int delayMs) { + lc.removeListener(mListener); + LinphoneManager.getInstance().routeAudioToReceiver(); - CheckBoxPreference echoCancellation = (CheckBoxPreference) findPreference(getString(R.string.pref_echo_cancellation_key)); - Preference echoCancellerCalibration = findPreference(getString(R.string.pref_echo_canceller_calibration_key)); + CheckBoxPreference echoCancellation = + (CheckBoxPreference) + findPreference( + getString(R.string.pref_echo_cancellation_key)); + Preference echoCancellerCalibration = + findPreference( + getString(R.string.pref_echo_canceller_calibration_key)); - if (status == EcCalibratorStatus.DoneNoEcho) { - echoCancellerCalibration.setSummary(R.string.no_echo); - echoCancellation.setChecked(false); - LinphonePreferences.instance().setEchoCancellation(false); - ((AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE)).setMode(AudioManager.MODE_NORMAL); - Log.i("Set audio mode on 'Normal'"); - } else if (status == EcCalibratorStatus.Done) { - echoCancellerCalibration.setSummary(String.format(getString(R.string.ec_calibrated), String.valueOf(delayMs))); - echoCancellation.setChecked(true); - LinphonePreferences.instance().setEchoCancellation(true); - ((AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE)).setMode(AudioManager.MODE_NORMAL); - Log.i("Set audio mode on 'Normal'"); - } else if (status == EcCalibratorStatus.Failed) { - echoCancellerCalibration.setSummary(R.string.failed); - echoCancellation.setChecked(true); - LinphonePreferences.instance().setEchoCancellation(true); - ((AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE)).setMode(AudioManager.MODE_NORMAL); - Log.i("Set audio mode on 'Normal'"); - } - } - }; + if (status == EcCalibratorStatus.DoneNoEcho) { + echoCancellerCalibration.setSummary(R.string.no_echo); + echoCancellation.setChecked(false); + LinphonePreferences.instance().setEchoCancellation(false); + ((AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE)) + .setMode(AudioManager.MODE_NORMAL); + Log.i("Set audio mode on 'Normal'"); + } else if (status == EcCalibratorStatus.Done) { + echoCancellerCalibration.setSummary( + String.format( + getString(R.string.ec_calibrated), + String.valueOf(delayMs))); + echoCancellation.setChecked(true); + LinphonePreferences.instance().setEchoCancellation(true); + ((AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE)) + .setMode(AudioManager.MODE_NORMAL); + Log.i("Set audio mode on 'Normal'"); + } else if (status == EcCalibratorStatus.Failed) { + echoCancellerCalibration.setSummary(R.string.failed); + echoCancellation.setChecked(true); + LinphonePreferences.instance().setEchoCancellation(true); + ((AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE)) + .setMode(AudioManager.MODE_NORMAL); + Log.i("Set audio mode on 'Normal'"); + } + } + }; initSettings(); setListeners(); @@ -155,26 +177,34 @@ public class SettingsFragment extends PreferencesListFragment { initNetworkSettings(); initAdvancedSettings(); - findPreference(getString(R.string.pref_add_account_key)).setOnPreferenceClickListener(new OnPreferenceClickListener() { - @Override - public boolean onPreferenceClick(Preference preference) { - int nbAccounts = mPrefs.getAccountCount(); - LinphoneActivity.instance().displayAccountSettings(nbAccounts); - return true; - } - }); + findPreference(getString(R.string.pref_add_account_key)) + .setOnPreferenceClickListener( + new OnPreferenceClickListener() { + @Override + public boolean onPreferenceClick(Preference preference) { + int nbAccounts = mPrefs.getAccountCount(); + LinphoneActivity.instance().displayAccountSettings(nbAccounts); + return true; + } + }); } // Sets listener for each preference to update the matching value in linphonecore private void setListeners() { - findPreference(getString(R.string.pref_tunnel_key)).setOnPreferenceClickListener(prefClickListener); - findPreference(getString(R.string.pref_audio_key)).setOnPreferenceClickListener(prefClickListener); - findPreference(getString(R.string.pref_video_key)).setOnPreferenceClickListener(prefClickListener); - findPreference(getString(R.string.pref_call_key)).setOnPreferenceClickListener(prefClickListener); - findPreference(getString(R.string.pref_chat_key)).setOnPreferenceClickListener(prefClickListener); - findPreference(getString(R.string.pref_network_key)).setOnPreferenceClickListener(prefClickListener); - findPreference(getString(R.string.pref_advanced_key)).setOnPreferenceClickListener(prefClickListener); - + findPreference(getString(R.string.pref_tunnel_key)) + .setOnPreferenceClickListener(prefClickListener); + findPreference(getString(R.string.pref_audio_key)) + .setOnPreferenceClickListener(prefClickListener); + findPreference(getString(R.string.pref_video_key)) + .setOnPreferenceClickListener(prefClickListener); + findPreference(getString(R.string.pref_call_key)) + .setOnPreferenceClickListener(prefClickListener); + findPreference(getString(R.string.pref_chat_key)) + .setOnPreferenceClickListener(prefClickListener); + findPreference(getString(R.string.pref_network_key)) + .setOnPreferenceClickListener(prefClickListener); + findPreference(getString(R.string.pref_advanced_key)) + .setOnPreferenceClickListener(prefClickListener); setTunnelPreferencesListener(); setAudioPreferencesListener(); @@ -196,14 +226,16 @@ public class SettingsFragment extends PreferencesListFragment { } if (getResources().getBoolean(R.bool.disable_chat)) { - findPreference(getString(R.string.pref_image_sharing_server_key)).setLayoutResource(R.layout.hidden); + findPreference(getString(R.string.pref_image_sharing_server_key)) + .setLayoutResource(R.layout.hidden); } if (!getResources().getBoolean(R.bool.enable_push_id)) { hidePreference(R.string.pref_push_notification_key); } - if (!Version.isVideoCapable() || !LinphoneManager.getLcIfManagerNotDestroyedOrNull().videoSupported()) { + if (!Version.isVideoCapable() + || !LinphoneManager.getLcIfManagerNotDestroyedOrNull().videoSupported()) { emptyAndHidePreference(R.string.pref_video_key); } else { if (!AndroidCameraConfiguration.hasFrontCamera()) { @@ -231,8 +263,7 @@ public class SettingsFragment extends PreferencesListFragment { private void uncheckAndHidePreference(int preferenceKey) { Preference preference = findPreference(getString(preferenceKey)); - if (!(preference instanceof CheckBoxPreference)) - return; + if (!(preference instanceof CheckBoxPreference)) return; CheckBoxPreference checkBoxPreference = (CheckBoxPreference) preference; checkBoxPreference.setChecked(false); @@ -241,16 +272,14 @@ public class SettingsFragment extends PreferencesListFragment { private void emptyAndHidePreference(int preferenceKey) { Preference preference = findPreference(getString(preferenceKey)); - if (preference instanceof PreferenceCategory) - emptyAndHidePreferenceCategory(preferenceKey); + if (preference instanceof PreferenceCategory) emptyAndHidePreferenceCategory(preferenceKey); else if (preference instanceof PreferenceScreen) emptyAndHidePreferenceScreen(preferenceKey); } private void emptyAndHidePreferenceCategory(int preferenceKey) { Preference preference = findPreference(getString(preferenceKey)); - if (!(preference instanceof PreferenceCategory)) - return; + if (!(preference instanceof PreferenceCategory)) return; PreferenceCategory preferenceCategory = (PreferenceCategory) preference; preferenceCategory.removeAll(); @@ -259,8 +288,7 @@ public class SettingsFragment extends PreferencesListFragment { private void emptyAndHidePreferenceScreen(int preferenceKey) { Preference preference = findPreference(getString(preferenceKey)); - if (!(preference instanceof PreferenceScreen)) - return; + if (!(preference instanceof PreferenceScreen)) return; PreferenceScreen preferenceScreen = (PreferenceScreen) preference; preferenceScreen.removeAll(); @@ -291,50 +319,62 @@ public class SettingsFragment extends PreferencesListFragment { } setPreferenceDefaultValueAndSummary(R.string.pref_tunnel_host_key, mPrefs.getTunnelHost()); - setPreferenceDefaultValueAndSummary(R.string.pref_tunnel_port_key, String.valueOf(mPrefs.getTunnelPort())); - ListPreference tunnelModePref = (ListPreference) findPreference(getString(R.string.pref_tunnel_mode_key)); + setPreferenceDefaultValueAndSummary( + R.string.pref_tunnel_port_key, String.valueOf(mPrefs.getTunnelPort())); + ListPreference tunnelModePref = + (ListPreference) findPreference(getString(R.string.pref_tunnel_mode_key)); String tunnelMode = mPrefs.getTunnelMode(); tunnelModePref.setSummary(tunnelMode); tunnelModePref.setValue(tunnelMode); } private void setTunnelPreferencesListener() { - findPreference(getString(R.string.pref_tunnel_host_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - String host = newValue.toString(); - mPrefs.setTunnelHost(host); - preference.setSummary(host); - return true; - } - }); - findPreference(getString(R.string.pref_tunnel_port_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - try { - int port = Integer.parseInt(newValue.toString()); - mPrefs.setTunnelPort(port); - preference.setSummary(String.valueOf(port)); - return true; - } catch (NumberFormatException nfe) { - return false; - } - } - }); - findPreference(getString(R.string.pref_tunnel_mode_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - String mode = newValue.toString(); - mPrefs.setTunnelMode(mode); - preference.setSummary(mode); - return true; - } - }); + findPreference(getString(R.string.pref_tunnel_host_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + String host = newValue.toString(); + mPrefs.setTunnelHost(host); + preference.setSummary(host); + return true; + } + }); + findPreference(getString(R.string.pref_tunnel_port_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + try { + int port = Integer.parseInt(newValue.toString()); + mPrefs.setTunnelPort(port); + preference.setSummary(String.valueOf(port)); + return true; + } catch (NumberFormatException nfe) { + return false; + } + } + }); + findPreference(getString(R.string.pref_tunnel_mode_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + String mode = newValue.toString(); + mPrefs.setTunnelMode(mode); + preference.setSummary(mode); + return true; + } + }); } private void initAccounts() { if (!getResources().getBoolean(R.bool.hide_accounts)) { - PreferenceCategory accounts = (PreferenceCategory) findPreference(getString(R.string.pref_sipaccounts_key)); + PreferenceCategory accounts = + (PreferenceCategory) findPreference(getString(R.string.pref_sipaccounts_key)); accounts.removeAll(); // Get already configured extra accounts @@ -357,19 +397,21 @@ public class SettingsFragment extends PreferencesListFragment { account.setSummary(R.string.default_account_flag); } - account.setOnPreferenceClickListener(new OnPreferenceClickListener() { - public boolean onPreferenceClick(Preference preference) { - LinphoneActivity.instance().displayAccountSettings(accountId); - return false; - } - }); + account.setOnPreferenceClickListener( + new OnPreferenceClickListener() { + public boolean onPreferenceClick(Preference preference) { + LinphoneActivity.instance().displayAccountSettings(accountId); + return false; + } + }); updateAccountLed(account, username, domain, mPrefs.isAccountEnabled(i)); accounts.addPreference(account); } } } - private void updateAccountLed(final LedPreference me, final String username, final String domain, boolean enabled) { + private void updateAccountLed( + final LedPreference me, final String username, final String domain, boolean enabled) { if (!enabled) { me.setLed(R.drawable.led_disconnected); return; @@ -385,12 +427,14 @@ public class SettingsFragment extends PreferencesListFragment { me.setLed(R.drawable.led_error); } else if (lpc.getState() == RegistrationState.Progress) { me.setLed(R.drawable.led_inprogress); - mHandler.postDelayed(new Runnable() { - @Override - public void run() { - updateAccountLed(me, username, domain, true); - } - }, 500); + mHandler.postDelayed( + new Runnable() { + @Override + public void run() { + updateAccountLed(me, username, domain, true); + } + }, + 500); } else { me.setLed(R.drawable.led_disconnected); } @@ -407,7 +451,8 @@ public class SettingsFragment extends PreferencesListFragment { values.add(getString(R.string.pref_media_encryption_key_none)); Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull(); - if (lc == null || getResources().getBoolean(R.bool.disable_all_security_features_for_markets)) { + if (lc == null + || getResources().getBoolean(R.bool.disable_all_security_features_for_markets)) { setListPreferenceValues(pref, entries, values); return; } @@ -430,7 +475,6 @@ public class SettingsFragment extends PreferencesListFragment { if (hasDtls) { entries.add(getString(R.string.media_encryption_dtls)); values.add(getString(R.string.pref_media_encryption_key_dtls)); - } setListPreferenceValues(pref, entries, values); } @@ -526,17 +570,9 @@ public class SettingsFragment extends PreferencesListFragment { } } - private static void setListPreferenceValues(ListPreference pref, List entries, List values) { - CharSequence[] contents = new CharSequence[entries.size()]; - entries.toArray(contents); - pref.setEntries(contents); - contents = new CharSequence[values.size()]; - values.toArray(contents); - pref.setEntryValues(contents); - } - private void initAudioSettings() { - PreferenceCategory codecs = (PreferenceCategory) findPreference(getString(R.string.pref_codecs_key)); + PreferenceCategory codecs = + (PreferenceCategory) findPreference(getString(R.string.pref_codecs_key)); codecs.removeAll(); Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull(); @@ -558,106 +594,141 @@ public class SettingsFragment extends PreferencesListFragment { codec.setSummary(pt.getClockRate() + " Hz"); codec.setDefaultValue(pt.enabled()); - codec.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - boolean enable = (Boolean) newValue; - pt.enable(enable); - return true; - } - }); + codec.setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + boolean enable = (Boolean) newValue; + pt.enable(enable); + return true; + } + }); codecs.addPreference(codec); } } - CheckBoxPreference echoCancellation = (CheckBoxPreference) findPreference(getString(R.string.pref_echo_cancellation_key)); + CheckBoxPreference echoCancellation = + (CheckBoxPreference) findPreference(getString(R.string.pref_echo_cancellation_key)); echoCancellation.setChecked(mPrefs.echoCancellationEnabled()); if (mPrefs.echoCancellationEnabled()) { - Preference echoCalibration = findPreference(getString(R.string.pref_echo_canceller_calibration_key)); - echoCalibration.setSummary(String.format(getString(R.string.ec_calibrated), String.valueOf(mPrefs.getEchoCalibration()))); + Preference echoCalibration = + findPreference(getString(R.string.pref_echo_canceller_calibration_key)); + echoCalibration.setSummary( + String.format( + getString(R.string.ec_calibrated), + String.valueOf(mPrefs.getEchoCalibration()))); } - CheckBoxPreference adaptiveRateControl = (CheckBoxPreference) findPreference(getString(R.string.pref_adaptive_rate_control_key)); + CheckBoxPreference adaptiveRateControl = + (CheckBoxPreference) + findPreference(getString(R.string.pref_adaptive_rate_control_key)); adaptiveRateControl.setChecked(mPrefs.adaptiveRateControlEnabled()); - ListPreference bitrateLimit = (ListPreference) findPreference(getString(R.string.pref_codec_bitrate_limit_key)); + ListPreference bitrateLimit = + (ListPreference) findPreference(getString(R.string.pref_codec_bitrate_limit_key)); bitrateLimit.setSummary(String.valueOf(mPrefs.getCodecBitrateLimit())); bitrateLimit.setValue(String.valueOf(mPrefs.getCodecBitrateLimit())); } private void setAudioPreferencesListener() { - findPreference(getString(R.string.pref_echo_cancellation_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - boolean enabled = (Boolean) newValue; - mPrefs.setEchoCancellation(enabled); - return true; - } - }); + findPreference(getString(R.string.pref_echo_cancellation_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + boolean enabled = (Boolean) newValue; + mPrefs.setEchoCancellation(enabled); + return true; + } + }); - findPreference(getString(R.string.pref_adaptive_rate_control_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - boolean enabled = (Boolean) newValue; - mPrefs.enableAdaptiveRateControl(enabled); - return true; - } - }); + findPreference(getString(R.string.pref_adaptive_rate_control_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + boolean enabled = (Boolean) newValue; + mPrefs.enableAdaptiveRateControl(enabled); + return true; + } + }); - findPreference(getString(R.string.pref_codec_bitrate_limit_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - mPrefs.setCodecBitrateLimit(Integer.parseInt(newValue.toString())); - Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull(); - int bitrate = Integer.parseInt(newValue.toString()); + findPreference(getString(R.string.pref_codec_bitrate_limit_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + mPrefs.setCodecBitrateLimit(Integer.parseInt(newValue.toString())); + Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull(); + int bitrate = Integer.parseInt(newValue.toString()); - for (final PayloadType pt : lc.getAudioPayloadTypes()) { - if (pt.isVbr()) { - pt.setNormalBitrate(bitrate); - } - } + for (final PayloadType pt : lc.getAudioPayloadTypes()) { + if (pt.isVbr()) { + pt.setNormalBitrate(bitrate); + } + } - preference.setSummary(String.valueOf(mPrefs.getCodecBitrateLimit())); - return true; - } - }); + preference.setSummary( + String.valueOf(mPrefs.getCodecBitrateLimit())); + return true; + } + }); - findPreference(getString(R.string.pref_echo_canceller_calibration_key)).setOnPreferenceClickListener(new OnPreferenceClickListener() { - @Override - public boolean onPreferenceClick(Preference preference) { - synchronized (SettingsFragment.this) { - preference.setSummary(R.string.ec_calibrating); + findPreference(getString(R.string.pref_echo_canceller_calibration_key)) + .setOnPreferenceClickListener( + new OnPreferenceClickListener() { + @Override + public boolean onPreferenceClick(Preference preference) { + synchronized (SettingsFragment.this) { + preference.setSummary(R.string.ec_calibrating); - int recordAudio = getActivity().getPackageManager().checkPermission(Manifest.permission.RECORD_AUDIO, getActivity().getPackageName()); - if (recordAudio == PackageManager.PERMISSION_GRANTED) { - startEchoCancellerCalibration(); - } else { - LinphoneActivity.instance().checkAndRequestRecordAudioPermissionForEchoCanceller(); - } - } - return true; - } - }); + int recordAudio = + getActivity() + .getPackageManager() + .checkPermission( + Manifest.permission.RECORD_AUDIO, + getActivity().getPackageName()); + if (recordAudio == PackageManager.PERMISSION_GRANTED) { + startEchoCancellerCalibration(); + } else { + LinphoneActivity.instance() + .checkAndRequestRecordAudioPermissionForEchoCanceller(); + } + } + return true; + } + }); - findPreference(getString(R.string.pref_echo_tester_key)).setOnPreferenceClickListener(new OnPreferenceClickListener() { - @Override - public boolean onPreferenceClick(Preference preference) { - synchronized (SettingsFragment.this) { - int recordAudio = getActivity().getPackageManager().checkPermission(Manifest.permission.RECORD_AUDIO, getActivity().getPackageName()); - if (recordAudio == PackageManager.PERMISSION_GRANTED) { - if (LinphoneManager.getInstance().getEchoTesterStatus()) - stopEchoTester(); - else - startEchoTester(); - } else { - LinphoneActivity.instance().checkAndRequestRecordAudioPermissionsForEchoTester(); - } - } - return true; - } - }); + findPreference(getString(R.string.pref_echo_tester_key)) + .setOnPreferenceClickListener( + new OnPreferenceClickListener() { + @Override + public boolean onPreferenceClick(Preference preference) { + synchronized (SettingsFragment.this) { + int recordAudio = + getActivity() + .getPackageManager() + .checkPermission( + Manifest.permission.RECORD_AUDIO, + getActivity().getPackageName()); + if (recordAudio == PackageManager.PERMISSION_GRANTED) { + if (LinphoneManager.getInstance().getEchoTesterStatus()) + stopEchoTester(); + else startEchoTester(); + } else { + LinphoneActivity.instance() + .checkAndRequestRecordAudioPermissionsForEchoTester(); + } + } + return true; + } + }); } public void startEchoTester() { @@ -684,8 +755,7 @@ public class SettingsFragment extends PreferencesListFragment { public void startEchoCancellerCalibration() { try { - if (LinphoneManager.getInstance().getEchoTesterStatus()) - stopEchoTester(); + if (LinphoneManager.getInstance().getEchoTesterStatus()) stopEchoTester(); LinphoneManager.getLc().addListener(mListener); LinphoneManager.getInstance().startEcCalibration(); } catch (CoreException e) { @@ -694,53 +764,69 @@ public class SettingsFragment extends PreferencesListFragment { } public void echoCalibrationFail() { - Preference echoCancellerCalibration = findPreference(getString(R.string.pref_echo_canceller_calibration_key)); + Preference echoCancellerCalibration = + findPreference(getString(R.string.pref_echo_canceller_calibration_key)); echoCancellerCalibration.setSummary(R.string.failed); } - private void initOpenH264AlertDialog(final OpenH264DownloadHelper mCodecDownloader, final CheckBoxPreference codec) { - mCodecDownloader.setOpenH264HelperListener(LinphoneManager.getInstance().getOpenH264HelperListener()); + private void initOpenH264AlertDialog( + final OpenH264DownloadHelper mCodecDownloader, final CheckBoxPreference codec) { + mCodecDownloader.setOpenH264HelperListener( + LinphoneManager.getInstance().getOpenH264HelperListener()); mCodecDownloader.setUserData(0, LinphoneManager.getInstance().getContext()); mCodecDownloader.setUserData(1, codec); - AlertDialog.Builder builder = new AlertDialog.Builder(LinphoneManager.getInstance().getContext()); + AlertDialog.Builder builder = + new AlertDialog.Builder(LinphoneManager.getInstance().getContext()); builder.setCancelable(false); - builder.setMessage("Do you agree to download " + mCodecDownloader.getLicenseMessage()).setPositiveButton("Yes", new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - if (which == DialogInterface.BUTTON_POSITIVE) - mCodecDownloader.downloadCodec(); - } - }); - builder.setNegativeButton("No", new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - if (which == DialogInterface.BUTTON_NEGATIVE) { - // Disable H264 - codec.setChecked(false); - } - } - }).show(); + builder.setMessage("Do you agree to download " + mCodecDownloader.getLicenseMessage()) + .setPositiveButton( + "Yes", + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + if (which == DialogInterface.BUTTON_POSITIVE) + mCodecDownloader.downloadCodec(); + } + }); + builder.setNegativeButton( + "No", + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + if (which == DialogInterface.BUTTON_NEGATIVE) { + // Disable H264 + codec.setChecked(false); + } + } + }) + .show(); } private void initVideoSettings() { - initializePreferredVideoSizePreferences((ListPreference) findPreference(getString(R.string.pref_preferred_video_size_key))); - initializePreferredVideoFpsPreferences((ListPreference) findPreference(getString(R.string.pref_preferred_video_fps_key))); - EditTextPreference bandwidth = (EditTextPreference) findPreference(getString(R.string.pref_bandwidth_limit_key)); + initializePreferredVideoSizePreferences( + (ListPreference) findPreference(getString(R.string.pref_preferred_video_size_key))); + initializePreferredVideoFpsPreferences( + (ListPreference) findPreference(getString(R.string.pref_preferred_video_fps_key))); + EditTextPreference bandwidth = + (EditTextPreference) findPreference(getString(R.string.pref_bandwidth_limit_key)); bandwidth.setText(Integer.toString(mPrefs.getBandwidthLimit())); bandwidth.setSummary(bandwidth.getText()); updateVideoPreferencesAccordingToPreset(); - ListPreference videoPresetPref = (ListPreference) findPreference(getString(R.string.pref_video_preset_key)); + ListPreference videoPresetPref = + (ListPreference) findPreference(getString(R.string.pref_video_preset_key)); videoPresetPref.setSummary(mPrefs.getVideoPreset()); videoPresetPref.setValue(mPrefs.getVideoPreset()); - PreferenceCategory codecs = (PreferenceCategory) findPreference(getString(R.string.pref_video_codecs_key)); + PreferenceCategory codecs = + (PreferenceCategory) findPreference(getString(R.string.pref_video_codecs_key)); codecs.removeAll(); final Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull(); - final OpenH264DownloadHelper mCodecDownloader = LinphoneManager.getInstance().getOpenH264DownloadHelper(); + final OpenH264DownloadHelper mCodecDownloader = + LinphoneManager.getInstance().getOpenH264DownloadHelper(); boolean h264IsHere = false; for (final PayloadType pt : lc.getVideoPayloadTypes()) { @@ -759,7 +845,8 @@ public class SettingsFragment extends PreferencesListFragment { } } else if (pt.getMimeType().equals("H264")) { h264IsHere = true; - if (OpenH264DownloadHelper.isOpenH264DownloadEnabled() && mCodecDownloader.isCodecFound()) { + if (OpenH264DownloadHelper.isOpenH264DownloadEnabled() + && mCodecDownloader.isCodecFound()) { codec.setSummary(mCodecDownloader.getLicenseMessage()); codec.setTitle("OpenH264"); } @@ -767,40 +854,63 @@ public class SettingsFragment extends PreferencesListFragment { codec.setDefaultValue(pt.enabled()); - codec.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - boolean enable = (Boolean) newValue; - if (OpenH264DownloadHelper.isOpenH264DownloadEnabled()) { - if (enable && Version.getCpuAbis().contains("armeabi-v7a") && !Version.getCpuAbis().contains("x86") - && pt.getMimeType().equals("H264") && !mCodecDownloader.isCodecFound()) { - mCodecDownloader.setOpenH264HelperListener(LinphoneManager.getInstance().getOpenH264HelperListener()); - mCodecDownloader.setUserData(0, LinphoneManager.getInstance().getContext()); - mCodecDownloader.setUserData(1, codec); + codec.setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange(Preference preference, Object newValue) { + boolean enable = (Boolean) newValue; + if (OpenH264DownloadHelper.isOpenH264DownloadEnabled()) { + if (enable + && Version.getCpuAbis().contains("armeabi-v7a") + && !Version.getCpuAbis().contains("x86") + && pt.getMimeType().equals("H264") + && !mCodecDownloader.isCodecFound()) { + mCodecDownloader.setOpenH264HelperListener( + LinphoneManager.getInstance() + .getOpenH264HelperListener()); + mCodecDownloader.setUserData( + 0, LinphoneManager.getInstance().getContext()); + mCodecDownloader.setUserData(1, codec); - AlertDialog.Builder builder = new AlertDialog.Builder(LinphoneManager.getInstance().getContext()); - builder.setCancelable(false); - builder.setMessage("Do you agree to download " + mCodecDownloader.getLicenseMessage()).setPositiveButton("Yes", new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - if (which == DialogInterface.BUTTON_POSITIVE) - mCodecDownloader.downloadCodec(); + AlertDialog.Builder builder = + new AlertDialog.Builder( + LinphoneManager.getInstance().getContext()); + builder.setCancelable(false); + builder.setMessage( + "Do you agree to download " + + mCodecDownloader.getLicenseMessage()) + .setPositiveButton( + "Yes", + new DialogInterface.OnClickListener() { + @Override + public void onClick( + DialogInterface dialog, int which) { + if (which + == DialogInterface + .BUTTON_POSITIVE) + mCodecDownloader.downloadCodec(); + } + }); + builder.setNegativeButton( + "No", + new DialogInterface.OnClickListener() { + @Override + public void onClick( + DialogInterface dialog, int which) { + if (which + == DialogInterface + .BUTTON_NEGATIVE) { + // Disable H264 + } + } + }) + .show(); } - }); - builder.setNegativeButton("No", new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - if (which == DialogInterface.BUTTON_NEGATIVE) { - // Disable H264 - } - } - }).show(); + } + pt.enable(enable); + return true; } - } - pt.enable(enable); - return true; - } - }); + }); codecs.addPreference(codec); } @@ -809,27 +919,38 @@ public class SettingsFragment extends PreferencesListFragment { final CheckBoxPreference codec = new CheckBoxPreference(getActivity()); codec.setTitle("OpenH264"); codec.setSummary(mCodecDownloader.getLicenseMessage()); - //codec.setEnabled(false); - codec.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - boolean enable = (Boolean) newValue; - if (mCodecDownloader.isOpenH264DownloadEnabled()) { - if (enable && Version.getCpuAbis().contains("armeabi-v7a") && !Version.getCpuAbis().contains("x86") - && !mCodecDownloader.isCodecFound()) { - initOpenH264AlertDialog(mCodecDownloader, codec); + // codec.setEnabled(false); + codec.setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange(Preference preference, Object newValue) { + boolean enable = (Boolean) newValue; + if (mCodecDownloader.isOpenH264DownloadEnabled()) { + if (enable + && Version.getCpuAbis().contains("armeabi-v7a") + && !Version.getCpuAbis().contains("x86") + && !mCodecDownloader.isCodecFound()) { + initOpenH264AlertDialog(mCodecDownloader, codec); + } + } + return true; } - } - return true; - } - }); + }); codecs.addPreference(codec); } - ((CheckBoxPreference) findPreference(getString(R.string.pref_video_enable_key))).setChecked(mPrefs.isVideoEnabled()); - ((CheckBoxPreference) findPreference(getString(R.string.pref_video_use_front_camera_key))).setChecked(mPrefs.useFrontCam()); - ((CheckBoxPreference) findPreference(getString(R.string.pref_video_initiate_call_with_video_key))).setChecked(mPrefs.shouldInitiateVideoCall()); - ((CheckBoxPreference) findPreference(getString(R.string.pref_video_automatically_accept_video_key))).setChecked(mPrefs.shouldAutomaticallyAcceptVideoRequests()); - ((CheckBoxPreference) findPreference(getString(R.string.pref_overlay_key))).setChecked(mPrefs.isOverlayEnabled()); + ((CheckBoxPreference) findPreference(getString(R.string.pref_video_enable_key))) + .setChecked(mPrefs.isVideoEnabled()); + ((CheckBoxPreference) findPreference(getString(R.string.pref_video_use_front_camera_key))) + .setChecked(mPrefs.useFrontCam()); + ((CheckBoxPreference) + findPreference(getString(R.string.pref_video_initiate_call_with_video_key))) + .setChecked(mPrefs.shouldInitiateVideoCall()); + ((CheckBoxPreference) + findPreference( + getString(R.string.pref_video_automatically_accept_video_key))) + .setChecked(mPrefs.shouldAutomaticallyAcceptVideoRequests()); + ((CheckBoxPreference) findPreference(getString(R.string.pref_overlay_key))) + .setChecked(mPrefs.isOverlayEnabled()); } private void updateVideoPreferencesAccordingToPreset() { @@ -840,122 +961,173 @@ public class SettingsFragment extends PreferencesListFragment { findPreference(getString(R.string.pref_preferred_video_fps_key)).setEnabled(false); findPreference(getString(R.string.pref_bandwidth_limit_key)).setEnabled(false); } - findPreference(getString(R.string.pref_video_preset_key)).setSummary(mPrefs.getVideoPreset()); + findPreference(getString(R.string.pref_video_preset_key)) + .setSummary(mPrefs.getVideoPreset()); int fps = mPrefs.getPreferredVideoFps(); String fpsStr = Integer.toString(fps); if (fpsStr.equals("0")) { fpsStr = getString(R.string.pref_none); } findPreference(getString(R.string.pref_preferred_video_fps_key)).setSummary(fpsStr); - findPreference(getString(R.string.pref_bandwidth_limit_key)).setSummary(Integer.toString(mPrefs.getBandwidthLimit())); + findPreference(getString(R.string.pref_bandwidth_limit_key)) + .setSummary(Integer.toString(mPrefs.getBandwidthLimit())); } private void setVideoPreferencesListener() { - findPreference(getString(R.string.pref_video_enable_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - boolean enable = (Boolean) newValue; - mPrefs.enableVideo(enable); - if (!enable) { - mPrefs.setInitiateVideoCall(false); - mPrefs.setAutomaticallyAcceptVideoRequests(false); - ((CheckBoxPreference) findPreference(getString(R.string.pref_video_initiate_call_with_video_key))).setChecked(mPrefs.shouldInitiateVideoCall()); - ((CheckBoxPreference) findPreference(getString(R.string.pref_video_automatically_accept_video_key))).setChecked(mPrefs.shouldAutomaticallyAcceptVideoRequests()); - } - return true; - } - }); + findPreference(getString(R.string.pref_video_enable_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + boolean enable = (Boolean) newValue; + mPrefs.enableVideo(enable); + if (!enable) { + mPrefs.setInitiateVideoCall(false); + mPrefs.setAutomaticallyAcceptVideoRequests(false); + ((CheckBoxPreference) + findPreference( + getString( + R.string + .pref_video_initiate_call_with_video_key))) + .setChecked(mPrefs.shouldInitiateVideoCall()); + ((CheckBoxPreference) + findPreference( + getString( + R.string + .pref_video_automatically_accept_video_key))) + .setChecked( + mPrefs + .shouldAutomaticallyAcceptVideoRequests()); + } + return true; + } + }); - findPreference(getString(R.string.pref_video_use_front_camera_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - boolean enable = (Boolean) newValue; - mPrefs.setFrontCamAsDefault(enable); - return true; - } - }); + findPreference(getString(R.string.pref_video_use_front_camera_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + boolean enable = (Boolean) newValue; + mPrefs.setFrontCamAsDefault(enable); + return true; + } + }); - findPreference(getString(R.string.pref_video_initiate_call_with_video_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - boolean enable = (Boolean) newValue; - mPrefs.setInitiateVideoCall(enable); - return true; - } - }); + findPreference(getString(R.string.pref_video_initiate_call_with_video_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + boolean enable = (Boolean) newValue; + mPrefs.setInitiateVideoCall(enable); + return true; + } + }); - findPreference(getString(R.string.pref_video_automatically_accept_video_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - boolean enable = (Boolean) newValue; - mPrefs.setAutomaticallyAcceptVideoRequests(enable); - return true; - } - }); + findPreference(getString(R.string.pref_video_automatically_accept_video_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + boolean enable = (Boolean) newValue; + mPrefs.setAutomaticallyAcceptVideoRequests(enable); + return true; + } + }); - findPreference(getString(R.string.pref_video_preset_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - mPrefs.setVideoPreset(newValue.toString()); - preference.setSummary(mPrefs.getVideoPreset()); - updateVideoPreferencesAccordingToPreset(); - return true; - } - }); - findPreference(getString(R.string.pref_preferred_video_size_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - mPrefs.setPreferredVideoSize(newValue.toString()); - preference.setSummary(mPrefs.getPreferredVideoSize()); - updateVideoPreferencesAccordingToPreset(); - return true; - } - }); + findPreference(getString(R.string.pref_video_preset_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + mPrefs.setVideoPreset(newValue.toString()); + preference.setSummary(mPrefs.getVideoPreset()); + updateVideoPreferencesAccordingToPreset(); + return true; + } + }); + findPreference(getString(R.string.pref_preferred_video_size_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + mPrefs.setPreferredVideoSize(newValue.toString()); + preference.setSummary(mPrefs.getPreferredVideoSize()); + updateVideoPreferencesAccordingToPreset(); + return true; + } + }); - findPreference(getString(R.string.pref_preferred_video_fps_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - mPrefs.setPreferredVideoFps(Integer.parseInt(newValue.toString())); - updateVideoPreferencesAccordingToPreset(); - return true; - } - }); + findPreference(getString(R.string.pref_preferred_video_fps_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + mPrefs.setPreferredVideoFps(Integer.parseInt(newValue.toString())); + updateVideoPreferencesAccordingToPreset(); + return true; + } + }); - findPreference(getString(R.string.pref_bandwidth_limit_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - mPrefs.setBandwidthLimit(Integer.parseInt(newValue.toString())); - preference.setSummary(newValue.toString()); - return true; - } - }); + findPreference(getString(R.string.pref_bandwidth_limit_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + mPrefs.setBandwidthLimit(Integer.parseInt(newValue.toString())); + preference.setSummary(newValue.toString()); + return true; + } + }); - findPreference(getString(R.string.pref_overlay_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - boolean enable = (Boolean) newValue; - if (enable) { - if (LinphoneActivity.instance().checkAndRequestOverlayPermission()) { - mPrefs.enableOverlay(true); - } - } else { - mPrefs.enableOverlay(false); - } - return true; - } - }); + findPreference(getString(R.string.pref_overlay_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + boolean enable = (Boolean) newValue; + if (enable) { + if (LinphoneActivity.instance() + .checkAndRequestOverlayPermission()) { + mPrefs.enableOverlay(true); + } + } else { + mPrefs.enableOverlay(false); + } + return true; + } + }); } private void initCallSettings() { - CheckBoxPreference deviceRingtone = (CheckBoxPreference) findPreference(getString(R.string.pref_device_ringtone_key)); - CheckBoxPreference incomingCallVibration = (CheckBoxPreference) findPreference(getString(R.string.pref_incoming_call_vibration_key)); - CheckBoxPreference autoAnswer = (CheckBoxPreference) findPreference(getString(R.string.pref_auto_answer_key)); - CheckBoxPreference rfc2833 = (CheckBoxPreference) findPreference(getString(R.string.pref_rfc2833_dtmf_key)); - CheckBoxPreference sipInfo = (CheckBoxPreference) findPreference(getString(R.string.pref_sipinfo_dtmf_key)); - CheckBoxPreference dialerCall = (CheckBoxPreference) findPreference(getString(R.string.pref_dialer_call_key)); - EditTextPreference incTimeout = (EditTextPreference) findPreference(getString(R.string.pref_incoming_call_timeout_key)); - EditTextPreference autoAnswerTime = (EditTextPreference) findPreference(getString(R.string.pref_auto_answer_time_key)); - + CheckBoxPreference deviceRingtone = + (CheckBoxPreference) findPreference(getString(R.string.pref_device_ringtone_key)); + CheckBoxPreference incomingCallVibration = + (CheckBoxPreference) + findPreference(getString(R.string.pref_incoming_call_vibration_key)); + CheckBoxPreference autoAnswer = + (CheckBoxPreference) findPreference(getString(R.string.pref_auto_answer_key)); + CheckBoxPreference rfc2833 = + (CheckBoxPreference) findPreference(getString(R.string.pref_rfc2833_dtmf_key)); + CheckBoxPreference sipInfo = + (CheckBoxPreference) findPreference(getString(R.string.pref_sipinfo_dtmf_key)); + CheckBoxPreference dialerCall = + (CheckBoxPreference) findPreference(getString(R.string.pref_dialer_call_key)); + EditTextPreference incTimeout = + (EditTextPreference) + findPreference(getString(R.string.pref_incoming_call_timeout_key)); + EditTextPreference autoAnswerTime = + (EditTextPreference) findPreference(getString(R.string.pref_auto_answer_time_key)); rfc2833.setChecked(mPrefs.useRfc2833Dtmfs()); sipInfo.setChecked(mPrefs.useSipInfoDtmfs()); @@ -977,501 +1149,684 @@ public class SettingsFragment extends PreferencesListFragment { } private void setCallPreferencesListener() { - findPreference(getString(R.string.pref_device_ringtone_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - boolean use = (Boolean) newValue; - if (use) { - int readExternalStorage = getActivity().getPackageManager().checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE, getActivity().getPackageName()); - if (readExternalStorage == PackageManager.PERMISSION_GRANTED) { - mPrefs.enableDeviceRingtone(true); - LinphoneManager.getInstance().enableDeviceRingtone(true); - } else { - LinphoneActivity.instance().checkAndRequestReadExternalStoragePermissionForDeviceRingtone(); - } - } else { - mPrefs.enableDeviceRingtone(false); - LinphoneManager.getInstance().enableDeviceRingtone(false); - } + findPreference(getString(R.string.pref_device_ringtone_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + boolean use = (Boolean) newValue; + if (use) { + int readExternalStorage = + getActivity() + .getPackageManager() + .checkPermission( + Manifest.permission + .READ_EXTERNAL_STORAGE, + getActivity().getPackageName()); + if (readExternalStorage == PackageManager.PERMISSION_GRANTED) { + mPrefs.enableDeviceRingtone(true); + LinphoneManager.getInstance().enableDeviceRingtone(true); + } else { + LinphoneActivity.instance() + .checkAndRequestReadExternalStoragePermissionForDeviceRingtone(); + } + } else { + mPrefs.enableDeviceRingtone(false); + LinphoneManager.getInstance().enableDeviceRingtone(false); + } - return true; - } - }); + return true; + } + }); - findPreference(getString(R.string.pref_incoming_call_vibration_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - boolean use = (Boolean) newValue; - mPrefs.enableIncomingCallVibration(use); - return true; - } - }); + findPreference(getString(R.string.pref_incoming_call_vibration_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + boolean use = (Boolean) newValue; + mPrefs.enableIncomingCallVibration(use); + return true; + } + }); - findPreference(getString(R.string.pref_media_encryption_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - String value = newValue.toString(); - MediaEncryption menc = MediaEncryption.None; - if (value.equals(getString(R.string.pref_media_encryption_key_srtp))) - menc = MediaEncryption.SRTP; - else if (value.equals(getString(R.string.pref_media_encryption_key_zrtp))) - menc = MediaEncryption.ZRTP; - else if (value.equals(getString(R.string.pref_media_encryption_key_dtls))) - menc = MediaEncryption.DTLS; - mPrefs.setMediaEncryption(menc); + findPreference(getString(R.string.pref_media_encryption_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + String value = newValue.toString(); + MediaEncryption menc = MediaEncryption.None; + if (value.equals( + getString(R.string.pref_media_encryption_key_srtp))) + menc = MediaEncryption.SRTP; + else if (value.equals( + getString(R.string.pref_media_encryption_key_zrtp))) + menc = MediaEncryption.ZRTP; + else if (value.equals( + getString(R.string.pref_media_encryption_key_dtls))) + menc = MediaEncryption.DTLS; + mPrefs.setMediaEncryption(menc); - preference.setSummary(mPrefs.getMediaEncryption().toString()); - return true; - } - }); + preference.setSummary(mPrefs.getMediaEncryption().toString()); + return true; + } + }); - initMediaEncryptionPreference((ListPreference) findPreference(getString(R.string.pref_media_encryption_key))); + initMediaEncryptionPreference( + (ListPreference) findPreference(getString(R.string.pref_media_encryption_key))); - findPreference(getString(R.string.pref_auto_answer_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - boolean use = (Boolean) newValue; - mPrefs.enableAutoAnswer(use); - if (use) { - findPreference(getString(R.string.pref_auto_answer_time_key)).setEnabled(true); - } else { - findPreference(getString(R.string.pref_auto_answer_time_key)).setEnabled(false); - } - return true; - } - }); + findPreference(getString(R.string.pref_auto_answer_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + boolean use = (Boolean) newValue; + mPrefs.enableAutoAnswer(use); + if (use) { + findPreference(getString(R.string.pref_auto_answer_time_key)) + .setEnabled(true); + } else { + findPreference(getString(R.string.pref_auto_answer_time_key)) + .setEnabled(false); + } + return true; + } + }); - findPreference(getString(R.string.pref_rfc2833_dtmf_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - boolean use = (Boolean) newValue; - mPrefs.sendDtmfsAsRfc2833(use); - return true; - } - }); + findPreference(getString(R.string.pref_rfc2833_dtmf_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + boolean use = (Boolean) newValue; + mPrefs.sendDtmfsAsRfc2833(use); + return true; + } + }); - findPreference(getString(R.string.pref_voice_mail_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - EditTextPreference voiceMail = (EditTextPreference) findPreference(getString(R.string.pref_voice_mail_key)); - voiceMail.setSummary(newValue.toString()); - voiceMail.setText(newValue.toString()); - mPrefs.setVoiceMailUri(newValue.toString()); - return true; - } - }); + findPreference(getString(R.string.pref_voice_mail_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + EditTextPreference voiceMail = + (EditTextPreference) + findPreference( + getString(R.string.pref_voice_mail_key)); + voiceMail.setSummary(newValue.toString()); + voiceMail.setText(newValue.toString()); + mPrefs.setVoiceMailUri(newValue.toString()); + return true; + } + }); - findPreference(getString(R.string.pref_sipinfo_dtmf_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - boolean use = (Boolean) newValue; - mPrefs.sendDTMFsAsSipInfo(use); - return true; - } - }); + findPreference(getString(R.string.pref_sipinfo_dtmf_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + boolean use = (Boolean) newValue; + mPrefs.sendDTMFsAsSipInfo(use); + return true; + } + }); - findPreference(getString(R.string.pref_dialer_call_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - boolean use = (Boolean) newValue; - mPrefs.setNativeDialerCall(use); - return true; - } - }); + findPreference(getString(R.string.pref_dialer_call_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + boolean use = (Boolean) newValue; + mPrefs.setNativeDialerCall(use); + return true; + } + }); - findPreference(getString(R.string.pref_incoming_call_timeout_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - String value = (String) newValue; - try { - mPrefs.setIncTimeout(Integer.valueOf(value)); - preference.setSummary(value); - } catch (NumberFormatException nfe) { - Log.e("Value is not an Integer ! " + value); - return false; - } - return true; - } - }); + findPreference(getString(R.string.pref_incoming_call_timeout_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + String value = (String) newValue; + try { + mPrefs.setIncTimeout(Integer.valueOf(value)); + preference.setSummary(value); + } catch (NumberFormatException nfe) { + Log.e("Value is not an Integer ! " + value); + return false; + } + return true; + } + }); - findPreference(getString(R.string.pref_auto_answer_time_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - String value = (String) newValue; - mPrefs.setAutoAnswerTime(Integer.valueOf(value)); - preference.setSummary(value); - return true; - } - }); + findPreference(getString(R.string.pref_auto_answer_time_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + String value = (String) newValue; + mPrefs.setAutoAnswerTime(Integer.valueOf(value)); + preference.setSummary(value); + return true; + } + }); } private void setEncryptionZrtp() { - LinphoneUtils.displayErrorAlert(getString(R.string.lime_encryption_enable_zrtp), LinphoneActivity.instance()); + LinphoneUtils.displayErrorAlert( + getString(R.string.lime_encryption_enable_zrtp), LinphoneActivity.instance()); mPrefs.setMediaEncryption(MediaEncryption.ZRTP); - findPreference(getString(R.string.pref_media_encryption_key)).setSummary(mPrefs.getMediaEncryption().toString()); + findPreference(getString(R.string.pref_media_encryption_key)) + .setSummary(mPrefs.getMediaEncryption().toString()); } private void initChatSettings() { - setPreferenceDefaultValueAndSummary(R.string.pref_image_sharing_server_key, mPrefs.getSharingPictureServerUrl()); - initLimeEncryptionPreference((ListPreference) findPreference(getString(R.string.pref_use_lime_encryption_key))); - initAutoDownloadPolicyPreference((ListPreference) findPreference(getString(R.string.pref_auto_download_policy_key))); + setPreferenceDefaultValueAndSummary( + R.string.pref_image_sharing_server_key, mPrefs.getSharingPictureServerUrl()); + initLimeEncryptionPreference( + (ListPreference) findPreference(getString(R.string.pref_use_lime_encryption_key))); + initAutoDownloadPolicyPreference( + (ListPreference) findPreference(getString(R.string.pref_auto_download_policy_key))); int max_size = mPrefs.getAutoDownloadFileMaxSize(); - setPreferenceDefaultValueAndSummary(R.string.pref_auto_download_max_size_key, String.valueOf(max_size)); - findPreference(getString(R.string.pref_auto_download_max_size_key)).setEnabled(max_size > 0); + setPreferenceDefaultValueAndSummary( + R.string.pref_auto_download_max_size_key, String.valueOf(max_size)); + findPreference(getString(R.string.pref_auto_download_max_size_key)) + .setEnabled(max_size > 0); if (Version.sdkStrictlyBelow(Version.API26_O_80)) { - findPreference(getString(R.string.pref_android_app_notif_settings_key)).setLayoutResource(R.layout.hidden); + findPreference(getString(R.string.pref_android_app_notif_settings_key)) + .setLayoutResource(R.layout.hidden); } } private void setChatPreferencesListener() { - findPreference(getString(R.string.pref_image_sharing_server_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - String value = (String) newValue; - mPrefs.setSharingPictureServerUrl(value); - preference.setSummary(value); - return true; - } - }); + findPreference(getString(R.string.pref_image_sharing_server_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + String value = (String) newValue; + mPrefs.setSharingPictureServerUrl(value); + preference.setSummary(value); + return true; + } + }); - findPreference(getString(R.string.pref_use_lime_encryption_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - String value = newValue.toString(); - LimeState lime = LimeState.Disabled; - if (value.equals(LimeState.Mandatory.toString())) - lime = LimeState.Mandatory; - else if (value.equals(LimeState.Preferred.toString())) - lime = LimeState.Preferred; - mPrefs.enableLime(lime); + findPreference(getString(R.string.pref_use_lime_encryption_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + String value = newValue.toString(); + LimeState lime = LimeState.Disabled; + if (value.equals(LimeState.Mandatory.toString())) + lime = LimeState.Mandatory; + else if (value.equals(LimeState.Preferred.toString())) + lime = LimeState.Preferred; + mPrefs.enableLime(lime); - lime = mPrefs.limeEnabled(); - if (lime == LimeState.Disabled) { - preference.setSummary(getString(R.string.lime_encryption_entry_disabled)); - } else if (lime == LimeState.Mandatory) { - setEncryptionZrtp(); - preference.setSummary(getString(R.string.lime_encryption_entry_mandatory)); - } else if (lime == LimeState.Preferred) { - setEncryptionZrtp(); - preference.setSummary(getString(R.string.lime_encryption_entry_preferred)); - } + lime = mPrefs.limeEnabled(); + if (lime == LimeState.Disabled) { + preference.setSummary( + getString(R.string.lime_encryption_entry_disabled)); + } else if (lime == LimeState.Mandatory) { + setEncryptionZrtp(); + preference.setSummary( + getString(R.string.lime_encryption_entry_mandatory)); + } else if (lime == LimeState.Preferred) { + setEncryptionZrtp(); + preference.setSummary( + getString(R.string.lime_encryption_entry_preferred)); + } - return true; - } - }); + return true; + } + }); - findPreference(getString(R.string.pref_android_app_notif_settings_key)).setOnPreferenceClickListener(new OnPreferenceClickListener() { - @Override - public boolean onPreferenceClick(Preference preference) { - synchronized (SettingsFragment.this) { - Context context = SettingsFragment.this.getActivity(); - Intent i = new Intent(); - i.setAction(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS); - i.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName()); - i.putExtra(Settings.EXTRA_CHANNEL_ID, context.getString(R.string.notification_channel_id)); - i.addCategory(Intent.CATEGORY_DEFAULT); - 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; - } - } - }); + findPreference(getString(R.string.pref_android_app_notif_settings_key)) + .setOnPreferenceClickListener( + new OnPreferenceClickListener() { + @Override + public boolean onPreferenceClick(Preference preference) { + synchronized (SettingsFragment.this) { + Context context = SettingsFragment.this.getActivity(); + Intent i = new Intent(); + i.setAction(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS); + i.putExtra( + Settings.EXTRA_APP_PACKAGE, context.getPackageName()); + i.putExtra( + Settings.EXTRA_CHANNEL_ID, + context.getString(R.string.notification_channel_id)); + i.addCategory(Intent.CATEGORY_DEFAULT); + 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; + } + } + }); - findPreference(getString(R.string.pref_auto_download_policy_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - String value = (String)newValue; - int size = Integer.valueOf(value); - mPrefs.setAutoDownloadFileMaxSize(size); - initAutoDownloadPolicyPreference((ListPreference) findPreference(getString(R.string.pref_auto_download_policy_key))); - setPreferenceDefaultValueAndSummary(R.string.pref_auto_download_max_size_key, String.valueOf(size)); - findPreference(getString(R.string.pref_auto_download_max_size_key)).setEnabled(size > 0); - return true; - } - }); + findPreference(getString(R.string.pref_auto_download_policy_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + String value = (String) newValue; + int size = Integer.valueOf(value); + mPrefs.setAutoDownloadFileMaxSize(size); + initAutoDownloadPolicyPreference( + (ListPreference) + findPreference( + getString( + R.string + .pref_auto_download_policy_key))); + setPreferenceDefaultValueAndSummary( + R.string.pref_auto_download_max_size_key, + String.valueOf(size)); + findPreference(getString(R.string.pref_auto_download_max_size_key)) + .setEnabled(size > 0); + return true; + } + }); - findPreference(getString(R.string.pref_auto_download_max_size_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - String value = (String)newValue; - int size = Integer.valueOf(value); - mPrefs.setAutoDownloadFileMaxSize(size); - preference.setSummary(String.valueOf(size)); - preference.setEnabled(size > 0); - initAutoDownloadPolicyPreference((ListPreference) findPreference(getString(R.string.pref_auto_download_policy_key))); - return true; - } - }); + findPreference(getString(R.string.pref_auto_download_max_size_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + String value = (String) newValue; + int size = Integer.valueOf(value); + mPrefs.setAutoDownloadFileMaxSize(size); + preference.setSummary(String.valueOf(size)); + preference.setEnabled(size > 0); + initAutoDownloadPolicyPreference( + (ListPreference) + findPreference( + getString( + R.string + .pref_auto_download_policy_key))); + return true; + } + }); } private void initNetworkSettings() { - ((CheckBoxPreference) findPreference(getString(R.string.pref_wifi_only_key))).setChecked(mPrefs.isWifiOnlyEnabled()); + ((CheckBoxPreference) findPreference(getString(R.string.pref_wifi_only_key))) + .setChecked(mPrefs.isWifiOnlyEnabled()); // Disable UPnP if ICE si enabled, or disable ICE if UPnP is enabled - CheckBoxPreference ice = (CheckBoxPreference) findPreference(getString(R.string.pref_ice_enable_key)); - CheckBoxPreference turn = (CheckBoxPreference) findPreference(getString(R.string.pref_turn_enable_key)); + CheckBoxPreference ice = + (CheckBoxPreference) findPreference(getString(R.string.pref_ice_enable_key)); + CheckBoxPreference turn = + (CheckBoxPreference) findPreference(getString(R.string.pref_turn_enable_key)); ice.setChecked(mPrefs.isIceEnabled()); turn.setEnabled(mPrefs.getStunServer() != null); turn.setChecked(mPrefs.isTurnEnabled()); - EditTextPreference turnUsername = (EditTextPreference) findPreference(getString(R.string.pref_turn_username_key)); - EditTextPreference turnPassword = (EditTextPreference) findPreference(getString(R.string.pref_turn_passwd_key)); + EditTextPreference turnUsername = + (EditTextPreference) findPreference(getString(R.string.pref_turn_username_key)); + EditTextPreference turnPassword = + (EditTextPreference) findPreference(getString(R.string.pref_turn_passwd_key)); turnUsername.setEnabled(mPrefs.isTurnEnabled()); turnUsername.setSummary(mPrefs.getTurnUsername()); turnUsername.setText(mPrefs.getTurnUsername()); turnPassword.setEnabled(mPrefs.isTurnEnabled()); - CheckBoxPreference randomPort = (CheckBoxPreference) findPreference(getString(R.string.pref_transport_use_random_ports_key)); + CheckBoxPreference randomPort = + (CheckBoxPreference) + findPreference(getString(R.string.pref_transport_use_random_ports_key)); randomPort.setChecked(mPrefs.isUsingRandomPort()); // Disable sip port choice if port is random - EditTextPreference sipPort = (EditTextPreference) findPreference(getString(R.string.pref_sip_port_key)); + EditTextPreference sipPort = + (EditTextPreference) findPreference(getString(R.string.pref_sip_port_key)); sipPort.setEnabled(!randomPort.isChecked()); sipPort.setSummary(mPrefs.getSipPort()); sipPort.setText(mPrefs.getSipPort()); - EditTextPreference stun = (EditTextPreference) findPreference(getString(R.string.pref_stun_server_key)); + EditTextPreference stun = + (EditTextPreference) findPreference(getString(R.string.pref_stun_server_key)); stun.setSummary(mPrefs.getStunServer()); stun.setText(mPrefs.getStunServer()); - ((CheckBoxPreference) findPreference(getString(R.string.pref_push_notification_key))).setChecked(mPrefs.isPushNotificationEnabled()); - ((CheckBoxPreference) findPreference(getString(R.string.pref_ipv6_key))).setChecked(mPrefs.isUsingIpv6()); + ((CheckBoxPreference) findPreference(getString(R.string.pref_push_notification_key))) + .setChecked(mPrefs.isPushNotificationEnabled()); + ((CheckBoxPreference) findPreference(getString(R.string.pref_ipv6_key))) + .setChecked(mPrefs.isUsingIpv6()); } private void setNetworkPreferencesListener() { - findPreference(getString(R.string.pref_wifi_only_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - mPrefs.setWifiOnlyEnabled((Boolean) newValue); - return true; - } - }); + findPreference(getString(R.string.pref_wifi_only_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + mPrefs.setWifiOnlyEnabled((Boolean) newValue); + return true; + } + }); - findPreference(getString(R.string.pref_stun_server_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - mPrefs.setStunServer(newValue.toString()); - preference.setSummary(newValue.toString()); + findPreference(getString(R.string.pref_stun_server_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + mPrefs.setStunServer(newValue.toString()); + preference.setSummary(newValue.toString()); - CheckBoxPreference turn = (CheckBoxPreference) findPreference(getString(R.string.pref_turn_enable_key)); - turn.setEnabled(mPrefs.getStunServer() != null); - return true; - } - }); + CheckBoxPreference turn = + (CheckBoxPreference) + findPreference( + getString(R.string.pref_turn_enable_key)); + turn.setEnabled(mPrefs.getStunServer() != null); + return true; + } + }); - findPreference(getString(R.string.pref_ice_enable_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - mPrefs.setIceEnabled((Boolean) newValue); - return true; - } - }); + findPreference(getString(R.string.pref_ice_enable_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + mPrefs.setIceEnabled((Boolean) newValue); + return true; + } + }); - findPreference(getString(R.string.pref_turn_enable_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - mPrefs.setTurnEnabled((Boolean) newValue); - EditTextPreference turnUsername = (EditTextPreference) findPreference(getString(R.string.pref_turn_username_key)); - EditTextPreference turnPassword = (EditTextPreference) findPreference(getString(R.string.pref_turn_passwd_key)); - turnUsername.setEnabled(mPrefs.isTurnEnabled()); - turnPassword.setEnabled(mPrefs.isTurnEnabled()); - return true; - } - }); + findPreference(getString(R.string.pref_turn_enable_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + mPrefs.setTurnEnabled((Boolean) newValue); + EditTextPreference turnUsername = + (EditTextPreference) + findPreference( + getString(R.string.pref_turn_username_key)); + EditTextPreference turnPassword = + (EditTextPreference) + findPreference( + getString(R.string.pref_turn_passwd_key)); + turnUsername.setEnabled(mPrefs.isTurnEnabled()); + turnPassword.setEnabled(mPrefs.isTurnEnabled()); + return true; + } + }); - findPreference(getString(R.string.pref_turn_username_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - mPrefs.setTurnUsername((String) newValue); - preference.setSummary(mPrefs.getTurnUsername()); - return true; - } - }); + findPreference(getString(R.string.pref_turn_username_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + mPrefs.setTurnUsername((String) newValue); + preference.setSummary(mPrefs.getTurnUsername()); + return true; + } + }); - findPreference(getString(R.string.pref_turn_passwd_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - mPrefs.setTurnPassword((String) newValue); - return true; - } - }); + findPreference(getString(R.string.pref_turn_passwd_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + mPrefs.setTurnPassword((String) newValue); + return true; + } + }); - findPreference(getString(R.string.pref_upnp_enable_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - boolean value = (Boolean) newValue; - mPrefs.setUpnpEnabled(value); - return true; - } - }); + findPreference(getString(R.string.pref_upnp_enable_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + boolean value = (Boolean) newValue; + mPrefs.setUpnpEnabled(value); + return true; + } + }); - findPreference(getString(R.string.pref_transport_use_random_ports_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - boolean randomPort = (Boolean) newValue; - mPrefs.useRandomPort((Boolean) newValue); - findPreference(getString(R.string.pref_sip_port_key)).setEnabled(!randomPort); - return true; - } - }); + findPreference(getString(R.string.pref_transport_use_random_ports_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + boolean randomPort = (Boolean) newValue; + mPrefs.useRandomPort((Boolean) newValue); + findPreference(getString(R.string.pref_sip_port_key)) + .setEnabled(!randomPort); + return true; + } + }); - findPreference(getString(R.string.pref_sip_port_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - int port = -1; - try { - port = Integer.parseInt(newValue.toString()); - } catch (NumberFormatException nfe) { - } + findPreference(getString(R.string.pref_sip_port_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + int port = -1; + try { + port = Integer.parseInt(newValue.toString()); + } catch (NumberFormatException nfe) { + } - mPrefs.setSipPort(port); - preference.setSummary(newValue.toString()); - return true; - } - }); + mPrefs.setSipPort(port); + preference.setSummary(newValue.toString()); + return true; + } + }); - findPreference(getString(R.string.pref_push_notification_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - mPrefs.setPushNotificationEnabled((Boolean) newValue); - return true; - } - }); + findPreference(getString(R.string.pref_push_notification_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + mPrefs.setPushNotificationEnabled((Boolean) newValue); + return true; + } + }); - findPreference(getString(R.string.pref_ipv6_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - mPrefs.useIpv6((Boolean) newValue); - return true; - } - }); + findPreference(getString(R.string.pref_ipv6_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + mPrefs.useIpv6((Boolean) newValue); + return true; + } + }); } private void initAdvancedSettings() { - ((CheckBoxPreference) findPreference(getString(R.string.pref_friendlist_subscribe_key))).setChecked(mPrefs.isFriendlistsubscriptionEnabled()); - ((CheckBoxPreference) findPreference(getString(R.string.pref_debug_key))).setChecked(mPrefs.isDebugEnabled()); - ((CheckBoxPreference) findPreference(getString(R.string.pref_java_debug_key))).setChecked(mPrefs.useJavaLogger()); - ((CheckBoxPreference) findPreference(getString(R.string.pref_background_mode_key))).setChecked(mPrefs.isBackgroundModeEnabled()); - ((CheckBoxPreference) findPreference(getString(R.string.pref_service_notification_key))).setChecked(mPrefs.getServiceNotificationVisibility()); - ((CheckBoxPreference) findPreference(getString(R.string.pref_autostart_key))).setChecked(mPrefs.isAutoStartEnabled()); - setPreferenceDefaultValueAndSummary(R.string.pref_remote_provisioning_key, mPrefs.getRemoteProvisioningUrl()); - setPreferenceDefaultValueAndSummary(R.string.pref_display_name_key, mPrefs.getDefaultDisplayName()); - setPreferenceDefaultValueAndSummary(R.string.pref_user_name_key, mPrefs.getDefaultUsername()); + ((CheckBoxPreference) findPreference(getString(R.string.pref_friendlist_subscribe_key))) + .setChecked(mPrefs.isFriendlistsubscriptionEnabled()); + ((CheckBoxPreference) findPreference(getString(R.string.pref_debug_key))) + .setChecked(mPrefs.isDebugEnabled()); + ((CheckBoxPreference) findPreference(getString(R.string.pref_java_debug_key))) + .setChecked(mPrefs.useJavaLogger()); + ((CheckBoxPreference) findPreference(getString(R.string.pref_background_mode_key))) + .setChecked(mPrefs.isBackgroundModeEnabled()); + ((CheckBoxPreference) findPreference(getString(R.string.pref_service_notification_key))) + .setChecked(mPrefs.getServiceNotificationVisibility()); + ((CheckBoxPreference) findPreference(getString(R.string.pref_autostart_key))) + .setChecked(mPrefs.isAutoStartEnabled()); + setPreferenceDefaultValueAndSummary( + R.string.pref_remote_provisioning_key, mPrefs.getRemoteProvisioningUrl()); + setPreferenceDefaultValueAndSummary( + R.string.pref_display_name_key, mPrefs.getDefaultDisplayName()); + setPreferenceDefaultValueAndSummary( + R.string.pref_user_name_key, mPrefs.getDefaultUsername()); } private void setAdvancedPreferencesListener() { - findPreference(getString(R.string.pref_friendlist_subscribe_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - boolean value = (Boolean) newValue; - mPrefs.enabledFriendlistSubscription(value); - LinphoneManager.getInstance().subscribeFriendList(value); - return true; - } - }); + findPreference(getString(R.string.pref_friendlist_subscribe_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + boolean value = (Boolean) newValue; + mPrefs.enabledFriendlistSubscription(value); + LinphoneManager.getInstance().subscribeFriendList(value); + return true; + } + }); - findPreference(getString(R.string.pref_debug_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - boolean value = (Boolean) newValue; - mPrefs.setDebugEnabled(value); - return true; - } - }); + findPreference(getString(R.string.pref_debug_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + boolean value = (Boolean) newValue; + mPrefs.setDebugEnabled(value); + return true; + } + }); - findPreference(getString(R.string.pref_java_debug_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - boolean value = (Boolean) newValue; - mPrefs.setJavaLogger(value); - return true; - } - }); + findPreference(getString(R.string.pref_java_debug_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + boolean value = (Boolean) newValue; + mPrefs.setJavaLogger(value); + return true; + } + }); - findPreference(getString(R.string.pref_background_mode_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - boolean value = (Boolean) newValue; - mPrefs.setBackgroundModeEnabled(value); - return true; - } - }); + findPreference(getString(R.string.pref_background_mode_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + boolean value = (Boolean) newValue; + mPrefs.setBackgroundModeEnabled(value); + return true; + } + }); - findPreference(getString(R.string.pref_service_notification_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - boolean value = (Boolean) newValue; - mPrefs.setServiceNotificationVisibility(value); - if (value) { - LinphoneService.instance().getNotificationManager().startForeground(); - } else { - LinphoneService.instance().getNotificationManager().stopForeground(); - } - return true; - } - }); + findPreference(getString(R.string.pref_service_notification_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + boolean value = (Boolean) newValue; + mPrefs.setServiceNotificationVisibility(value); + if (value) { + LinphoneService.instance() + .getNotificationManager() + .startForeground(); + } else { + LinphoneService.instance() + .getNotificationManager() + .stopForeground(); + } + return true; + } + }); - findPreference(getString(R.string.pref_autostart_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - boolean value = (Boolean) newValue; - mPrefs.setAutoStart(value); - return true; - } - }); + findPreference(getString(R.string.pref_autostart_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + boolean value = (Boolean) newValue; + mPrefs.setAutoStart(value); + return true; + } + }); - findPreference(getString(R.string.pref_remote_provisioning_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - String value = (String) newValue; - mPrefs.setRemoteProvisioningUrl(value); - preference.setSummary(value); - return true; - } - }); + findPreference(getString(R.string.pref_remote_provisioning_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + String value = (String) newValue; + mPrefs.setRemoteProvisioningUrl(value); + preference.setSummary(value); + return true; + } + }); - findPreference(getString(R.string.pref_android_app_settings_key)).setOnPreferenceClickListener(new OnPreferenceClickListener() { - @Override - public boolean onPreferenceClick(Preference preference) { - synchronized (SettingsFragment.this) { - Context context = SettingsFragment.this.getActivity(); - Intent i = new Intent(); - i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); - i.addCategory(Intent.CATEGORY_DEFAULT); - i.setData(Uri.parse("package:" + context.getPackageName())); - 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; - } - }); + findPreference(getString(R.string.pref_android_app_settings_key)) + .setOnPreferenceClickListener( + new OnPreferenceClickListener() { + @Override + public boolean onPreferenceClick(Preference preference) { + synchronized (SettingsFragment.this) { + Context context = SettingsFragment.this.getActivity(); + Intent i = new Intent(); + i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); + i.addCategory(Intent.CATEGORY_DEFAULT); + i.setData(Uri.parse("package:" + context.getPackageName())); + 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; + } + }); - findPreference(getString(R.string.pref_display_name_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - String value = (String) newValue; - mPrefs.setDefaultDisplayName(value); - preference.setSummary(value); - return true; - } - }); + findPreference(getString(R.string.pref_display_name_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + String value = (String) newValue; + mPrefs.setDefaultDisplayName(value); + preference.setSummary(value); + return true; + } + }); - findPreference(getString(R.string.pref_user_name_key)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - String value = (String) newValue; - if (value.equals("")) return false; + findPreference(getString(R.string.pref_user_name_key)) + .setOnPreferenceChangeListener( + new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange( + Preference preference, Object newValue) { + String value = (String) newValue; + if (value.equals("")) return false; - mPrefs.setDefaultUsername(value); - preference.setSummary(value); - return true; - } - }); + mPrefs.setDefaultUsername(value); + preference.setSummary(value); + return true; + } + }); } @Override @@ -1489,8 +1844,7 @@ public class SettingsFragment extends PreferencesListFragment { @Override public void onPause() { if (LinphoneActivity.isInstanciated() && LinphoneManager.isInstanciated()) { - if (LinphoneManager.getInstance().getEchoTesterStatus()) - stopEchoTester(); + if (LinphoneManager.getInstance().getEchoTesterStatus()) stopEchoTester(); LinphoneActivity.instance().hideTopBar(); } super.onPause(); diff --git a/app/src/main/java/org/linphone/sync/AuthenticationService.java b/app/src/main/java/org/linphone/sync/AuthenticationService.java index ca791026d..6bb0eb778 100644 --- a/app/src/main/java/org/linphone/sync/AuthenticationService.java +++ b/app/src/main/java/org/linphone/sync/AuthenticationService.java @@ -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. */ - import android.app.Service; import android.content.Intent; import android.os.IBinder; @@ -37,4 +36,4 @@ public class AuthenticationService extends Service { public IBinder onBind(Intent intent) { return mAuthenticator.getIBinder(); } -} \ No newline at end of file +} diff --git a/app/src/main/java/org/linphone/sync/Authenticator.java b/app/src/main/java/org/linphone/sync/Authenticator.java index c5b9cfb53..56c082d3a 100644 --- a/app/src/main/java/org/linphone/sync/Authenticator.java +++ b/app/src/main/java/org/linphone/sync/Authenticator.java @@ -33,35 +33,27 @@ public class Authenticator extends AbstractAccountAuthenticator { } @Override - public Bundle editProperties( - AccountAuthenticatorResponse r, String s) { + public Bundle editProperties(AccountAuthenticatorResponse r, String s) { throw new UnsupportedOperationException(); } @Override public Bundle addAccount( - AccountAuthenticatorResponse r, - String s, - String s2, - String[] strings, - Bundle bundle) throws NetworkErrorException { + AccountAuthenticatorResponse r, String s, String s2, String[] strings, Bundle bundle) + throws NetworkErrorException { return null; } @Override - public Bundle confirmCredentials( - AccountAuthenticatorResponse r, - Account account, - Bundle bundle) throws NetworkErrorException { + public Bundle confirmCredentials(AccountAuthenticatorResponse r, Account account, Bundle bundle) + throws NetworkErrorException { return null; } @Override public Bundle getAuthToken( - AccountAuthenticatorResponse r, - Account account, - String s, - Bundle bundle) throws NetworkErrorException { + AccountAuthenticatorResponse r, Account account, String s, Bundle bundle) + throws NetworkErrorException { throw new UnsupportedOperationException(); } @@ -72,16 +64,14 @@ public class Authenticator extends AbstractAccountAuthenticator { @Override public Bundle updateCredentials( - AccountAuthenticatorResponse r, - Account account, - String s, Bundle bundle) throws NetworkErrorException { + AccountAuthenticatorResponse r, Account account, String s, Bundle bundle) + throws NetworkErrorException { throw new UnsupportedOperationException(); } @Override - public Bundle hasFeatures( - AccountAuthenticatorResponse r, - Account account, String[] strings) throws NetworkErrorException { + public Bundle hasFeatures(AccountAuthenticatorResponse r, Account account, String[] strings) + throws NetworkErrorException { throw new UnsupportedOperationException(); } -} \ No newline at end of file +} diff --git a/app/src/main/java/org/linphone/sync/SyncAdapter.java b/app/src/main/java/org/linphone/sync/SyncAdapter.java index cb18046b9..50509eb45 100755 --- a/app/src/main/java/org/linphone/sync/SyncAdapter.java +++ b/app/src/main/java/org/linphone/sync/SyncAdapter.java @@ -33,8 +33,10 @@ public class SyncAdapter extends AbstractThreadedSyncAdapter { } @Override - public void onPerformSync(Account account, Bundle extras, String authority, - ContentProviderClient provider, SyncResult syncResult) { - } + public void onPerformSync( + Account account, + Bundle extras, + String authority, + ContentProviderClient provider, + SyncResult syncResult) {} } - diff --git a/app/src/main/java/org/linphone/sync/SyncService.java b/app/src/main/java/org/linphone/sync/SyncService.java index 483297a5f..b3d6e7ddc 100755 --- a/app/src/main/java/org/linphone/sync/SyncService.java +++ b/app/src/main/java/org/linphone/sync/SyncService.java @@ -19,14 +19,13 @@ along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ - import android.app.Service; import android.content.Intent; import android.os.IBinder; public class SyncService extends Service { - private static SyncAdapter sSyncAdapter = null; private static final Object sSyncAdapterLock = new Object(); + private static SyncAdapter sSyncAdapter = null; @Override public void onCreate() { diff --git a/app/src/main/java/org/linphone/utils/FileUtils.java b/app/src/main/java/org/linphone/utils/FileUtils.java index 4ec2eeafc..d2c83f829 100644 --- a/app/src/main/java/org/linphone/utils/FileUtils.java +++ b/app/src/main/java/org/linphone/utils/FileUtils.java @@ -27,15 +27,6 @@ import android.os.Environment; import android.provider.MediaStore; import android.provider.OpenableColumns; import android.text.TextUtils; - -import org.linphone.LinphoneManager; -import org.linphone.core.Address; -import org.linphone.core.ChatMessage; -import org.linphone.core.Content; -import org.linphone.core.Friend; -import org.linphone.core.FriendList; -import org.linphone.mediastream.Log; - import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; @@ -46,6 +37,13 @@ import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; +import org.linphone.LinphoneManager; +import org.linphone.core.Address; +import org.linphone.core.ChatMessage; +import org.linphone.core.Content; +import org.linphone.core.Friend; +import org.linphone.core.FriendList; +import org.linphone.mediastream.Log; public class FileUtils { public static String getNameFromFilePath(String filePath) { @@ -68,8 +66,7 @@ public class FileUtils { public static Boolean isExtensionImage(String path) { String extension = getExtensionFromFileName(path); - if (extension != null) - extension = extension.toLowerCase(); + if (extension != null) extension = extension.toLowerCase(); return (extension != null && extension.matches("(png|jpg|jpeg|bmp|gif)")); } @@ -85,6 +82,7 @@ public class FileUtils { } } } + public static String getFilePath(final Context context, final Uri uri) { if (uri == null) return null; @@ -124,8 +122,7 @@ public class FileUtils { } /** - * Copy data from a source stream to destFile. - * Return true if succeed, return false if failed. + * Copy data from a source stream to destFile. Return true if succeed, return false if failed. */ private static boolean copyToFile(InputStream inputStream, File destFile) { if (inputStream == null || destFile == null) return false; @@ -147,8 +144,7 @@ public class FileUtils { } public static File createFile(Context context, String fileName) throws IOException { - if (TextUtils.isEmpty(fileName)) - fileName = getStartDate(); + if (TextUtils.isEmpty(fileName)) fileName = getStartDate(); if (!fileName.contains(".")) { fileName = fileName + ".unknown"; @@ -157,8 +153,7 @@ public class FileUtils { final File root; root = context.getExternalCacheDir(); - if (root != null && !root.exists()) - root.mkdirs(); + if (root != null && !root.exists()) root.mkdirs(); return new File(root, fileName); } @@ -190,7 +185,13 @@ public class FileUtils { } public static String getStorageDirectory(Context mContext) { - String storageDir = Environment.getExternalStorageDirectory() + "/" + mContext.getString(mContext.getResources().getIdentifier("app_name", "string", mContext.getPackageName())); + String storageDir = + Environment.getExternalStorageDirectory() + + "/" + + mContext.getString( + mContext.getResources() + .getIdentifier( + "app_name", "string", mContext.getPackageName())); File file = new File(storageDir); if (!file.isDirectory() || !file.exists()) { Log.w("Directory " + file + " doesn't seem to exists yet, let's create it"); @@ -201,12 +202,19 @@ public class FileUtils { } public static String getRecordingsDirectory(Context mContext) { - String recordingsDir = Environment.getExternalStorageDirectory() + "/" + mContext.getString(mContext.getResources().getIdentifier("app_name", "string", mContext.getPackageName())) + "/recordings"; + String recordingsDir = + Environment.getExternalStorageDirectory() + + "/" + + mContext.getString( + mContext.getResources() + .getIdentifier( + "app_name", "string", mContext.getPackageName())) + + "/recordings"; File file = new File(recordingsDir); if (!file.isDirectory() || !file.exists()) { Log.w("Directory " + file + " doesn't seem to exists yet, let's create it"); file.mkdirs(); - LinphoneManager.getInstance().getMediaScanner().scanFile(file); + LinphoneManager.getInstance().getMediaScanner().scanFile(file, null); } return recordingsDir; } @@ -215,7 +223,8 @@ public class FileUtils { public static String getCallRecordingFilename(Context context, Address address) { String fileName = getRecordingsDirectory(context) + "/"; - String name = address.getDisplayName() == null ? address.getUsername() : address.getDisplayName(); + String name = + address.getDisplayName() == null ? address.getUsername() : address.getDisplayName(); fileName += name + "_"; DateFormat format = new SimpleDateFormat("dd-MM-yyyy-HH-mm-ss"); diff --git a/app/src/main/java/org/linphone/utils/ImageUtils.java b/app/src/main/java/org/linphone/utils/ImageUtils.java index 10f0919fa..bde3c7488 100644 --- a/app/src/main/java/org/linphone/utils/ImageUtils.java +++ b/app/src/main/java/org/linphone/utils/ImageUtils.java @@ -20,7 +20,6 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import android.content.Context; -import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; @@ -33,15 +32,13 @@ import android.provider.MediaStore; import android.util.DisplayMetrics; import android.util.TypedValue; import android.widget.ImageView; - -import org.linphone.R; -import org.linphone.contacts.ContactsManager; -import org.linphone.mediastream.Log; - import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; +import org.linphone.R; +import org.linphone.contacts.ContactsManager; +import org.linphone.mediastream.Log; public class ImageUtils { @@ -65,8 +62,8 @@ public class ImageUtils { return null; } - - public static void setImagePictureFromUri(Context c, ImageView view, Uri pictureUri, Uri thumbnailUri) { + public static void setImagePictureFromUri( + Context c, ImageView view, Uri pictureUri, Uri thumbnailUri) { if (pictureUri == null && thumbnailUri == null) { view.setImageBitmap(ContactsManager.getInstance().getDefaultAvatarBitmap()); return; @@ -82,7 +79,9 @@ public class ImageUtils { } catch (IOException e) { if (thumbnailUri != null) { try { - bm = MediaStore.Images.Media.getBitmap(c.getContentResolver(), thumbnailUri); + bm = + MediaStore.Images.Media.getBitmap( + c.getContentResolver(), thumbnailUri); } catch (IOException ie) { } } @@ -100,7 +99,9 @@ public class ImageUtils { Bitmap roundBm; if (fromPictureUri != null) { try { - bm = MediaStore.Images.Media.getBitmap(context.getContentResolver(), fromPictureUri); + bm = + MediaStore.Images.Media.getBitmap( + context.getContentResolver(), fromPictureUri); } catch (Exception e) { bm = BitmapFactory.decodeResource(context.getResources(), R.drawable.topbar_avatar); } @@ -118,7 +119,8 @@ public class ImageUtils { } public static Bitmap getRoundBitmap(Bitmap bitmap) { - Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); + Bitmap output = + Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(output); final int color = 0xff424242; @@ -128,7 +130,8 @@ public class ImageUtils { paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(color); - canvas.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2, bitmap.getWidth() / 2, paint); + canvas.drawCircle( + bitmap.getWidth() / 2, bitmap.getHeight() / 2, bitmap.getWidth() / 2, paint); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect, rect, paint); @@ -136,10 +139,13 @@ public class ImageUtils { } public static float dpToPixels(Context context, float dp) { - return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources().getDisplayMetrics()); + return TypedValue.applyDimension( + TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources().getDisplayMetrics()); } public static float pixelsToDp(Context context, float pixels) { - return pixels / ((float) context.getResources().getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT); + return pixels + / ((float) context.getResources().getDisplayMetrics().densityDpi + / DisplayMetrics.DENSITY_DEFAULT); } } diff --git a/app/src/main/java/org/linphone/utils/LinphoneGenericActivity.java b/app/src/main/java/org/linphone/utils/LinphoneGenericActivity.java index 792b9eddf..0d185d805 100644 --- a/app/src/main/java/org/linphone/utils/LinphoneGenericActivity.java +++ b/app/src/main/java/org/linphone/utils/LinphoneGenericActivity.java @@ -21,10 +21,9 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import android.app.Activity; import android.os.Bundle; - +import org.linphone.LinphoneLauncherActivity; import org.linphone.LinphoneManager; import org.linphone.LinphoneService; -import org.linphone.LinphoneLauncherActivity; public class LinphoneGenericActivity extends Activity { diff --git a/app/src/main/java/org/linphone/utils/LinphoneMediaScanner.java b/app/src/main/java/org/linphone/utils/LinphoneMediaScanner.java index 5d59e4587..f8943217c 100644 --- a/app/src/main/java/org/linphone/utils/LinphoneMediaScanner.java +++ b/app/src/main/java/org/linphone/utils/LinphoneMediaScanner.java @@ -3,10 +3,8 @@ package org.linphone.utils; import android.content.Context; import android.media.MediaScannerConnection; import android.net.Uri; - -import org.linphone.mediastream.Log; - import java.io.File; +import org.linphone.mediastream.Log; public class LinphoneMediaScanner implements MediaScannerConnection.MediaScannerConnectionClient { private MediaScannerConnection mMediaConnection; @@ -61,4 +59,4 @@ public class LinphoneMediaScanner implements MediaScannerConnection.MediaScanner mMediaConnection.disconnect(); mIsConnected = false; } -} \ No newline at end of file +} diff --git a/app/src/main/java/org/linphone/utils/LinphoneUtils.java b/app/src/main/java/org/linphone/utils/LinphoneUtils.java index 5740b2f05..b2aab57f0 100644 --- a/app/src/main/java/org/linphone/utils/LinphoneUtils.java +++ b/app/src/main/java/org/linphone/utils/LinphoneUtils.java @@ -38,7 +38,13 @@ import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.TextView; - +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Collection; +import java.util.List; +import java.util.Locale; +import java.util.regex.Pattern; import org.linphone.LinphoneManager; import org.linphone.LinphoneService; import org.linphone.R; @@ -57,29 +63,19 @@ import org.linphone.mediastream.Log; import org.linphone.mediastream.video.capture.hwconf.Hacks; import org.linphone.settings.LinphonePreferences; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collection; -import java.util.List; -import java.util.Locale; -import java.util.regex.Pattern; - -/** - * Helpers. - */ +/** Helpers. */ public final class LinphoneUtils { private static Context context = null; private static Handler mHandler = new Handler(Looper.getMainLooper()); - private LinphoneUtils() { - - } + private LinphoneUtils() {} public static String getDeviceName(Context context) { String name = null; if (Build.VERSION.SDK_INT > 17) { - name = Settings.Global.getString(context.getContentResolver(), Settings.Global.DEVICE_NAME); + name = + Settings.Global.getString( + context.getContentResolver(), Settings.Global.DEVICE_NAME); } if (name == null) { name = BluetoothAdapter.getDefaultAdapter().getName(); @@ -99,30 +95,38 @@ public final class LinphoneUtils { Factory.instance().setDebugMode(isDebugEnabled, appName); } else { Factory.instance().setDebugMode(isDebugEnabled, appName); - Factory.instance().enableLogCollection(LogCollectionState.EnabledWithoutPreviousLogHandler); - Factory.instance().getLoggingService().setListener(new LoggingServiceListener() { - @Override - public void onLogMessageWritten(LoggingService logService, String domain, LogLevel lev, String message) { - switch (lev) { - case Debug: - android.util.Log.d(domain, message); - break; - case Message: - android.util.Log.i(domain, message); - break; - case Warning: - android.util.Log.w(domain, message); - break; - case Error: - android.util.Log.e(domain, message); - break; - case Fatal: - default: - android.util.Log.wtf(domain, message); - break; - } - } - }); + Factory.instance() + .enableLogCollection(LogCollectionState.EnabledWithoutPreviousLogHandler); + Factory.instance() + .getLoggingService() + .setListener( + new LoggingServiceListener() { + @Override + public void onLogMessageWritten( + LoggingService logService, + String domain, + LogLevel lev, + String message) { + switch (lev) { + case Debug: + android.util.Log.d(domain, message); + break; + case Message: + android.util.Log.i(domain, message); + break; + case Warning: + android.util.Log.w(domain, message); + break; + case Error: + android.util.Log.e(domain, message); + break; + case Fatal: + default: + android.util.Log.wtf(domain, message); + break; + } + } + }); } } @@ -130,8 +134,10 @@ public final class LinphoneUtils { mHandler.post(r); } - //private static final String sipAddressRegExp = "^(sip:)?(\\+)?[a-z0-9]+([_\\.-][a-z0-9]+)*@([a-z0-9]+([\\.-][a-z0-9]+)*)+\\.[a-z]{2,}(:[0-9]{2,5})?$"; - //private static final String strictSipAddressRegExp = "^sip:(\\+)?[a-z0-9]+([_\\.-][a-z0-9]+)*@([a-z0-9]+([\\.-][a-z0-9]+)*)+\\.[a-z]{2,}$"; + // private static final String sipAddressRegExp = + // "^(sip:)?(\\+)?[a-z0-9]+([_\\.-][a-z0-9]+)*@([a-z0-9]+([\\.-][a-z0-9]+)*)+\\.[a-z]{2,}(:[0-9]{2,5})?$"; + // private static final String strictSipAddressRegExp = + // "^sip:(\\+)?[a-z0-9]+([_\\.-][a-z0-9]+)*@([a-z0-9]+([\\.-][a-z0-9]+)*)+\\.[a-z]{2,}$"; public static boolean isSipAddress(String numberOrAddress) { Factory.instance().createAddress(numberOrAddress); @@ -167,11 +173,9 @@ public final class LinphoneUtils { } public static String getUsernameFromAddress(String address) { - if (address.contains("sip:")) - address = address.replace("sip:", ""); + if (address.contains("sip:")) address = address.replace("sip:", ""); - if (address.contains("@")) - address = address.split("@")[0]; + if (address.contains("@")) address = address.split("@")[0]; return address; } @@ -181,9 +185,8 @@ public final class LinphoneUtils { return false; // continue } - activity.startActivity(new Intent() - .setAction(Intent.ACTION_MAIN) - .addCategory(Intent.CATEGORY_HOME)); + activity.startActivity( + new Intent().setAction(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME)); return true; } @@ -198,7 +201,10 @@ public final class LinphoneUtils { SimpleDateFormat dateFormat; if (isToday(cal)) { - dateFormat = new SimpleDateFormat(context.getResources().getString(R.string.today_date_format), Locale.getDefault()); + dateFormat = + new SimpleDateFormat( + context.getResources().getString(R.string.today_date_format), + Locale.getDefault()); } else { dateFormat = new SimpleDateFormat(format, Locale.getDefault()); } @@ -218,14 +224,15 @@ public final class LinphoneUtils { return false; } - return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) && - cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && - cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR)); + return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) + && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) + && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR)); } public static boolean onKeyVolumeAdjust(int keyCode) { if (!((keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) - && (Hacks.needSoftvolume()) || Build.VERSION.SDK_INT >= 15)) { + && (Hacks.needSoftvolume()) + || Build.VERSION.SDK_INT >= 15)) { return false; // continue } @@ -257,11 +264,11 @@ public final class LinphoneUtils { Call.State state = call.getState(); - return state == Call.State.Connected || - state == Call.State.Updating || - state == Call.State.UpdatedByRemote || - state == Call.State.StreamsRunning || - state == Call.State.Resuming; + return state == Call.State.Connected + || state == Call.State.Updating + || state == Call.State.UpdatedByRemote + || state == Call.State.StreamsRunning + || state == Call.State.Resuming; } public static boolean isCallEstablished(Call call) { @@ -271,16 +278,19 @@ public final class LinphoneUtils { Call.State state = call.getState(); - return isCallRunning(call) || - state == Call.State.Paused || - state == Call.State.PausedByRemote || - state == Call.State.Pausing; + return isCallRunning(call) + || state == Call.State.Paused + || state == Call.State.PausedByRemote + || state == Call.State.Pausing; } public static boolean isHighBandwidthConnection(Context context) { - ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); + ConnectivityManager cm = + (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = cm.getActiveNetworkInfo(); - return (info != null && info.isConnected() && isConnectionFast(info.getType(), info.getSubtype())); + return (info != null + && info.isConnected() + && isConnectionFast(info.getType(), info.getSubtype())); } private static boolean isConnectionFast(int type, int subType) { @@ -292,7 +302,7 @@ public final class LinphoneUtils { return false; } } - //in doubt, assume connection is good. + // in doubt, assume connection is good. return true; } @@ -313,7 +323,10 @@ public final class LinphoneUtils { return username.split("@")[0]; } } else { - if (domain.equals(LinphoneManager.getInstance().getContext().getString(R.string.default_domain))) { + if (domain.equals( + LinphoneManager.getInstance() + .getContext() + .getString(R.string.default_domain))) { return username.split("@")[0]; } } @@ -335,7 +348,12 @@ public final class LinphoneUtils { if (lpc != null) { sipAddress = sipAddress + "@" + lpc.getDomain(); } else { - sipAddress = sipAddress + "@" + LinphoneManager.getInstance().getContext().getString(R.string.default_domain); + sipAddress = + sipAddress + + "@" + + LinphoneManager.getInstance() + .getContext() + .getString(R.string.default_domain); } } return sipAddress; @@ -430,8 +448,7 @@ public final class LinphoneUtils { || status.equals(AccountCreator.Status.AccountAlreadyActivated) || status.equals(AccountCreator.Status.AccountActivated) || status.equals(AccountCreator.Status.AccountNotCreated) - || status.equals(AccountCreator.Status.RequestOk)) - return ""; + || status.equals(AccountCreator.Status.RequestOk)) return ""; } return null; } @@ -471,24 +488,37 @@ public final class LinphoneUtils { } if (text.contains("http://")) { int indexHttp = text.indexOf("http://"); - int indexFinHttp = text.indexOf(" ", indexHttp) == -1 ? text.length() : text.indexOf(" ", indexHttp); + int indexFinHttp = + text.indexOf(" ", indexHttp) == -1 + ? text.length() + : text.indexOf(" ", indexHttp); String link = text.substring(indexHttp, indexFinHttp); String linkWithoutScheme = link.replace("http://", ""); - text = text.replaceFirst(Pattern.quote(link), "" + linkWithoutScheme + ""); + text = + text.replaceFirst( + Pattern.quote(link), + "" + linkWithoutScheme + ""); } if (text.contains("https://")) { int indexHttp = text.indexOf("https://"); - int indexFinHttp = text.indexOf(" ", indexHttp) == -1 ? text.length() : text.indexOf(" ", indexHttp); + int indexFinHttp = + text.indexOf(" ", indexHttp) == -1 + ? text.length() + : text.indexOf(" ", indexHttp); String link = text.substring(indexHttp, indexFinHttp); String linkWithoutScheme = link.replace("https://", ""); - text = text.replaceFirst(Pattern.quote(link), "" + linkWithoutScheme + ""); + text = + text.replaceFirst( + Pattern.quote(link), + "" + linkWithoutScheme + ""); } return Html.fromHtml(text); } public static void hideKeyboard(Activity activity) { - InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE); + InputMethodManager imm = + (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE); View view = activity.getCurrentFocus(); if (view == null) { view = new View(activity); @@ -502,4 +532,3 @@ public final class LinphoneUtils { return context; } } - diff --git a/app/src/main/java/org/linphone/utils/SelectableAdapter.java b/app/src/main/java/org/linphone/utils/SelectableAdapter.java index 505c7547f..f5da92301 100644 --- a/app/src/main/java/org/linphone/utils/SelectableAdapter.java +++ b/app/src/main/java/org/linphone/utils/SelectableAdapter.java @@ -1,31 +1,31 @@ package org.linphone.utils; /* - SelectableAdapter.java - Copyright (C) 2018 Belledonne Communications, Grenoble, France +SelectableAdapter.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 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. +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. - */ +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 androidx.recyclerview.widget.RecyclerView; import android.util.SparseBooleanArray; - +import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; import java.util.List; -public abstract class SelectableAdapter extends RecyclerView.Adapter { +public abstract class SelectableAdapter + extends RecyclerView.Adapter { private SparseBooleanArray mSelectedItems; private boolean mIsEditionEnabled = false; private SelectableHelper mListHelper; @@ -67,7 +67,8 @@ public abstract class SelectableAdapter exte } else { mSelectedItems.put(position, true); } - mListHelper.updateSelectionButtons(getSelectedItemCount() == 0, getSelectedItemCount() == getItemCount()); + mListHelper.updateSelectionButtons( + getSelectedItemCount() == 0, getSelectedItemCount() == getItemCount()); notifyItemChanged(position); } diff --git a/app/src/main/java/org/linphone/utils/SelectableHelper.java b/app/src/main/java/org/linphone/utils/SelectableHelper.java index 518c76d3f..85c3281cb 100644 --- a/app/src/main/java/org/linphone/utils/SelectableHelper.java +++ b/app/src/main/java/org/linphone/utils/SelectableHelper.java @@ -21,31 +21,26 @@ package org.linphone.utils; import android.app.Dialog; import android.content.Context; -import androidx.recyclerview.widget.RecyclerView; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; - -import org.linphone.R; +import androidx.recyclerview.widget.RecyclerView; import org.linphone.LinphoneActivity; +import org.linphone.R; public class SelectableHelper { - private ImageView mEditButton, mSelectAllButton, mDeselectAllButton, mDeleteSelectionButton, mCancelButton; + private ImageView mEditButton, + mSelectAllButton, + mDeselectAllButton, + mDeleteSelectionButton, + mCancelButton; private LinearLayout mEditTopBar, mTopBar; private SelectableAdapter mAdapter; private DeleteListener mDeleteListener; private Context mContext; private int mDialogDeleteMessageResourceId; - public void setDialogMessage(int id) { - mDialogDeleteMessageResourceId = id; - } - - public interface DeleteListener { - void onDeleteSelection(Object[] objectsToDelete); - } - public SelectableHelper(View view, DeleteListener listener) { mContext = view.getContext(); mDeleteListener = listener; @@ -54,86 +49,100 @@ public class SelectableHelper { mTopBar = view.findViewById(R.id.top_bar); mCancelButton = view.findViewById(R.id.cancel); - mCancelButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - quitEditionMode(); - } - }); + mCancelButton.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View v) { + quitEditionMode(); + } + }); mEditButton = view.findViewById(R.id.edit); mEditButton.setEnabled(false); - mEditButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (mAdapter.getItemCount() > 0) { - enterEditionMode(); - mTopBar.setVisibility(View.GONE); - mEditTopBar.setVisibility(View.VISIBLE); - } - } - }); + mEditButton.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View v) { + if (mAdapter.getItemCount() > 0) { + enterEditionMode(); + mTopBar.setVisibility(View.GONE); + mEditTopBar.setVisibility(View.VISIBLE); + } + } + }); mSelectAllButton = view.findViewById(R.id.select_all); - mSelectAllButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - mAdapter.selectAll(); - } - }); + mSelectAllButton.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View v) { + mAdapter.selectAll(); + } + }); mDeselectAllButton = view.findViewById(R.id.deselect_all); - mDeselectAllButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - mAdapter.deselectAll(); - } - }); + mDeselectAllButton.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View v) { + mAdapter.deselectAll(); + } + }); mDeleteSelectionButton = view.findViewById(R.id.delete); mDeleteSelectionButton.setEnabled(false); - mDeleteSelectionButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - final Dialog dialog = LinphoneActivity.instance().displayDialog(mContext.getString(mDialogDeleteMessageResourceId)); - Button delete = dialog.findViewById(R.id.dialog_delete_button); - Button cancel = dialog.findViewById(R.id.dialog_cancel_button); - - delete.setOnClickListener(new View.OnClickListener() { + mDeleteSelectionButton.setOnClickListener( + new View.OnClickListener() { @Override - public void onClick(View view) { - mDeleteListener.onDeleteSelection(getSelectedObjects()); - mEditButton.setEnabled(mAdapter.getItemCount() != 0); - dialog.dismiss(); - quitEditionMode(); + public void onClick(View v) { + final Dialog dialog = + LinphoneActivity.instance() + .displayDialog( + mContext.getString(mDialogDeleteMessageResourceId)); + Button delete = dialog.findViewById(R.id.dialog_delete_button); + Button cancel = dialog.findViewById(R.id.dialog_cancel_button); + + delete.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View view) { + mDeleteListener.onDeleteSelection(getSelectedObjects()); + mEditButton.setEnabled(mAdapter.getItemCount() != 0); + dialog.dismiss(); + quitEditionMode(); + } + }); + + cancel.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View view) { + dialog.dismiss(); + quitEditionMode(); + } + }); + dialog.show(); } }); - cancel.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - dialog.dismiss(); - quitEditionMode(); - } - }); - dialog.show(); - } - }); - mDialogDeleteMessageResourceId = R.string.delete_text; } + public void setDialogMessage(int id) { + mDialogDeleteMessageResourceId = id; + } + + public SelectableAdapter getAdapter() { + return mAdapter; + } + public void setAdapter(SelectableAdapter adapter) { mAdapter = adapter; mEditButton.setEnabled(mAdapter.getItemCount() != 0); } - public SelectableAdapter getAdapter() { - return mAdapter; - } - public void updateSelectionButtons(boolean isSelectionEmpty, boolean isSelectionFull) { if (isSelectionEmpty) { mDeleteSelectionButton.setEnabled(false); @@ -177,4 +186,8 @@ public class SelectableHelper { } return objects; } + + public interface DeleteListener { + void onDeleteSelection(Object[] objectsToDelete); + } } diff --git a/app/src/main/java/org/linphone/views/AddressText.java b/app/src/main/java/org/linphone/views/AddressText.java index 09c46db55..e50e5f4b6 100644 --- a/app/src/main/java/org/linphone/views/AddressText.java +++ b/app/src/main/java/org/linphone/views/AddressText.java @@ -25,7 +25,6 @@ import android.graphics.Paint; import android.util.AttributeSet; import android.util.TypedValue; import android.widget.EditText; - import org.linphone.LinphoneManager.AddressType; import org.linphone.R; import org.linphone.fragments.DialerFragment; @@ -65,8 +64,7 @@ public class AddressText extends EditText implements AddressType { } @Override - protected void onTextChanged(CharSequence text, int start, int before, - int after) { + protected void onTextChanged(CharSequence text, int start, int before, int after) { clearDisplayedName(); refitText(getWidth(), getHeight()); @@ -114,8 +112,7 @@ public class AddressText extends EditText implements AddressType { float size = getOptimizedTextSize(getHintText(), textWidth, textHeight); float entrySize = getOptimizedTextSize(getText().toString(), textWidth, textHeight); - if (entrySize < size) - size = entrySize; + if (entrySize < size) size = entrySize; setTextSize(TypedValue.COMPLEX_UNIT_PX, size); } diff --git a/app/src/main/java/org/linphone/views/AsyncBitmap.java b/app/src/main/java/org/linphone/views/AsyncBitmap.java index bc66446f9..b195cd485 100644 --- a/app/src/main/java/org/linphone/views/AsyncBitmap.java +++ b/app/src/main/java/org/linphone/views/AsyncBitmap.java @@ -22,7 +22,6 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; - import java.lang.ref.WeakReference; public class AsyncBitmap extends BitmapDrawable { @@ -36,4 +35,4 @@ public class AsyncBitmap extends BitmapDrawable { public BitmapWorkerTask getBitmapWorkerTask() { return bitmapWorkerTaskReference.get(); } -} \ No newline at end of file +} diff --git a/app/src/main/java/org/linphone/views/BitmapWorkerTask.java b/app/src/main/java/org/linphone/views/BitmapWorkerTask.java index 5ba532a21..902f441d4 100644 --- a/app/src/main/java/org/linphone/views/BitmapWorkerTask.java +++ b/app/src/main/java/org/linphone/views/BitmapWorkerTask.java @@ -31,21 +31,18 @@ import android.provider.MediaStore; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; - +import java.io.FileNotFoundException; +import java.io.IOException; +import java.lang.ref.WeakReference; import org.linphone.mediastream.Log; import org.linphone.utils.FileUtils; import org.linphone.utils.ImageUtils; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.lang.ref.WeakReference; - public class BitmapWorkerTask extends AsyncTask { - private Context mContext; - private Bitmap mDefaultBitmap; - private final WeakReference imageViewReference; public String path; + private Context mContext; + private Bitmap mDefaultBitmap; public BitmapWorkerTask(Context context, ImageView imageView, Bitmap defaultBitmap) { mContext = context; @@ -55,6 +52,17 @@ public class BitmapWorkerTask extends AsyncTask { imageViewReference = new WeakReference<>(imageView); } + public static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) { + if (imageView != null) { + final Drawable drawable = imageView.getDrawable(); + if (drawable instanceof AsyncBitmap) { + final AsyncBitmap asyncDrawable = (AsyncBitmap) drawable; + return asyncDrawable.getBitmapWorkerTask(); + } + } + return null; + } + private Bitmap scaleToFitHeight(Bitmap b, int height) { float factor = height / (float) b.getHeight(); int dstWidth = (int) (b.getWidth() * factor); @@ -73,7 +81,9 @@ public class BitmapWorkerTask extends AsyncTask { if (FileUtils.isExtensionImage(path)) { if (path.startsWith("content")) { try { - bm = MediaStore.Images.Media.getBitmap(mContext.getContentResolver(), Uri.parse(path)); + bm = + MediaStore.Images.Media.getBitmap( + mContext.getContentResolver(), Uri.parse(path)); } catch (FileNotFoundException e) { Log.e(e); } catch (IOException e) { @@ -141,7 +151,9 @@ public class BitmapWorkerTask extends AsyncTask { if (this == bitmapWorkerTask && imageView != null) { imageView.setImageBitmap(bitmap); if (bitmap.getWidth() > ImageUtils.dpToPixels(mContext, 300)) { - RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(bitmap.getWidth(), ViewGroup.LayoutParams.WRAP_CONTENT); + RelativeLayout.LayoutParams params = + new RelativeLayout.LayoutParams( + bitmap.getWidth(), ViewGroup.LayoutParams.WRAP_CONTENT); int margin = (int) ImageUtils.dpToPixels(mContext, 5); params.setMargins(margin, margin, margin, margin); imageView.setLayoutParams(params); @@ -150,15 +162,4 @@ public class BitmapWorkerTask extends AsyncTask { } } } - - public static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) { - if (imageView != null) { - final Drawable drawable = imageView.getDrawable(); - if (drawable instanceof AsyncBitmap) { - final AsyncBitmap asyncDrawable = (AsyncBitmap) drawable; - return asyncDrawable.getBitmapWorkerTask(); - } - } - return null; - } } diff --git a/app/src/main/java/org/linphone/views/CallButton.java b/app/src/main/java/org/linphone/views/CallButton.java index db9201030..cef56ce61 100644 --- a/app/src/main/java/org/linphone/views/CallButton.java +++ b/app/src/main/java/org/linphone/views/CallButton.java @@ -26,20 +26,23 @@ import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.Toast; - import org.linphone.LinphoneManager; -import org.linphone.settings.LinphonePreferences; import org.linphone.R; import org.linphone.core.Call; import org.linphone.core.CallLog; -import org.linphone.core.CoreException; import org.linphone.core.ProxyConfig; +import org.linphone.settings.LinphonePreferences; @SuppressLint("AppCompatCustomView") public class CallButton extends ImageView implements OnClickListener, AddressAware { private AddressText mAddress; + public CallButton(Context context, AttributeSet attrs) { + super(context, attrs); + setOnClickListener(this); + } + public void setAddressWidget(AddressText a) { mAddress = a; } @@ -52,11 +55,6 @@ public class CallButton extends ImageView implements OnClickListener, AddressAwa setOnClickListener(this); } - public CallButton(Context context, AttributeSet attrs) { - super(context, attrs); - setOnClickListener(this); - } - public void onClick(View v) { if (mAddress.getText().length() > 0) { LinphoneManager.getInstance().newOutgoingCall(mAddress); @@ -87,8 +85,13 @@ public class CallButton extends ImageView implements OnClickListener, AddressAwa } protected void onWrongDestinationAddress() { - Toast.makeText(getContext() - , String.format(getResources().getString(R.string.warning_wrong_destination_address), mAddress.getText().toString()) - , Toast.LENGTH_LONG).show(); + Toast.makeText( + getContext(), + String.format( + getResources() + .getString(R.string.warning_wrong_destination_address), + mAddress.getText().toString()), + Toast.LENGTH_LONG) + .show(); } } diff --git a/app/src/main/java/org/linphone/views/CallIncomingAnswerButton.java b/app/src/main/java/org/linphone/views/CallIncomingAnswerButton.java index f4fff9721..048585ce7 100644 --- a/app/src/main/java/org/linphone/views/CallIncomingAnswerButton.java +++ b/app/src/main/java/org/linphone/views/CallIncomingAnswerButton.java @@ -20,15 +20,15 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import android.content.Context; -import androidx.annotation.Nullable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.widget.LinearLayout; - +import androidx.annotation.Nullable; import org.linphone.R; -public class CallIncomingAnswerButton extends LinearLayout implements View.OnClickListener, View.OnTouchListener { +public class CallIncomingAnswerButton extends LinearLayout + implements View.OnClickListener, View.OnTouchListener { private LinearLayout mRoot; private boolean mUseSliderMode = false; private CallIncomingButtonListener mListener; @@ -43,12 +43,13 @@ public class CallIncomingAnswerButton extends LinearLayout implements View.OnCli init(); } - public CallIncomingAnswerButton(Context context,@Nullable AttributeSet attrs) { + public CallIncomingAnswerButton(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } - public CallIncomingAnswerButton(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { + public CallIncomingAnswerButton( + Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } @@ -97,8 +98,7 @@ public class CallIncomingAnswerButton extends LinearLayout implements View.OnCli view.scrollBy((int) (mAnswerX - curX), view.getScrollY()); mOldSize -= mAnswerX - curX; mAnswerX = curX; - if (mOldSize < -25) - mBegin = false; + if (mOldSize < -25) mBegin = false; if (curX < (mScreenWidth / 4) - mRoot.getWidth() && !mBegin) { performClick(); return true; diff --git a/app/src/main/java/org/linphone/views/CallIncomingDeclineButton.java b/app/src/main/java/org/linphone/views/CallIncomingDeclineButton.java index fcce753eb..6cf86cae6 100644 --- a/app/src/main/java/org/linphone/views/CallIncomingDeclineButton.java +++ b/app/src/main/java/org/linphone/views/CallIncomingDeclineButton.java @@ -20,15 +20,15 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import android.content.Context; -import androidx.annotation.Nullable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.widget.LinearLayout; - +import androidx.annotation.Nullable; import org.linphone.R; -public class CallIncomingDeclineButton extends LinearLayout implements View.OnClickListener, View.OnTouchListener { +public class CallIncomingDeclineButton extends LinearLayout + implements View.OnClickListener, View.OnTouchListener { private LinearLayout mRoot; private boolean mUseSliderMode = false; private CallIncomingButtonListener mListener; @@ -47,7 +47,8 @@ public class CallIncomingDeclineButton extends LinearLayout implements View.OnCl init(); } - public CallIncomingDeclineButton(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { + public CallIncomingDeclineButton( + Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } diff --git a/app/src/main/java/org/linphone/views/ContactAvatar.java b/app/src/main/java/org/linphone/views/ContactAvatar.java index 14fbe2fad..734680e60 100644 --- a/app/src/main/java/org/linphone/views/ContactAvatar.java +++ b/app/src/main/java/org/linphone/views/ContactAvatar.java @@ -24,17 +24,13 @@ import android.provider.MediaStore; import android.view.View; import android.widget.ImageView; import android.widget.TextView; - +import java.io.IOException; import org.linphone.LinphoneService; -import org.linphone.utils.ImageUtils; -import org.linphone.utils.LinphoneUtils; import org.linphone.R; import org.linphone.contacts.LinphoneContact; import org.linphone.core.ChatRoomSecurityLevel; import org.linphone.mediastream.Log; - -import java.io.IOException; - +import org.linphone.utils.ImageUtils; class ContactAvatarHolder { public ImageView contactPicture, avatarMask, securityLevel; @@ -99,7 +95,8 @@ public class ContactAvatar { holder.init(); if (displayName.startsWith("+")) { - // If display name is a phone number, use default avatar because generated one will be +... + // If display name is a phone number, use default avatar because generated one will be + // +... holder.generatedAvatar.setVisibility(View.GONE); } else { holder.generatedAvatar.setText(generateAvatar(displayName)); @@ -108,7 +105,8 @@ public class ContactAvatar { holder.securityLevel.setVisibility(View.GONE); } - public static void displayAvatar(String displayName, ChatRoomSecurityLevel securityLevel, View v) { + public static void displayAvatar( + String displayName, ChatRoomSecurityLevel securityLevel, View v) { displayAvatar(displayName, v); setSecurityLevel(securityLevel, v); } @@ -120,12 +118,16 @@ public class ContactAvatar { ContactAvatarHolder holder = new ContactAvatarHolder(v); holder.init(); - if (contact.getThumbnailUri() != null && contact.getThumbnailUri().getScheme().startsWith("http")) { + if (contact.getThumbnailUri() != null + && contact.getThumbnailUri().getScheme().startsWith("http")) { bm = ImageUtils.downloadBitmap(contact.getThumbnailUri()); } else { if (contact.getThumbnailUri() != null) { try { - bm = MediaStore.Images.Media.getBitmap(LinphoneService.instance().getContentResolver(), contact.getThumbnailUri()); + bm = + MediaStore.Images.Media.getBitmap( + LinphoneService.instance().getContentResolver(), + contact.getThumbnailUri()); } catch (IOException e) { Log.e(e); } @@ -137,14 +139,18 @@ public class ContactAvatar { holder.contactPicture.setVisibility(View.VISIBLE); holder.generatedAvatar.setVisibility(View.GONE); } else { - holder.generatedAvatar.setText(generateAvatar(contact.getFullName() == null ? - contact.getFirstName() + " " + contact.getLastName() : contact.getFullName())); + holder.generatedAvatar.setText( + generateAvatar( + contact.getFullName() == null + ? contact.getFirstName() + " " + contact.getLastName() + : contact.getFullName())); holder.generatedAvatar.setVisibility(View.VISIBLE); } holder.securityLevel.setVisibility(View.GONE); } - public static void displayAvatar(LinphoneContact contact, ChatRoomSecurityLevel securityLevel, View v) { + public static void displayAvatar( + LinphoneContact contact, ChatRoomSecurityLevel securityLevel, View v) { displayAvatar(contact, v); setSecurityLevel(securityLevel, v); } diff --git a/app/src/main/java/org/linphone/views/ContactSelectView.java b/app/src/main/java/org/linphone/views/ContactSelectView.java index 58a24b96b..7980eb9bb 100644 --- a/app/src/main/java/org/linphone/views/ContactSelectView.java +++ b/app/src/main/java/org/linphone/views/ContactSelectView.java @@ -24,7 +24,6 @@ import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.TextView; - import org.linphone.LinphoneManager; import org.linphone.R; import org.linphone.contacts.ContactAddress; @@ -36,20 +35,22 @@ public class ContactSelectView extends View { public ContactSelectView(Context context) { super(context); - LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + LayoutInflater inflater = + (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.contact_selected, null); contactName = view.findViewById(R.id.sipUri); deleteContact = view.findViewById(R.id.contactChatDelete); - } public void setContactName(ContactAddress ca) { if (ca.getContact() != null) { contactName.setText(ca.getContact().getFirstName()); } else { - LinphoneManager.getLc().createFriendWithAddress(ca.getAddressAsDisplayableString()).getName(); + LinphoneManager.getLc() + .createFriendWithAddress(ca.getAddressAsDisplayableString()) + .getName(); contactName.setText(ca.getAddressAsDisplayableString()); } } diff --git a/app/src/main/java/org/linphone/views/Digit.java b/app/src/main/java/org/linphone/views/Digit.java index 64db7ca5d..af6861156 100644 --- a/app/src/main/java/org/linphone/views/Digit.java +++ b/app/src/main/java/org/linphone/views/Digit.java @@ -28,33 +28,45 @@ import android.view.MotionEvent; import android.view.View; import android.widget.Button; import android.widget.Toast; - import org.linphone.LinphoneManager; -import org.linphone.settings.LinphonePreferences; import org.linphone.LinphoneService; import org.linphone.R; import org.linphone.call.CallActivity; import org.linphone.core.Core; import org.linphone.mediastream.Log; +import org.linphone.settings.LinphonePreferences; @SuppressLint("AppCompatCustomView") public class Digit extends Button implements AddressAware { private AddressText mAddress; + private boolean mPlayDtmf; + + public Digit(Context context, AttributeSet attrs, int style) { + super(context, attrs, style); + setLongClickable(true); + } + + public Digit(Context context, AttributeSet attrs) { + super(context, attrs); + setLongClickable(true); + } + + public Digit(Context context) { + super(context); + setLongClickable(true); + } public void setAddressWidget(AddressText address) { mAddress = address; } - private boolean mPlayDtmf; - public void setPlayDtmf(boolean play) { mPlayDtmf = play; } @Override - protected void onTextChanged(CharSequence text, int start, int before, - int after) { + protected void onTextChanged(CharSequence text, int start, int before, int after) { super.onTextChanged(text, start, before, after); if (text == null || text.length() < 1) { @@ -74,21 +86,6 @@ public class Digit extends Button implements AddressAware { } } - public Digit(Context context, AttributeSet attrs, int style) { - super(context, attrs, style); - setLongClickable(true); - } - - public Digit(Context context, AttributeSet attrs) { - super(context, attrs); - setLongClickable(true); - } - - public Digit(Context context) { - super(context); - setLongClickable(true); - } - private class DialKeyListener implements OnClickListener, OnTouchListener, OnLongClickListener { final char mKeyCode; boolean mIsDtmfStarted; @@ -100,7 +97,11 @@ public class Digit extends Button implements AddressAware { private boolean linphoneServiceReady() { if (!LinphoneService.isReady()) { Log.w("Service is not ready while pressing digit"); - Toast.makeText(getContext(), getContext().getString(R.string.skipable_error_service_not_ready), Toast.LENGTH_SHORT).show(); + Toast.makeText( + getContext(), + getContext().getString(R.string.skipable_error_service_not_ready), + Toast.LENGTH_SHORT) + .show(); return false; } return true; @@ -127,7 +128,9 @@ public class Digit extends Button implements AddressAware { } if (LinphonePreferences.instance().getDebugPopupAddress() != null - && mAddress.getText().toString().equals(LinphonePreferences.instance().getDebugPopupAddress())) { + && mAddress.getText() + .toString() + .equals(LinphonePreferences.instance().getDebugPopupAddress())) { displayDebugPopup(); } } @@ -137,28 +140,32 @@ public class Digit extends Button implements AddressAware { AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext()); alertDialog.setTitle(getContext().getString(R.string.debug_popup_title)); if (LinphonePreferences.instance().isDebugEnabled()) { - alertDialog.setItems(getContext().getResources().getStringArray(R.array.popup_send_log), new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int which) { - if (which == 0) { - LinphonePreferences.instance().setDebugEnabled(false); - } - if (which == 1) { - Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull(); - if (lc != null) { - lc.uploadLogCollection(); + alertDialog.setItems( + getContext().getResources().getStringArray(R.array.popup_send_log), + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + if (which == 0) { + LinphonePreferences.instance().setDebugEnabled(false); + } + if (which == 1) { + Core lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull(); + if (lc != null) { + lc.uploadLogCollection(); + } + } } - } - } - }); + }); } else { - alertDialog.setItems(getContext().getResources().getStringArray(R.array.popup_enable_log), new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int which) { - if (which == 0) { - LinphonePreferences.instance().setDebugEnabled(true); - } - } - }); + alertDialog.setItems( + getContext().getResources().getStringArray(R.array.popup_enable_log), + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + if (which == 0) { + LinphonePreferences.instance().setDebugEnabled(true); + } + } + }); } alertDialog.show(); mAddress.getEditableText().clear(); @@ -205,7 +212,6 @@ public class Digit extends Button implements AddressAware { return true; } - if (mAddress == null) return true; int lBegin = mAddress.getSelectionStart(); @@ -218,6 +224,4 @@ public class Digit extends Button implements AddressAware { return true; } } - - } diff --git a/app/src/main/java/org/linphone/views/EraseButton.java b/app/src/main/java/org/linphone/views/EraseButton.java index 2c35b7d94..237c572ba 100644 --- a/app/src/main/java/org/linphone/views/EraseButton.java +++ b/app/src/main/java/org/linphone/views/EraseButton.java @@ -29,7 +29,8 @@ import android.view.View.OnLongClickListener; import android.widget.ImageView; @SuppressLint("AppCompatCustomView") -public class EraseButton extends ImageView implements AddressAware, OnClickListener, OnLongClickListener, TextWatcher { +public class EraseButton extends ImageView + implements AddressAware, OnClickListener, OnLongClickListener, TextWatcher { private AddressText address; @@ -61,20 +62,14 @@ public class EraseButton extends ImageView implements AddressAware, OnClickListe view.addTextChangedListener(this); } + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) {} @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - - } - - @Override - public void beforeTextChanged(CharSequence s, int start, int count, - int after) { - } + public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void afterTextChanged(Editable s) { setEnabled(s.length() > 0); } - } diff --git a/app/src/main/java/org/linphone/views/LedPreference.java b/app/src/main/java/org/linphone/views/LedPreference.java index 62e7f9291..afa714cb0 100644 --- a/app/src/main/java/org/linphone/views/LedPreference.java +++ b/app/src/main/java/org/linphone/views/LedPreference.java @@ -23,7 +23,6 @@ import android.content.Context; import android.preference.Preference; import android.view.View; import android.widget.ImageView; - import org.linphone.R; public class LedPreference extends Preference { diff --git a/app/src/main/java/org/linphone/views/LinphoneOverlay.java b/app/src/main/java/org/linphone/views/LinphoneOverlay.java index 9e20ca845..5b4be61b5 100644 --- a/app/src/main/java/org/linphone/views/LinphoneOverlay.java +++ b/app/src/main/java/org/linphone/views/LinphoneOverlay.java @@ -30,10 +30,9 @@ import android.view.MotionEvent; import android.view.SurfaceView; import android.view.View; import android.view.WindowManager; - +import org.linphone.LinphoneActivity; import org.linphone.LinphoneManager; import org.linphone.LinphoneService; -import org.linphone.LinphoneActivity; import org.linphone.core.Call; import org.linphone.core.CallParams; import org.linphone.mediastream.Version; @@ -61,31 +60,35 @@ public class LinphoneOverlay extends org.linphone.mediastream.video.display.GL2J LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_PHONE; } - params = new WindowManager.LayoutParams( - WindowManager.LayoutParams.WRAP_CONTENT, - WindowManager.LayoutParams.WRAP_CONTENT, - LAYOUT_FLAG, - WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, - PixelFormat.TRANSLUCENT); + params = + new WindowManager.LayoutParams( + WindowManager.LayoutParams.WRAP_CONTENT, + WindowManager.LayoutParams.WRAP_CONTENT, + LAYOUT_FLAG, + WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, + PixelFormat.TRANSLUCENT); params.gravity = Gravity.TOP | Gravity.LEFT; metrics = new DisplayMetrics(); wm.getDefaultDisplay().getMetrics(metrics); - androidVideoWindowImpl = new AndroidVideoWindowImpl(this, null, new AndroidVideoWindowImpl.VideoWindowListener() { - public void onVideoRenderingSurfaceReady(AndroidVideoWindowImpl vw, SurfaceView surface) { - LinphoneManager.getLc().setNativeVideoWindowId(vw); - } + androidVideoWindowImpl = + new AndroidVideoWindowImpl( + this, + null, + new AndroidVideoWindowImpl.VideoWindowListener() { + public void onVideoRenderingSurfaceReady( + AndroidVideoWindowImpl vw, SurfaceView surface) { + LinphoneManager.getLc().setNativeVideoWindowId(vw); + } - public void onVideoRenderingSurfaceDestroyed(AndroidVideoWindowImpl vw) { + public void onVideoRenderingSurfaceDestroyed( + AndroidVideoWindowImpl vw) {} - } + public void onVideoPreviewSurfaceReady( + AndroidVideoWindowImpl vw, SurfaceView surface) {} - public void onVideoPreviewSurfaceReady(AndroidVideoWindowImpl vw, SurfaceView surface) { - } - - public void onVideoPreviewSurfaceDestroyed(AndroidVideoWindowImpl vw) { - } - }); + public void onVideoPreviewSurfaceDestroyed(AndroidVideoWindowImpl vw) {} + }); Call call = LinphoneManager.getLc().getCurrentCall(); CallParams callParams = call.getCurrentParams(); @@ -93,21 +96,25 @@ public class LinphoneOverlay extends org.linphone.mediastream.video.display.GL2J params.height = callParams.getReceivedVideoDefinition().getHeight(); LinphoneManager.getLc().setNativeVideoWindowId(androidVideoWindowImpl); - setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - Context context = LinphoneService.instance(); - Intent intent = new Intent(context, LinphoneActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - context.startActivity(intent); - } - }); - setOnLongClickListener(new OnLongClickListener() { - @Override - public boolean onLongClick(View v) { - dragEnabled = true; - return true; - } - }); + setOnClickListener( + new OnClickListener() { + @Override + public void onClick(View v) { + Context context = LinphoneService.instance(); + Intent intent = + new Intent(context, LinphoneActivity.class) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + context.startActivity(intent); + } + }); + setOnLongClickListener( + new OnLongClickListener() { + @Override + public boolean onLongClick(View v) { + dragEnabled = true; + return true; + } + }); } public LinphoneOverlay(Context context, AttributeSet attrs) { @@ -148,8 +155,12 @@ public class LinphoneOverlay extends org.linphone.mediastream.video.display.GL2J } private void updateViewPostion() { - params.x = Math.min(Math.max(0, (int) (x - touchX)), metrics.widthPixels - getMeasuredWidth()); - params.y = Math.min(Math.max(0, (int) (y - touchY)), metrics.heightPixels - getMeasuredHeight()); + params.x = + Math.min(Math.max(0, (int) (x - touchX)), metrics.widthPixels - getMeasuredWidth()); + params.y = + Math.min( + Math.max(0, (int) (y - touchY)), + metrics.heightPixels - getMeasuredHeight()); wm.updateViewLayout(this, params); } diff --git a/app/src/main/java/org/linphone/views/Numpad.java b/app/src/main/java/org/linphone/views/Numpad.java index e2bf799c2..e0a0e921c 100644 --- a/app/src/main/java/org/linphone/views/Numpad.java +++ b/app/src/main/java/org/linphone/views/Numpad.java @@ -26,20 +26,14 @@ import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; - -import org.linphone.R; - import java.util.ArrayList; import java.util.Collection; +import org.linphone.R; public class Numpad extends LinearLayout implements AddressAware { private boolean mPlayDtmf; - public void setPlayDtmf(boolean sendDtmf) { - this.mPlayDtmf = sendDtmf; - } - public Numpad(Context context, boolean playDtmf) { super(context); mPlayDtmf = playDtmf; @@ -57,6 +51,10 @@ public class Numpad extends LinearLayout implements AddressAware { setLongClickable(true); } + public void setPlayDtmf(boolean sendDtmf) { + this.mPlayDtmf = sendDtmf; + } + @Override protected final void onFinishInflate() { for (Digit v : retrieveChildren(this, Digit.class)) { @@ -71,7 +69,6 @@ public class Numpad extends LinearLayout implements AddressAware { } } - private final Collection retrieveChildren(ViewGroup viewGroup, Class clazz) { final Collection views = new ArrayList<>(); @@ -80,12 +77,10 @@ public class Numpad extends LinearLayout implements AddressAware { if (v instanceof ViewGroup) { views.addAll(retrieveChildren((ViewGroup) v, clazz)); } else { - if (clazz.isInstance(v)) - views.add(clazz.cast(v)); + if (clazz.isInstance(v)) views.add(clazz.cast(v)); } } return views; } - } diff --git a/app/src/main/java/org/linphone/views/SlidingDrawer.java b/app/src/main/java/org/linphone/views/SlidingDrawer.java index cc795cb17..9475c0afe 100644 --- a/app/src/main/java/org/linphone/views/SlidingDrawer.java +++ b/app/src/main/java/org/linphone/views/SlidingDrawer.java @@ -33,7 +33,6 @@ import android.view.VelocityTracker; import android.view.View; import android.view.ViewGroup; import android.view.accessibility.AccessibilityEvent; - import org.linphone.R; public class SlidingDrawer extends ViewGroup { @@ -57,17 +56,17 @@ public class SlidingDrawer extends ViewGroup { private final int mHandleId; private final int mContentId; - - private View mHandle; - private View mContent; - private final Rect mFrame = new Rect(); private final Rect mInvalidate = new Rect(); + private final Handler mHandler = new SlidingHandler(); + private final int mTapThreshold; + private final int mMaximumTapVelocity; + private final int mVelocityUnits; + private View mHandle; + private View mContent; private boolean mTracking; private boolean mLocked; - private VelocityTracker mVelocityTracker; - private boolean mInvert; private boolean mVertical; private boolean mExpanded; @@ -75,12 +74,9 @@ public class SlidingDrawer extends ViewGroup { private int mTopOffset; private int mHandleHeight; private int mHandleWidth; - private OnDrawerOpenListener mOnDrawerOpenListener; private OnDrawerCloseListener mOnDrawerCloseListener; private OnDrawerScrollListener mOnDrawerScrollListener; - - private final Handler mHandler = new SlidingHandler(); private float mAnimatedAcceleration; private float mAnimatedVelocity; private float mAnimationPosition; @@ -90,105 +86,57 @@ public class SlidingDrawer extends ViewGroup { private boolean mAnimating; private boolean mAllowSingleTap; private boolean mAnimateOnClick; - - private final int mTapThreshold; - private final int mMaximumTapVelocity; private int mMaximumMinorVelocity; private int mMaximumMajorVelocity; private int mMaximumAcceleration; - private final int mVelocityUnits; /** - * Callback invoked when the drawer is opened. - */ - public static interface OnDrawerOpenListener { - - /** - * Invoked when the drawer becomes fully open. - */ - public void onDrawerOpened(); - } - - /** - * Callback invoked when the drawer is closed. - */ - public static interface OnDrawerCloseListener { - - /** - * Invoked when the drawer becomes fully closed. - */ - public void onDrawerClosed(); - } - - /** - * Callback invoked when the drawer is scrolled. - */ - public static interface OnDrawerScrollListener { - - /** - * Invoked when the user starts dragging/flinging the drawer's handle. - */ - public void onScrollStarted(); - - /** - * Invoked when the user stops dragging/flinging the drawer's handle. - */ - public void onScrollEnded(); - } - - /** - * Creates a new SlidingDrawer from a specified set of attributes defined in - * XML. + * Creates a new SlidingDrawer from a specified set of attributes defined in XML. * * @param context The application's environment. - * @param attrs The attributes defined in XML. + * @param attrs The attributes defined in XML. */ public SlidingDrawer(Context context, AttributeSet attrs) { this(context, attrs, 0); } /** - * Creates a new SlidingDrawer from a specified set of attributes defined in - * XML. + * Creates a new SlidingDrawer from a specified set of attributes defined in XML. * - * @param context The application's environment. - * @param attrs The attributes defined in XML. + * @param context The application's environment. + * @param attrs The attributes defined in XML. * @param defStyle The style to apply to this widget. */ @SuppressWarnings("deprecation") public SlidingDrawer(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); - TypedArray a = context.obtainStyledAttributes(attrs, - R.styleable.SlidingDrawer, defStyle, 0); + TypedArray a = + context.obtainStyledAttributes(attrs, R.styleable.SlidingDrawer, defStyle, 0); mBottomOffset = 0; mTopOffset = 0; mAllowSingleTap = true; mAnimateOnClick = true; - int orientation = a.getInt(R.styleable.SlidingDrawer_direction, - ORIENTATION_BTT); + int orientation = a.getInt(R.styleable.SlidingDrawer_direction, ORIENTATION_BTT); mVertical = (orientation == ORIENTATION_BTT || orientation == ORIENTATION_TTB); mInvert = (orientation == ORIENTATION_TTB || orientation == ORIENTATION_LTR); int handleId = a.getResourceId(R.styleable.SlidingDrawer_handle, 0); if (handleId == 0) { throw new IllegalArgumentException( - "The handle attribute is required and must refer " - + "to a valid child."); + "The handle attribute is required and must refer " + "to a valid child."); } int contentId = a.getResourceId(R.styleable.SlidingDrawer_content, 0); if (contentId == 0) { throw new IllegalArgumentException( - "The content attribute is required and must refer " - + "to a valid child."); + "The content attribute is required and must refer " + "to a valid child."); } if (handleId == contentId) { throw new IllegalArgumentException( - "The content and handle attributes must refer " - + "to different children."); + "The content and handle attributes must refer " + "to different children."); } mHandleId = handleId; mContentId = contentId; @@ -217,16 +165,14 @@ public class SlidingDrawer extends ViewGroup { mHandle = findViewById(mHandleId); if (mHandle == null) { throw new IllegalArgumentException( - "The handle attribute is must refer to an" - + " existing child."); + "The handle attribute is must refer to an" + " existing child."); } mHandle.setOnClickListener(new DrawerToggler()); mContent = findViewById(mContentId); if (mContent == null) { throw new IllegalArgumentException( - "The content attribute is must refer to an" - + " existing child."); + "The content attribute is must refer to an" + " existing child."); } mContent.setVisibility(View.GONE); } @@ -239,26 +185,23 @@ public class SlidingDrawer extends ViewGroup { int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec); int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec); - if (widthSpecMode == MeasureSpec.UNSPECIFIED - || heightSpecMode == MeasureSpec.UNSPECIFIED) { - throw new RuntimeException( - "SlidingDrawer cannot have UNSPECIFIED dimensions"); + if (widthSpecMode == MeasureSpec.UNSPECIFIED || heightSpecMode == MeasureSpec.UNSPECIFIED) { + throw new RuntimeException("SlidingDrawer cannot have UNSPECIFIED dimensions"); } final View handle = mHandle; measureChild(handle, widthMeasureSpec, heightMeasureSpec); if (mVertical) { - int height = heightSpecSize - handle.getMeasuredHeight() - - mTopOffset; - mContent.measure(MeasureSpec.makeMeasureSpec(widthSpecSize, - MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, - MeasureSpec.AT_MOST)); + int height = heightSpecSize - handle.getMeasuredHeight() - mTopOffset; + mContent.measure( + MeasureSpec.makeMeasureSpec(widthSpecSize, MeasureSpec.EXACTLY), + MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST)); } else { int width = widthSpecSize - handle.getMeasuredWidth() - mTopOffset; - mContent.measure(MeasureSpec.makeMeasureSpec(width, - MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec( - heightSpecSize, MeasureSpec.EXACTLY)); + mContent.measure( + MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), + MeasureSpec.makeMeasureSpec(heightSpecSize, MeasureSpec.EXACTLY)); } setMeasuredDimension(widthSpecSize, heightSpecSize); @@ -281,28 +224,35 @@ public class SlidingDrawer extends ViewGroup { if (cache != null) { if (isVertical) { if (mInvert) { - canvas.drawBitmap(cache, 0, handle.getTop() - - (getCustomBottom() - getTop()) + mHandleHeight, + canvas.drawBitmap( + cache, + 0, + handle.getTop() - (getCustomBottom() - getTop()) + mHandleHeight, null); } else { canvas.drawBitmap(cache, 0, handle.getBottom(), null); } } else { - canvas.drawBitmap(cache, - mInvert ? handle.getLeft() - cache.getWidth() - : handle.getRight(), 0, null); + canvas.drawBitmap( + cache, + mInvert ? handle.getLeft() - cache.getWidth() : handle.getRight(), + 0, + null); } } else { canvas.save(); if (mInvert) { - canvas.translate(isVertical ? 0 : handle.getLeft() - - mTopOffset - mContent.getMeasuredWidth(), - isVertical ? handle.getTop() - mTopOffset - - mContent.getMeasuredHeight() : 0); + canvas.translate( + isVertical + ? 0 + : handle.getLeft() - mTopOffset - mContent.getMeasuredWidth(), + isVertical + ? handle.getTop() - mTopOffset - mContent.getMeasuredHeight() + : 0); } else { - canvas.translate(isVertical ? 0 : handle.getLeft() - - mTopOffset, isVertical ? handle.getTop() - - mTopOffset : 0); + canvas.translate( + isVertical ? 0 : handle.getLeft() - mTopOffset, + isVertical ? handle.getTop() - mTopOffset : 0); } drawChild(canvas, mContent, drawingTime); canvas.restore(); @@ -327,7 +277,6 @@ public class SlidingDrawer extends ViewGroup { int handleWidth = handle.getMeasuredWidth(); int handleHeight = handle.getMeasuredHeight(); - int handleLeft; int handleTop; @@ -337,34 +286,39 @@ public class SlidingDrawer extends ViewGroup { handleLeft = (width - handleWidth) / 2; if (mInvert) { handleTop = mExpanded ? content.getMeasuredHeight() - mBottomOffset : mTopOffset; - content.layout(0, mTopOffset, content.getMeasuredWidth(), + content.layout( + 0, + mTopOffset, + content.getMeasuredWidth(), mTopOffset + content.getMeasuredHeight()); } else { - handleTop = mExpanded ? mTopOffset : height - handleHeight - + mBottomOffset; - content.layout(0, mTopOffset + handleHeight, - content.getMeasuredWidth(), mTopOffset + handleHeight - + content.getMeasuredHeight()); + handleTop = mExpanded ? mTopOffset : height - handleHeight + mBottomOffset; + content.layout( + 0, + mTopOffset + handleHeight, + content.getMeasuredWidth(), + mTopOffset + handleHeight + content.getMeasuredHeight()); } } else { handleTop = (height - handleHeight) / 2; if (mInvert) { - handleLeft = mExpanded ? width - mBottomOffset - handleWidth - : mTopOffset; - content.layout(mTopOffset, 0, + handleLeft = mExpanded ? width - mBottomOffset - handleWidth : mTopOffset; + content.layout( + mTopOffset, + 0, mTopOffset + content.getMeasuredWidth(), content.getMeasuredHeight()); } else { - handleLeft = mExpanded ? mTopOffset : width - handleWidth - + mBottomOffset; - content.layout(mTopOffset + handleWidth, 0, mTopOffset - + handleWidth + content.getMeasuredWidth(), + handleLeft = mExpanded ? mTopOffset : width - handleWidth + mBottomOffset; + content.layout( + mTopOffset + handleWidth, + 0, + mTopOffset + handleWidth + content.getMeasuredWidth(), content.getMeasuredHeight()); } } - handle.layout(handleLeft, handleTop, handleLeft + handleWidth, - handleTop + handleHeight); + handle.layout(handleLeft, handleTop, handleLeft + handleWidth, handleTop + handleHeight); mHandleHeight = handle.getHeight(); mHandleWidth = handle.getWidth(); } @@ -426,103 +380,121 @@ public class SlidingDrawer extends ViewGroup { final int action = event.getAction(); switch (action) { case MotionEvent.ACTION_MOVE: - moveHandle((int) (mVertical ? event.getY() : event.getX()) - - mTouchDelta); + moveHandle((int) (mVertical ? event.getY() : event.getX()) - mTouchDelta); break; case MotionEvent.ACTION_UP: - case MotionEvent.ACTION_CANCEL: { - final VelocityTracker velocityTracker = mVelocityTracker; - velocityTracker.computeCurrentVelocity(mVelocityUnits); + case MotionEvent.ACTION_CANCEL: + { + final VelocityTracker velocityTracker = mVelocityTracker; + velocityTracker.computeCurrentVelocity(mVelocityUnits); - float yVelocity = velocityTracker.getYVelocity(); - float xVelocity = velocityTracker.getXVelocity(); - boolean negative; + float yVelocity = velocityTracker.getYVelocity(); + float xVelocity = velocityTracker.getXVelocity(); + boolean negative; - final boolean vertical = mVertical; - if (vertical) { - negative = yVelocity < 0; - if (xVelocity < 0) { - xVelocity = -xVelocity; - } - // fix by Maciej Ciemięga. - if ((!mInvert && xVelocity > mMaximumMinorVelocity) - || (mInvert && xVelocity < mMaximumMinorVelocity)) { - xVelocity = mMaximumMinorVelocity; - } - } else { - negative = xVelocity < 0; - if (yVelocity < 0) { - yVelocity = -yVelocity; - } - // fix by Maciej Ciemięga. - if ((!mInvert && yVelocity > mMaximumMinorVelocity) - || (mInvert && yVelocity < mMaximumMinorVelocity)) { - yVelocity = mMaximumMinorVelocity; - } - } - - float velocity = (float) Math.hypot(xVelocity, yVelocity); - if (negative) { - velocity = -velocity; - } - - final int handleTop = mHandle.getTop(); - final int handleLeft = mHandle.getLeft(); - final int handleBottom = mHandle.getBottom(); - final int handleRight = mHandle.getRight(); - - if (Math.abs(velocity) < mMaximumTapVelocity) { - boolean c1; - boolean c2; - boolean c3; - boolean c4; - - if (mInvert) { - c1 = (mExpanded && (getCustomBottom() - handleBottom) < mTapThreshold - + mBottomOffset); - c2 = (!mExpanded && handleTop < mTopOffset - + mHandleHeight - mTapThreshold); - c3 = (mExpanded && (getRight() - handleRight) < mTapThreshold - + mBottomOffset); - c4 = (!mExpanded && handleLeft > mTopOffset - + mHandleWidth + mTapThreshold); - } else { - c1 = (mExpanded && handleTop < mTapThreshold - + mTopOffset); - c2 = (!mExpanded && handleTop > mBottomOffset - + getCustomBottom() - getTop() - mHandleHeight - - mTapThreshold); - c3 = (mExpanded && handleLeft < mTapThreshold - + mTopOffset); - c4 = (!mExpanded && handleLeft > mBottomOffset - + getRight() - getLeft() - mHandleWidth - - mTapThreshold); - } - - if (vertical ? c1 || c2 : c3 || c4) { - - if (mAllowSingleTap) { - playSoundEffect(SoundEffectConstants.CLICK); - - if (mExpanded) { - animateClose(vertical ? handleTop : handleLeft); - } else { - animateOpen(vertical ? handleTop : handleLeft); - } - } else { - performFling(vertical ? handleTop : handleLeft, - velocity, false); + final boolean vertical = mVertical; + if (vertical) { + negative = yVelocity < 0; + if (xVelocity < 0) { + xVelocity = -xVelocity; + } + // fix by Maciej Ciemięga. + if ((!mInvert && xVelocity > mMaximumMinorVelocity) + || (mInvert && xVelocity < mMaximumMinorVelocity)) { + xVelocity = mMaximumMinorVelocity; } } else { - performFling(vertical ? handleTop : handleLeft, - velocity, false); + negative = xVelocity < 0; + if (yVelocity < 0) { + yVelocity = -yVelocity; + } + // fix by Maciej Ciemięga. + if ((!mInvert && yVelocity > mMaximumMinorVelocity) + || (mInvert && yVelocity < mMaximumMinorVelocity)) { + yVelocity = mMaximumMinorVelocity; + } + } + + float velocity = (float) Math.hypot(xVelocity, yVelocity); + if (negative) { + velocity = -velocity; + } + + final int handleTop = mHandle.getTop(); + final int handleLeft = mHandle.getLeft(); + final int handleBottom = mHandle.getBottom(); + final int handleRight = mHandle.getRight(); + + if (Math.abs(velocity) < mMaximumTapVelocity) { + boolean c1; + boolean c2; + boolean c3; + boolean c4; + + if (mInvert) { + c1 = + (mExpanded + && (getCustomBottom() - handleBottom) + < mTapThreshold + mBottomOffset); + c2 = + (!mExpanded + && handleTop + < mTopOffset + + mHandleHeight + - mTapThreshold); + c3 = + (mExpanded + && (getRight() - handleRight) + < mTapThreshold + mBottomOffset); + c4 = + (!mExpanded + && handleLeft + > mTopOffset + + mHandleWidth + + mTapThreshold); + } else { + c1 = (mExpanded && handleTop < mTapThreshold + mTopOffset); + c2 = + (!mExpanded + && handleTop + > mBottomOffset + + getCustomBottom() + - getTop() + - mHandleHeight + - mTapThreshold); + c3 = (mExpanded && handleLeft < mTapThreshold + mTopOffset); + c4 = + (!mExpanded + && handleLeft + > mBottomOffset + + getRight() + - getLeft() + - mHandleWidth + - mTapThreshold); + } + + if (vertical ? c1 || c2 : c3 || c4) { + + if (mAllowSingleTap) { + playSoundEffect(SoundEffectConstants.CLICK); + + if (mExpanded) { + animateClose(vertical ? handleTop : handleLeft); + } else { + animateOpen(vertical ? handleTop : handleLeft); + } + } else { + performFling( + vertical ? handleTop : handleLeft, velocity, false); + } + } else { + performFling(vertical ? handleTop : handleLeft, velocity, false); + } + } else { + performFling(vertical ? handleTop : handleLeft, velocity, false); } - } else { - performFling(vertical ? handleTop : handleLeft, velocity, - false); } - } - break; + break; } } @@ -551,13 +523,12 @@ public class SlidingDrawer extends ViewGroup { int bottom = mVertical ? getCustomBottom() + mHandleHeight : getRight(); int handleHeight = mVertical ? mHandleHeight : mHandleWidth; - c1 = mInvert ? velocity < mMaximumMajorVelocity - : velocity > mMaximumMajorVelocity; - c2 = mInvert ? (bottom - (position + handleHeight)) + mBottomOffset > handleHeight - : position > mTopOffset - + (mVertical ? mHandleHeight : mHandleWidth); - c3 = mInvert ? velocity < -mMaximumMajorVelocity - : velocity > -mMaximumMajorVelocity; + c1 = mInvert ? velocity < mMaximumMajorVelocity : velocity > mMaximumMajorVelocity; + c2 = + mInvert + ? (bottom - (position + handleHeight)) + mBottomOffset > handleHeight + : position > mTopOffset + (mVertical ? mHandleHeight : mHandleWidth); + c3 = mInvert ? velocity < -mMaximumMajorVelocity : velocity > -mMaximumMajorVelocity; if (always || (c1 || (c2 && c3))) { // We are expanded, So animate to CLOSE! mAnimatedAcceleration = mMaximumAcceleration; @@ -590,12 +561,12 @@ public class SlidingDrawer extends ViewGroup { // WE'RE COLLAPSED - c1 = mInvert ? velocity < mMaximumMajorVelocity - : velocity > mMaximumMajorVelocity; - c2 = mInvert ? (position < (mVertical ? getHeight() : getWidth()) / 2) - : (position > (mVertical ? getHeight() : getWidth()) / 2); - c3 = mInvert ? velocity < -mMaximumMajorVelocity - : velocity > -mMaximumMajorVelocity; + c1 = mInvert ? velocity < mMaximumMajorVelocity : velocity > mMaximumMajorVelocity; + c2 = + mInvert + ? (position < (mVertical ? getHeight() : getWidth()) / 2) + : (position > (mVertical ? getHeight() : getWidth()) / 2); + c3 = mInvert ? velocity < -mMaximumMajorVelocity : velocity > -mMaximumMajorVelocity; if (!always && (c1 || (c2 && c3))) { mAnimatedAcceleration = mMaximumAcceleration; @@ -629,8 +600,7 @@ public class SlidingDrawer extends ViewGroup { mCurrentAnimationTime = now + ANIMATION_FRAME_DURATION; mAnimating = true; mHandler.removeMessages(MSG_ANIMATE); - mHandler.sendMessageAtTime(mHandler.obtainMessage(MSG_ANIMATE), - mCurrentAnimationTime); + mHandler.sendMessageAtTime(mHandler.obtainMessage(MSG_ANIMATE), mCurrentAnimationTime); stopTracking(); } @@ -642,12 +612,13 @@ public class SlidingDrawer extends ViewGroup { if (opening) { mAnimatedAcceleration = mMaximumAcceleration; mAnimatedVelocity = mMaximumMajorVelocity; - if (mInvert) - mAnimationPosition = mTopOffset; + if (mInvert) mAnimationPosition = mTopOffset; else - mAnimationPosition = mBottomOffset - + (mVertical ? getHeight() - mHandleHeight : getWidth() - - mHandleWidth); + mAnimationPosition = + mBottomOffset + + (mVertical + ? getHeight() - mHandleHeight + : getWidth() - mHandleWidth); moveHandle((int) mAnimationPosition); mAnimating = true; mHandler.removeMessages(MSG_ANIMATE); @@ -670,17 +641,20 @@ public class SlidingDrawer extends ViewGroup { if (mVertical) { if (position == EXPANDED_FULL_OPEN) { if (mInvert) - handle.offsetTopAndBottom(mBottomOffset + getCustomBottom() - - getTop() - mHandleHeight); - else - handle.offsetTopAndBottom(mTopOffset - handle.getTop()); + handle.offsetTopAndBottom( + mBottomOffset + getCustomBottom() - getTop() - mHandleHeight); + else handle.offsetTopAndBottom(mTopOffset - handle.getTop()); invalidate(); } else if (position == COLLAPSED_FULL_CLOSED) { if (mInvert) { handle.offsetTopAndBottom(mTopOffset - handle.getTop()); } else { - handle.offsetTopAndBottom(mBottomOffset + getCustomBottom() - - getTop() - mHandleHeight - handle.getTop()); + handle.offsetTopAndBottom( + mBottomOffset + + getCustomBottom() + - getTop() + - mHandleHeight + - handle.getTop()); } invalidate(); } else { @@ -688,10 +662,9 @@ public class SlidingDrawer extends ViewGroup { int deltaY = position - top; if (position < mTopOffset) { deltaY = mTopOffset - top; - } else if (deltaY > mBottomOffset + getCustomBottom() - getTop() - - mHandleHeight - top) { - deltaY = mBottomOffset + getCustomBottom() - getTop() - - mHandleHeight - top; + } else if (deltaY + > mBottomOffset + getCustomBottom() - getTop() - mHandleHeight - top) { + deltaY = mBottomOffset + getCustomBottom() - getTop() - mHandleHeight - top; } handle.offsetTopAndBottom(deltaY); @@ -702,37 +675,39 @@ public class SlidingDrawer extends ViewGroup { handle.getHitRect(frame); region.set(frame); - region.union(frame.left, frame.top - deltaY, frame.right, - frame.bottom - deltaY); - region.union(0, frame.bottom - deltaY, getWidth(), frame.bottom - - deltaY + mContent.getHeight()); + region.union(frame.left, frame.top - deltaY, frame.right, frame.bottom - deltaY); + region.union( + 0, + frame.bottom - deltaY, + getWidth(), + frame.bottom - deltaY + mContent.getHeight()); invalidate(region); } } else { if (position == EXPANDED_FULL_OPEN) { if (mInvert) - handle.offsetLeftAndRight(mBottomOffset + getRight() - - getLeft() - mHandleWidth); - else - handle.offsetLeftAndRight(mTopOffset - handle.getLeft()); + handle.offsetLeftAndRight( + mBottomOffset + getRight() - getLeft() - mHandleWidth); + else handle.offsetLeftAndRight(mTopOffset - handle.getLeft()); invalidate(); } else if (position == COLLAPSED_FULL_CLOSED) { - if (mInvert) - handle.offsetLeftAndRight(mTopOffset - handle.getLeft()); + if (mInvert) handle.offsetLeftAndRight(mTopOffset - handle.getLeft()); else - handle.offsetLeftAndRight(mBottomOffset + getRight() - - getLeft() - mHandleWidth - handle.getLeft()); + handle.offsetLeftAndRight( + mBottomOffset + + getRight() + - getLeft() + - mHandleWidth + - handle.getLeft()); invalidate(); } else { final int left = handle.getLeft(); int deltaX = position - left; if (position < mTopOffset) { deltaX = mTopOffset - left; - } else if (deltaX > mBottomOffset + getRight() - getLeft() - - mHandleWidth - left) { - deltaX = mBottomOffset + getRight() - getLeft() - - mHandleWidth - left; + } else if (deltaX > mBottomOffset + getRight() - getLeft() - mHandleWidth - left) { + deltaX = mBottomOffset + getRight() - getLeft() - mHandleWidth - left; } handle.offsetLeftAndRight(deltaX); @@ -742,10 +717,12 @@ public class SlidingDrawer extends ViewGroup { handle.getHitRect(frame); region.set(frame); - region.union(frame.left - deltaX, frame.top, frame.right - - deltaX, frame.bottom); - region.union(frame.right - deltaX, 0, frame.right - deltaX - + mContent.getWidth(), getHeight()); + region.union(frame.left - deltaX, frame.top, frame.right - deltaX, frame.bottom); + region.union( + frame.right - deltaX, + 0, + frame.right - deltaX + mContent.getWidth(), + getHeight()); invalidate(region); } @@ -765,36 +742,42 @@ public class SlidingDrawer extends ViewGroup { if (mVertical) { final int handleHeight = mHandleHeight; int height = getBottom() - getTop() - handleHeight - mTopOffset; - content.measure(MeasureSpec.makeMeasureSpec(getRight() - - getLeft(), MeasureSpec.EXACTLY), MeasureSpec - .makeMeasureSpec(height, MeasureSpec.AT_MOST)); + content.measure( + MeasureSpec.makeMeasureSpec(getRight() - getLeft(), MeasureSpec.EXACTLY), + MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST)); if (mInvert) - content.layout(0, mTopOffset, content.getMeasuredWidth(), + content.layout( + 0, + mTopOffset, + content.getMeasuredWidth(), mTopOffset + content.getMeasuredHeight()); else content.layout( 0, mTopOffset + handleHeight, content.getMeasuredWidth(), - mTopOffset + handleHeight - + content.getMeasuredHeight()); + mTopOffset + handleHeight + content.getMeasuredHeight()); } else { final int handleWidth = mHandle.getWidth(); int width = getRight() - getLeft() - handleWidth - mTopOffset; - content.measure(MeasureSpec.makeMeasureSpec(width, - MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec( - getBottom() - getTop(), MeasureSpec.EXACTLY)); + content.measure( + MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), + MeasureSpec.makeMeasureSpec(getBottom() - getTop(), MeasureSpec.EXACTLY)); if (mInvert) - content.layout(mTopOffset, 0, + content.layout( + mTopOffset, + 0, mTopOffset + content.getMeasuredWidth(), content.getMeasuredHeight()); else - content.layout(handleWidth + mTopOffset, 0, mTopOffset - + handleWidth + content.getMeasuredWidth(), + content.layout( + handleWidth + mTopOffset, + 0, + mTopOffset + handleWidth + content.getMeasuredWidth(), content.getMeasuredHeight()); } } @@ -828,20 +811,19 @@ public class SlidingDrawer extends ViewGroup { if (mAnimationPosition < mTopOffset) { mAnimating = false; closeDrawer(); - } else if (mAnimationPosition >= mTopOffset - + (mVertical ? getHeight() : getWidth()) - 1) { + } else if (mAnimationPosition + >= mTopOffset + (mVertical ? getHeight() : getWidth()) - 1) { mAnimating = false; openDrawer(); } else { moveHandle((int) mAnimationPosition); mCurrentAnimationTime += ANIMATION_FRAME_DURATION; mHandler.sendMessageAtTime( - mHandler.obtainMessage(MSG_ANIMATE), - mCurrentAnimationTime); + mHandler.obtainMessage(MSG_ANIMATE), mCurrentAnimationTime); } } else { - if (mAnimationPosition >= mBottomOffset - + (mVertical ? getHeight() : getWidth()) - 1) { + if (mAnimationPosition + >= mBottomOffset + (mVertical ? getHeight() : getWidth()) - 1) { mAnimating = false; closeDrawer(); } else if (mAnimationPosition < mTopOffset) { @@ -851,8 +833,7 @@ public class SlidingDrawer extends ViewGroup { moveHandle((int) mAnimationPosition); mCurrentAnimationTime += ANIMATION_FRAME_DURATION; mHandler.sendMessageAtTime( - mHandler.obtainMessage(MSG_ANIMATE), - mCurrentAnimationTime); + mHandler.obtainMessage(MSG_ANIMATE), mCurrentAnimationTime); } } } @@ -1014,44 +995,38 @@ public class SlidingDrawer extends ViewGroup { } /** - * Sets the listener that receives a notification when the drawer becomes - * open. + * Sets the listener that receives a notification when the drawer becomes open. * * @param onDrawerOpenListener The listener to be notified when the drawer is opened. */ - public void setOnDrawerOpenListener( - OnDrawerOpenListener onDrawerOpenListener) { + public void setOnDrawerOpenListener(OnDrawerOpenListener onDrawerOpenListener) { mOnDrawerOpenListener = onDrawerOpenListener; } /** - * Sets the listener that receives a notification when the drawer becomes - * close. + * Sets the listener that receives a notification when the drawer becomes close. * * @param onDrawerCloseListener The listener to be notified when the drawer is closed. */ - public void setOnDrawerCloseListener( - OnDrawerCloseListener onDrawerCloseListener) { + public void setOnDrawerCloseListener(OnDrawerCloseListener onDrawerCloseListener) { mOnDrawerCloseListener = onDrawerCloseListener; } /** - * Sets the listener that receives a notification when the drawer starts or - * ends a scroll. A fling is considered as a scroll. A fling will also - * trigger a drawer opened or drawer closed event. + * Sets the listener that receives a notification when the drawer starts or ends a scroll. A + * fling is considered as a scroll. A fling will also trigger a drawer opened or drawer closed + * event. * * @param onDrawerScrollListener The listener to be notified when scrolling starts or stops. */ - public void setOnDrawerScrollListener( - OnDrawerScrollListener onDrawerScrollListener) { + public void setOnDrawerScrollListener(OnDrawerScrollListener onDrawerScrollListener) { mOnDrawerScrollListener = onDrawerScrollListener; } /** * Returns the handle of the drawer. * - * @return The View reprenseting the handle of the drawer, identified by the - * "handle" id in XML. + * @return The View reprenseting the handle of the drawer, identified by the "handle" id in XML. */ public View getHandle() { return mHandle; @@ -1060,8 +1035,8 @@ public class SlidingDrawer extends ViewGroup { /** * Returns the content of the drawer. * - * @return The View reprenseting the content of the drawer, identified by - * the "content" id in XML. + * @return The View reprenseting the content of the drawer, identified by the "content" id in + * XML. */ public View getContent() { return mContent; @@ -1103,6 +1078,30 @@ public class SlidingDrawer extends ViewGroup { return mTracking || mAnimating; } + /** Callback invoked when the drawer is opened. */ + public static interface OnDrawerOpenListener { + + /** Invoked when the drawer becomes fully open. */ + public void onDrawerOpened(); + } + + /** Callback invoked when the drawer is closed. */ + public static interface OnDrawerCloseListener { + + /** Invoked when the drawer becomes fully closed. */ + public void onDrawerClosed(); + } + + /** Callback invoked when the drawer is scrolled. */ + public static interface OnDrawerScrollListener { + + /** Invoked when the user starts dragging/flinging the drawer's handle. */ + public void onScrollStarted(); + + /** Invoked when the user stops dragging/flinging the drawer's handle. */ + public void onScrollEnded(); + } + private class DrawerToggler implements OnClickListener { public void onClick(View v) { @@ -1131,4 +1130,4 @@ public class SlidingDrawer extends ViewGroup { } } } -} \ No newline at end of file +} diff --git a/app/src/main/java/org/linphone/xmlrpc/XmlRpcHelper.java b/app/src/main/java/org/linphone/xmlrpc/XmlRpcHelper.java index 62aea2469..04354cbb4 100644 --- a/app/src/main/java/org/linphone/xmlrpc/XmlRpcHelper.java +++ b/app/src/main/java/org/linphone/xmlrpc/XmlRpcHelper.java @@ -20,13 +20,13 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import org.linphone.LinphoneManager; -import org.linphone.settings.LinphonePreferences; import org.linphone.core.XmlRpcArgType; import org.linphone.core.XmlRpcRequest; import org.linphone.core.XmlRpcRequestListener; import org.linphone.core.XmlRpcSession; import org.linphone.core.XmlRpcStatus; import org.linphone.mediastream.Log; +import org.linphone.settings.LinphonePreferences; public class XmlRpcHelper { public static final String SERVER_ERROR_INVALID_ACCOUNT = "ERROR_INVALID_ACCOUNT"; @@ -36,7 +36,8 @@ public class XmlRpcHelper { public static final String SERVER_ERROR_PURCHASE_CANCELLED = "ERROR_PURCHASE_CANCELLED"; public static final String SERVER_ERROR_RECEIPT_PARSING_FAILED = "ERROR_RECEIPT_PARSING_FAILED"; public static final String SERVER_ERROR_UID_ALREADY_IN_USE = "ERROR_UID_ALREADY_IN_USE"; - public static final String SERVER_ERROR_SIGNATURE_VERIFICATION_FAILED = "ERROR_SIGNATURE_VERIFICATION_FAILED"; + public static final String SERVER_ERROR_SIGNATURE_VERIFICATION_FAILED = + "ERROR_SIGNATURE_VERIFICATION_FAILED"; public static final String SERVER_ERROR_ACCOUNT_ALREADY_EXISTS = "ERROR_ACCOUNT_ALREADY_EXISTS"; public static final String SERVER_ERROR_UNKNOWN_ERROR = "ERROR_UNKNOWN_ERROR"; @@ -46,77 +47,95 @@ public class XmlRpcHelper { private XmlRpcSession xmlRpcSession; public XmlRpcHelper() { - xmlRpcSession = LinphoneManager.getLcIfManagerNotDestroyedOrNull().createXmlRpcSession(LinphonePreferences.instance().getInAppPurchaseValidatingServerUrl()); + xmlRpcSession = + LinphoneManager.getLcIfManagerNotDestroyedOrNull() + .createXmlRpcSession( + LinphonePreferences.instance() + .getInAppPurchaseValidatingServerUrl()); } - public void createAccountAsync(final XmlRpcListener listener, String username, String email, String password) { - XmlRpcRequest xmlRpcRequest = xmlRpcSession.createRequest(XmlRpcArgType.String, "create_account"); - xmlRpcRequest.setListener(new XmlRpcRequestListener() { - @Override - public void onResponse(XmlRpcRequest request) { - String result = request.getStringResponse(); - if (request.getStatus() == XmlRpcStatus.Ok) { - if (result.startsWith("ERROR_")) { - Log.e(result); - listener.onError(result); - return; + public void createAccountAsync( + final XmlRpcListener listener, String username, String email, String password) { + XmlRpcRequest xmlRpcRequest = + xmlRpcSession.createRequest(XmlRpcArgType.String, "create_account"); + xmlRpcRequest.setListener( + new XmlRpcRequestListener() { + @Override + public void onResponse(XmlRpcRequest request) { + String result = request.getStringResponse(); + if (request.getStatus() == XmlRpcStatus.Ok) { + if (result.startsWith("ERROR_")) { + Log.e(result); + listener.onError(result); + return; + } + listener.onAccountCreated(result); + } else if (request.getStatus() == XmlRpcStatus.Failed) { + Log.e(result); + listener.onError(result); + } } - listener.onAccountCreated(result); - } else if (request.getStatus() == XmlRpcStatus.Failed) { - Log.e(result); - listener.onError(result); - } - } - }); + }); xmlRpcRequest.addStringArg(username); xmlRpcRequest.addStringArg(email); xmlRpcRequest.addStringArg(password == null ? "" : password); xmlRpcSession.sendRequest(xmlRpcRequest); } - public void getAccountExpireAsync(final XmlRpcListener listener, String username, String password) { - XmlRpcRequest xmlRpcRequest = xmlRpcSession.createRequest(XmlRpcArgType.String, "get_account_expiration"); - xmlRpcRequest.setListener(new XmlRpcRequestListener() { - @Override - public void onResponse(XmlRpcRequest request) { - String result = request.getStringResponse(); - if (request.getStatus() == XmlRpcStatus.Ok) { - if (result.startsWith("ERROR_")) { - Log.e(result); - listener.onError(result); - return; + public void getAccountExpireAsync( + final XmlRpcListener listener, String username, String password) { + XmlRpcRequest xmlRpcRequest = + xmlRpcSession.createRequest(XmlRpcArgType.String, "get_account_expiration"); + xmlRpcRequest.setListener( + new XmlRpcRequestListener() { + @Override + public void onResponse(XmlRpcRequest request) { + String result = request.getStringResponse(); + if (request.getStatus() == XmlRpcStatus.Ok) { + if (result.startsWith("ERROR_")) { + Log.e(result); + listener.onError(result); + return; + } + listener.onAccountExpireFetched(result); + } else if (request.getStatus() == XmlRpcStatus.Failed) { + Log.e(result); + listener.onError(result); + } } - listener.onAccountExpireFetched(result); - } else if (request.getStatus() == XmlRpcStatus.Failed) { - Log.e(result); - listener.onError(result); - } - } - }); + }); xmlRpcRequest.addStringArg(username); xmlRpcRequest.addStringArg(password); xmlRpcSession.sendRequest(xmlRpcRequest); } - public void updateAccountExpireAsync(final XmlRpcListener listener, String username, String password, String domain, String payload, String signature) { - XmlRpcRequest xmlRpcRequest = xmlRpcSession.createRequest(XmlRpcArgType.String, "update_expiration_date"); - xmlRpcRequest.setListener(new XmlRpcRequestListener() { - @Override - public void onResponse(XmlRpcRequest request) { - String result = request.getStringResponse(); - if (request.getStatus() == XmlRpcStatus.Ok) { - if (result.startsWith("ERROR_")) { - Log.e(result); - listener.onError(result); - return; + public void updateAccountExpireAsync( + final XmlRpcListener listener, + String username, + String password, + String domain, + String payload, + String signature) { + XmlRpcRequest xmlRpcRequest = + xmlRpcSession.createRequest(XmlRpcArgType.String, "update_expiration_date"); + xmlRpcRequest.setListener( + new XmlRpcRequestListener() { + @Override + public void onResponse(XmlRpcRequest request) { + String result = request.getStringResponse(); + if (request.getStatus() == XmlRpcStatus.Ok) { + if (result.startsWith("ERROR_")) { + Log.e(result); + listener.onError(result); + return; + } + listener.onAccountExpireUpdated(result); + } else if (request.getStatus() == XmlRpcStatus.Failed) { + Log.e(result); + listener.onError(result); + } } - listener.onAccountExpireUpdated(result); - } else if (request.getStatus() == XmlRpcStatus.Failed) { - Log.e(result); - listener.onError(result); - } - } - }); + }); xmlRpcRequest.addStringArg(username); xmlRpcRequest.addStringArg(password); xmlRpcRequest.addStringArg(domain); @@ -125,298 +144,339 @@ public class XmlRpcHelper { xmlRpcSession.sendRequest(xmlRpcRequest); } - public void activateAccountAsync(final XmlRpcListener listener, String username, String password) { - XmlRpcRequest xmlRpcRequest = xmlRpcSession.createRequest(XmlRpcArgType.String, "activate_account"); - xmlRpcRequest.setListener(new XmlRpcRequestListener() { - @Override - public void onResponse(XmlRpcRequest request) { - String result = request.getStringResponse(); - if (request.getStatus() == XmlRpcStatus.Ok) { - if (result.startsWith("ERROR_")) { - Log.e(result); - listener.onError(result); - return; + public void activateAccountAsync( + final XmlRpcListener listener, String username, String password) { + XmlRpcRequest xmlRpcRequest = + xmlRpcSession.createRequest(XmlRpcArgType.String, "activate_account"); + xmlRpcRequest.setListener( + new XmlRpcRequestListener() { + @Override + public void onResponse(XmlRpcRequest request) { + String result = request.getStringResponse(); + if (request.getStatus() == XmlRpcStatus.Ok) { + if (result.startsWith("ERROR_")) { + Log.e(result); + listener.onError(result); + return; + } + listener.onAccountActivated(result); + } else if (request.getStatus() == XmlRpcStatus.Failed) { + Log.e(result); + listener.onError(result); + } } - listener.onAccountActivated(result); - } else if (request.getStatus() == XmlRpcStatus.Failed) { - Log.e(result); - listener.onError(result); - } - } - }); + }); xmlRpcRequest.addStringArg(username); xmlRpcRequest.addStringArg(password); xmlRpcSession.sendRequest(xmlRpcRequest); } public void isAccountActivatedAsync(final XmlRpcListener listener, String username) { - XmlRpcRequest xmlRpcRequest = xmlRpcSession.createRequest(XmlRpcArgType.String, "check_account_activated"); - xmlRpcRequest.setListener(new XmlRpcRequestListener() { - @Override - public void onResponse(XmlRpcRequest request) { - String result = request.getStringResponse(); - if (request.getStatus() == XmlRpcStatus.Ok) { - if ("OK".equals(result)) { - listener.onAccountActivatedFetched(true); - return; - } else if (!"ERROR_ACCOUNT_NOT_ACTIVATED".equals(result)) { - Log.e(result); - listener.onError(result); + XmlRpcRequest xmlRpcRequest = + xmlRpcSession.createRequest(XmlRpcArgType.String, "check_account_activated"); + xmlRpcRequest.setListener( + new XmlRpcRequestListener() { + @Override + public void onResponse(XmlRpcRequest request) { + String result = request.getStringResponse(); + if (request.getStatus() == XmlRpcStatus.Ok) { + if ("OK".equals(result)) { + listener.onAccountActivatedFetched(true); + return; + } else if (!"ERROR_ACCOUNT_NOT_ACTIVATED".equals(result)) { + Log.e(result); + listener.onError(result); + } + listener.onAccountActivatedFetched(false); + } else if (request.getStatus() == XmlRpcStatus.Failed) { + Log.e(result); + listener.onError(result); + } } - listener.onAccountActivatedFetched(false); - } else if (request.getStatus() == XmlRpcStatus.Failed) { - Log.e(result); - listener.onError(result); - } - } - }); + }); xmlRpcRequest.addStringArg(username); xmlRpcSession.sendRequest(xmlRpcRequest); } - public void isTrialAccountAsync(final XmlRpcListener listener, String username, String password) { - XmlRpcRequest xmlRpcRequest = xmlRpcSession.createRequest(XmlRpcArgType.String, "is_account_trial"); - xmlRpcRequest.setListener(new XmlRpcRequestListener() { - @Override - public void onResponse(XmlRpcRequest request) { - String result = request.getStringResponse(); - if (request.getStatus() == XmlRpcStatus.Ok) { - if (!"NOK".equals(result) && !"OK".equals(result)) { - listener.onError(result); + public void isTrialAccountAsync( + final XmlRpcListener listener, String username, String password) { + XmlRpcRequest xmlRpcRequest = + xmlRpcSession.createRequest(XmlRpcArgType.String, "is_account_trial"); + xmlRpcRequest.setListener( + new XmlRpcRequestListener() { + @Override + public void onResponse(XmlRpcRequest request) { + String result = request.getStringResponse(); + if (request.getStatus() == XmlRpcStatus.Ok) { + if (!"NOK".equals(result) && !"OK".equals(result)) { + listener.onError(result); + } + listener.onTrialAccountFetched("OK".equals(result)); + } else if (request.getStatus() == XmlRpcStatus.Failed) { + Log.e(result); + listener.onError(result); + } } - listener.onTrialAccountFetched("OK".equals(result)); - } else if (request.getStatus() == XmlRpcStatus.Failed) { - Log.e(result); - listener.onError(result); - } - } - }); + }); xmlRpcRequest.addStringArg(username); xmlRpcRequest.addStringArg(password); xmlRpcSession.sendRequest(xmlRpcRequest); } public void isAccountAsync(final XmlRpcListener listener, String username) { - XmlRpcRequest xmlRpcRequest = xmlRpcSession.createRequest(XmlRpcArgType.String, "check_account_activated"); - xmlRpcRequest.setListener(new XmlRpcRequestListener() { - @Override - public void onResponse(XmlRpcRequest request) { - String result = request.getStringResponse(); - if (request.getStatus() == XmlRpcStatus.Ok) { - if ("OK".equals(result)) { - listener.onAccountFetched(true); - return; - } else if (!"ERROR_ACCOUNT_DOESNT_EXIST".equals(result)) { - Log.e(result); - listener.onError(result); + XmlRpcRequest xmlRpcRequest = + xmlRpcSession.createRequest(XmlRpcArgType.String, "check_account_activated"); + xmlRpcRequest.setListener( + new XmlRpcRequestListener() { + @Override + public void onResponse(XmlRpcRequest request) { + String result = request.getStringResponse(); + if (request.getStatus() == XmlRpcStatus.Ok) { + if ("OK".equals(result)) { + listener.onAccountFetched(true); + return; + } else if (!"ERROR_ACCOUNT_DOESNT_EXIST".equals(result)) { + Log.e(result); + listener.onError(result); + } + listener.onAccountFetched(false); + } else if (request.getStatus() == XmlRpcStatus.Failed) { + Log.e(result); + listener.onError(result); + } } - listener.onAccountFetched(false); - } else if (request.getStatus() == XmlRpcStatus.Failed) { - Log.e(result); - listener.onError(result); - } - } - }); + }); xmlRpcRequest.addStringArg(username); xmlRpcSession.sendRequest(xmlRpcRequest); } - public void changeAccountEmailAsync(final XmlRpcListener listener, String username, String password, String newEmail) { - XmlRpcRequest xmlRpcRequest = xmlRpcSession.createRequest(XmlRpcArgType.String, "change_email"); - xmlRpcRequest.setListener(new XmlRpcRequestListener() { - @Override - public void onResponse(XmlRpcRequest request) { - String result = request.getStringResponse(); - if (request.getStatus() == XmlRpcStatus.Ok) { - if (result.startsWith("ERROR_")) { - Log.e(result); - listener.onError(result); - return; - } + public void changeAccountEmailAsync( + final XmlRpcListener listener, String username, String password, String newEmail) { + XmlRpcRequest xmlRpcRequest = + xmlRpcSession.createRequest(XmlRpcArgType.String, "change_email"); + xmlRpcRequest.setListener( + new XmlRpcRequestListener() { + @Override + public void onResponse(XmlRpcRequest request) { + String result = request.getStringResponse(); + if (request.getStatus() == XmlRpcStatus.Ok) { + if (result.startsWith("ERROR_")) { + Log.e(result); + listener.onError(result); + return; + } - listener.onAccountEmailChanged(result); - } else if (request.getStatus() == XmlRpcStatus.Failed) { - Log.e(result); - listener.onError(result); - } - } - }); + listener.onAccountEmailChanged(result); + } else if (request.getStatus() == XmlRpcStatus.Failed) { + Log.e(result); + listener.onError(result); + } + } + }); xmlRpcRequest.addStringArg(username); xmlRpcRequest.addStringArg(password); xmlRpcRequest.addStringArg(newEmail); xmlRpcSession.sendRequest(xmlRpcRequest); } - public void changeAccountPasswordAsync(final XmlRpcListener listener, String username, String oldPassword, String newPassword) { - XmlRpcRequest xmlRpcRequest = xmlRpcSession.createRequest(XmlRpcArgType.String, "change_password"); - xmlRpcRequest.setListener(new XmlRpcRequestListener() { - @Override - public void onResponse(XmlRpcRequest request) { - String result = request.getStringResponse(); - if (request.getStatus() == XmlRpcStatus.Ok) { - if (result.startsWith("ERROR_")) { - Log.e(result); - listener.onError(result); - return; - } + public void changeAccountPasswordAsync( + final XmlRpcListener listener, + String username, + String oldPassword, + String newPassword) { + XmlRpcRequest xmlRpcRequest = + xmlRpcSession.createRequest(XmlRpcArgType.String, "change_password"); + xmlRpcRequest.setListener( + new XmlRpcRequestListener() { + @Override + public void onResponse(XmlRpcRequest request) { + String result = request.getStringResponse(); + if (request.getStatus() == XmlRpcStatus.Ok) { + if (result.startsWith("ERROR_")) { + Log.e(result); + listener.onError(result); + return; + } - listener.onAccountPasswordChanged(result); - } else if (request.getStatus() == XmlRpcStatus.Failed) { - Log.e(result); - listener.onError(result); - } - } - }); + listener.onAccountPasswordChanged(result); + } else if (request.getStatus() == XmlRpcStatus.Failed) { + Log.e(result); + listener.onError(result); + } + } + }); xmlRpcRequest.addStringArg(username); xmlRpcRequest.addStringArg(oldPassword); xmlRpcRequest.addStringArg(newPassword); xmlRpcSession.sendRequest(xmlRpcRequest); } - public void changeAccountHashPasswordAsync(final XmlRpcListener listener, String username, String oldPassword, String newPassword) { - XmlRpcRequest xmlRpcRequest = xmlRpcSession.createRequest(XmlRpcArgType.String, "change_hash"); - xmlRpcRequest.setListener(new XmlRpcRequestListener() { - @Override - public void onResponse(XmlRpcRequest request) { - String result = request.getStringResponse(); - if (request.getStatus() == XmlRpcStatus.Ok) { - if (result.startsWith("ERROR_")) { - Log.e(result); - listener.onError(result); - return; - } + public void changeAccountHashPasswordAsync( + final XmlRpcListener listener, + String username, + String oldPassword, + String newPassword) { + XmlRpcRequest xmlRpcRequest = + xmlRpcSession.createRequest(XmlRpcArgType.String, "change_hash"); + xmlRpcRequest.setListener( + new XmlRpcRequestListener() { + @Override + public void onResponse(XmlRpcRequest request) { + String result = request.getStringResponse(); + if (request.getStatus() == XmlRpcStatus.Ok) { + if (result.startsWith("ERROR_")) { + Log.e(result); + listener.onError(result); + return; + } - listener.onAccountPasswordChanged(result); - } else if (request.getStatus() == XmlRpcStatus.Failed) { - Log.e(result); - listener.onError(result); - } - } - }); + listener.onAccountPasswordChanged(result); + } else if (request.getStatus() == XmlRpcStatus.Failed) { + Log.e(result); + listener.onError(result); + } + } + }); xmlRpcRequest.addStringArg(username); xmlRpcRequest.addStringArg(oldPassword); xmlRpcRequest.addStringArg(newPassword); xmlRpcSession.sendRequest(xmlRpcRequest); } - public void sendRecoverPasswordLinkByEmailAsync(final XmlRpcListener listener, String usernameOrEmail) { - XmlRpcRequest xmlRpcRequest = xmlRpcSession.createRequest(XmlRpcArgType.String, "send_reset_account_password_email"); - xmlRpcRequest.setListener(new XmlRpcRequestListener() { - @Override - public void onResponse(XmlRpcRequest request) { - String result = request.getStringResponse(); - if (request.getStatus() == XmlRpcStatus.Ok) { - if (result.startsWith("ERROR_")) { - Log.e(result); - listener.onError(result); - return; - } + public void sendRecoverPasswordLinkByEmailAsync( + final XmlRpcListener listener, String usernameOrEmail) { + XmlRpcRequest xmlRpcRequest = + xmlRpcSession.createRequest( + XmlRpcArgType.String, "send_reset_account_password_email"); + xmlRpcRequest.setListener( + new XmlRpcRequestListener() { + @Override + public void onResponse(XmlRpcRequest request) { + String result = request.getStringResponse(); + if (request.getStatus() == XmlRpcStatus.Ok) { + if (result.startsWith("ERROR_")) { + Log.e(result); + listener.onError(result); + return; + } - listener.onRecoverPasswordLinkSent(result); - } else if (request.getStatus() == XmlRpcStatus.Failed) { - Log.e(result); - listener.onError(result); - } - } - }); + listener.onRecoverPasswordLinkSent(result); + } else if (request.getStatus() == XmlRpcStatus.Failed) { + Log.e(result); + listener.onError(result); + } + } + }); xmlRpcRequest.addStringArg(usernameOrEmail); xmlRpcSession.sendRequest(xmlRpcRequest); } - public void sendActivateAccountLinkByEmailAsync(final XmlRpcListener listener, String usernameOrEmail) { - XmlRpcRequest xmlRpcRequest = xmlRpcSession.createRequest(XmlRpcArgType.String, "resend_activation_email"); - xmlRpcRequest.setListener(new XmlRpcRequestListener() { - @Override - public void onResponse(XmlRpcRequest request) { - String result = request.getStringResponse(); - if (request.getStatus() == XmlRpcStatus.Ok) { - if (result.startsWith("ERROR_")) { - Log.e(result); - listener.onError(result); - return; - } + public void sendActivateAccountLinkByEmailAsync( + final XmlRpcListener listener, String usernameOrEmail) { + XmlRpcRequest xmlRpcRequest = + xmlRpcSession.createRequest(XmlRpcArgType.String, "resend_activation_email"); + xmlRpcRequest.setListener( + new XmlRpcRequestListener() { + @Override + public void onResponse(XmlRpcRequest request) { + String result = request.getStringResponse(); + if (request.getStatus() == XmlRpcStatus.Ok) { + if (result.startsWith("ERROR_")) { + Log.e(result); + listener.onError(result); + return; + } - listener.onActivateAccountLinkSent(result); - } else if (request.getStatus() == XmlRpcStatus.Failed) { - Log.e(result); - listener.onError(result); - } - } - }); + listener.onActivateAccountLinkSent(result); + } else if (request.getStatus() == XmlRpcStatus.Failed) { + Log.e(result); + listener.onError(result); + } + } + }); xmlRpcRequest.addStringArg(usernameOrEmail); xmlRpcSession.sendRequest(xmlRpcRequest); } public void sendUsernameByEmailAsync(final XmlRpcListener listener, String email) { - XmlRpcRequest xmlRpcRequest = xmlRpcSession.createRequest(XmlRpcArgType.String, "recover_username_from_email"); - xmlRpcRequest.setListener(new XmlRpcRequestListener() { - @Override - public void onResponse(XmlRpcRequest request) { - String result = request.getStringResponse(); - if (request.getStatus() == XmlRpcStatus.Ok) { - if (result.startsWith("ERROR_")) { - Log.e(result); - listener.onError(result); - return; - } + XmlRpcRequest xmlRpcRequest = + xmlRpcSession.createRequest(XmlRpcArgType.String, "recover_username_from_email"); + xmlRpcRequest.setListener( + new XmlRpcRequestListener() { + @Override + public void onResponse(XmlRpcRequest request) { + String result = request.getStringResponse(); + if (request.getStatus() == XmlRpcStatus.Ok) { + if (result.startsWith("ERROR_")) { + Log.e(result); + listener.onError(result); + return; + } - listener.onUsernameSent(result); - } else if (request.getStatus() == XmlRpcStatus.Failed) { - Log.e(result); - listener.onError(result); - } - } - }); + listener.onUsernameSent(result); + } else if (request.getStatus() == XmlRpcStatus.Failed) { + Log.e(result); + listener.onError(result); + } + } + }); xmlRpcRequest.addStringArg(email); xmlRpcSession.sendRequest(xmlRpcRequest); } - public void verifySignatureAsync(final XmlRpcListener listener, String payload, String signature) { - XmlRpcRequest xmlRpcRequest = xmlRpcSession.createRequest(XmlRpcArgType.String, "check_payload_signature"); - xmlRpcRequest.setListener(new XmlRpcRequestListener() { - @Override - public void onResponse(XmlRpcRequest request) { - String result = request.getStringResponse(); - if (request.getStatus() == XmlRpcStatus.Ok) { - Log.w(result); - if (result.startsWith("ERROR_")) { - Log.e(result); - listener.onError(result); - return; - } + public void verifySignatureAsync( + final XmlRpcListener listener, String payload, String signature) { + XmlRpcRequest xmlRpcRequest = + xmlRpcSession.createRequest(XmlRpcArgType.String, "check_payload_signature"); + xmlRpcRequest.setListener( + new XmlRpcRequestListener() { + @Override + public void onResponse(XmlRpcRequest request) { + String result = request.getStringResponse(); + if (request.getStatus() == XmlRpcStatus.Ok) { + Log.w(result); + if (result.startsWith("ERROR_")) { + Log.e(result); + listener.onError(result); + return; + } - listener.onSignatureVerified("OK".equals(result)); - } else if (request.getStatus() == XmlRpcStatus.Failed) { - Log.e(result); - listener.onError(result); - } - } - }); + listener.onSignatureVerified("OK".equals(result)); + } else if (request.getStatus() == XmlRpcStatus.Failed) { + Log.e(result); + listener.onError(result); + } + } + }); xmlRpcRequest.addStringArg(payload); xmlRpcRequest.addStringArg(signature); xmlRpcSession.sendRequest(xmlRpcRequest); } - public void getRemoteProvisioningFilenameAsync(final XmlRpcListener listener, String username, String domain, String password) { - XmlRpcRequest xmlRpcRequest = xmlRpcSession.createRequest(XmlRpcArgType.String, "get_remote_provisioning_filename"); - xmlRpcRequest.setListener(new XmlRpcRequestListener() { - @Override - public void onResponse(XmlRpcRequest request) { - String result = request.getStringResponse(); - if (request.getStatus() == XmlRpcStatus.Ok) { - if (result.startsWith("ERROR_")) { - Log.e(result); - listener.onError(result); - return; - } + public void getRemoteProvisioningFilenameAsync( + final XmlRpcListener listener, String username, String domain, String password) { + XmlRpcRequest xmlRpcRequest = + xmlRpcSession.createRequest( + XmlRpcArgType.String, "get_remote_provisioning_filename"); + xmlRpcRequest.setListener( + new XmlRpcRequestListener() { + @Override + public void onResponse(XmlRpcRequest request) { + String result = request.getStringResponse(); + if (request.getStatus() == XmlRpcStatus.Ok) { + if (result.startsWith("ERROR_")) { + Log.e(result); + listener.onError(result); + return; + } - listener.onRemoteProvisioningFilenameSent(result); - } else if (request.getStatus() == XmlRpcStatus.Failed) { - Log.e(result); - listener.onError(result); - } - } - }); + listener.onRemoteProvisioningFilenameSent(result); + } else if (request.getStatus() == XmlRpcStatus.Failed) { + Log.e(result); + listener.onError(result); + } + } + }); xmlRpcRequest.addStringArg(username); xmlRpcRequest.addStringArg(domain); xmlRpcRequest.addStringArg(password); diff --git a/app/src/main/res/anim/slide_in_bottom_to_top.xml b/app/src/main/res/anim/slide_in_bottom_to_top.xml index 1cc55f9ab..f7bb0ec08 100644 --- a/app/src/main/res/anim/slide_in_bottom_to_top.xml +++ b/app/src/main/res/anim/slide_in_bottom_to_top.xml @@ -1,8 +1,10 @@ - + android:shareInterpolator="false"> + \ No newline at end of file diff --git a/app/src/main/res/anim/slide_in_left_to_right.xml b/app/src/main/res/anim/slide_in_left_to_right.xml index 490677824..d57afb2b5 100644 --- a/app/src/main/res/anim/slide_in_left_to_right.xml +++ b/app/src/main/res/anim/slide_in_left_to_right.xml @@ -1,8 +1,10 @@ - + android:shareInterpolator="false"> + \ No newline at end of file diff --git a/app/src/main/res/anim/slide_in_right_to_left.xml b/app/src/main/res/anim/slide_in_right_to_left.xml index bf15b1e13..47fd9ee8a 100644 --- a/app/src/main/res/anim/slide_in_right_to_left.xml +++ b/app/src/main/res/anim/slide_in_right_to_left.xml @@ -1,8 +1,10 @@ - + android:shareInterpolator="false"> + \ No newline at end of file diff --git a/app/src/main/res/anim/slide_in_top_to_bottom.xml b/app/src/main/res/anim/slide_in_top_to_bottom.xml index 6bb7ac339..b928aabfa 100644 --- a/app/src/main/res/anim/slide_in_top_to_bottom.xml +++ b/app/src/main/res/anim/slide_in_top_to_bottom.xml @@ -1,8 +1,10 @@ - + android:shareInterpolator="false"> + \ No newline at end of file diff --git a/app/src/main/res/anim/slide_out_bottom_to_top.xml b/app/src/main/res/anim/slide_out_bottom_to_top.xml index 5db6fd044..190217cd8 100644 --- a/app/src/main/res/anim/slide_out_bottom_to_top.xml +++ b/app/src/main/res/anim/slide_out_bottom_to_top.xml @@ -1,8 +1,10 @@ - + android:shareInterpolator="false"> + \ No newline at end of file diff --git a/app/src/main/res/anim/slide_out_left_to_right.xml b/app/src/main/res/anim/slide_out_left_to_right.xml index a18fc009b..fd1dae982 100644 --- a/app/src/main/res/anim/slide_out_left_to_right.xml +++ b/app/src/main/res/anim/slide_out_left_to_right.xml @@ -1,8 +1,10 @@ + android:shareInterpolator="false"> + android:duration="350" + android:fromXDelta="0%" + android:fromYDelta="0%" + android:toXDelta="100%" + android:toYDelta="0%" /> \ No newline at end of file diff --git a/app/src/main/res/anim/slide_out_right_to_left.xml b/app/src/main/res/anim/slide_out_right_to_left.xml index 4866f0a2d..2f19c3f6f 100644 --- a/app/src/main/res/anim/slide_out_right_to_left.xml +++ b/app/src/main/res/anim/slide_out_right_to_left.xml @@ -1,8 +1,10 @@ + android:shareInterpolator="false"> + android:duration="350" + android:fromXDelta="0%" + android:fromYDelta="0%" + android:toXDelta="-100%" + android:toYDelta="0%" /> \ No newline at end of file diff --git a/app/src/main/res/anim/slide_out_top_to_bottom.xml b/app/src/main/res/anim/slide_out_top_to_bottom.xml index ad6838797..fdfe2a714 100644 --- a/app/src/main/res/anim/slide_out_top_to_bottom.xml +++ b/app/src/main/res/anim/slide_out_top_to_bottom.xml @@ -1,8 +1,10 @@ - + android:shareInterpolator="false"> + \ No newline at end of file diff --git a/app/src/main/res/color/security_switch_track_color.xml b/app/src/main/res/color/security_switch_track_color.xml index abf1d92f8..1adc098ec 100644 --- a/app/src/main/res/color/security_switch_track_color.xml +++ b/app/src/main/res/color/security_switch_track_color.xml @@ -1,8 +1,6 @@ - - + + \ No newline at end of file diff --git a/app/src/main/res/drawable/call.xml b/app/src/main/res/drawable/call.xml index 7564861e6..d664e9a76 100644 --- a/app/src/main/res/drawable/call.xml +++ b/app/src/main/res/drawable/call.xml @@ -1,10 +1,7 @@ - - - + + + diff --git a/app/src/main/res/drawable/camera.xml b/app/src/main/res/drawable/camera.xml index 505527444..cedc0ed7f 100644 --- a/app/src/main/res/drawable/camera.xml +++ b/app/src/main/res/drawable/camera.xml @@ -1,9 +1,6 @@ - - - + + + diff --git a/app/src/main/res/drawable/chat.xml b/app/src/main/res/drawable/chat.xml index 5bdf45573..525c33507 100644 --- a/app/src/main/res/drawable/chat.xml +++ b/app/src/main/res/drawable/chat.xml @@ -1,9 +1,6 @@ - - - + + + diff --git a/app/src/main/res/drawable/delete.xml b/app/src/main/res/drawable/delete.xml index fc8292837..a7d8a0b2f 100644 --- a/app/src/main/res/drawable/delete.xml +++ b/app/src/main/res/drawable/delete.xml @@ -1,7 +1,5 @@ - - + + diff --git a/app/src/main/res/drawable/dialer.xml b/app/src/main/res/drawable/dialer.xml index cae05314b..525c33507 100644 --- a/app/src/main/res/drawable/dialer.xml +++ b/app/src/main/res/drawable/dialer.xml @@ -1,9 +1,6 @@ - - - + + + diff --git a/app/src/main/res/drawable/hangup.xml b/app/src/main/res/drawable/hangup.xml index 3a15ca838..6f845127d 100644 --- a/app/src/main/res/drawable/hangup.xml +++ b/app/src/main/res/drawable/hangup.xml @@ -1,10 +1,7 @@ - - - + + + diff --git a/app/src/main/res/drawable/menu.xml b/app/src/main/res/drawable/menu.xml index 4e9c8df94..34af69cdb 100644 --- a/app/src/main/res/drawable/menu.xml +++ b/app/src/main/res/drawable/menu.xml @@ -1,7 +1,5 @@ - - + + diff --git a/app/src/main/res/drawable/micro.xml b/app/src/main/res/drawable/micro.xml index 8570c32c3..7cc575277 100644 --- a/app/src/main/res/drawable/micro.xml +++ b/app/src/main/res/drawable/micro.xml @@ -1,7 +1,5 @@ - - + + diff --git a/app/src/main/res/drawable/options.xml b/app/src/main/res/drawable/options.xml index 863f137ac..0d23abd97 100644 --- a/app/src/main/res/drawable/options.xml +++ b/app/src/main/res/drawable/options.xml @@ -1,7 +1,5 @@ - - + + diff --git a/app/src/main/res/drawable/pause.xml b/app/src/main/res/drawable/pause.xml index e472ae14a..debf5030c 100644 --- a/app/src/main/res/drawable/pause.xml +++ b/app/src/main/res/drawable/pause.xml @@ -1,12 +1,8 @@ - - - - + + + + diff --git a/app/src/main/res/drawable/quit.xml b/app/src/main/res/drawable/quit.xml index f85f9638b..2369f4f01 100644 --- a/app/src/main/res/drawable/quit.xml +++ b/app/src/main/res/drawable/quit.xml @@ -1,7 +1,5 @@ - - + + diff --git a/app/src/main/res/drawable/routes.xml b/app/src/main/res/drawable/routes.xml index c86f360e4..ce4245e08 100644 --- a/app/src/main/res/drawable/routes.xml +++ b/app/src/main/res/drawable/routes.xml @@ -1,7 +1,5 @@ - - + + diff --git a/app/src/main/res/drawable/speaker.xml b/app/src/main/res/drawable/speaker.xml index ec5f9c595..0ccd6e57f 100644 --- a/app/src/main/res/drawable/speaker.xml +++ b/app/src/main/res/drawable/speaker.xml @@ -1,7 +1,7 @@ - + diff --git a/app/src/main/res/drawable/valid.xml b/app/src/main/res/drawable/valid.xml index 4ad5c5858..270d62b41 100644 --- a/app/src/main/res/drawable/valid.xml +++ b/app/src/main/res/drawable/valid.xml @@ -1,7 +1,5 @@ - - + + diff --git a/app/src/main/res/layout-land/about.xml b/app/src/main/res/layout-land/about.xml index 05198177f..1434003f1 100644 --- a/app/src/main/res/layout-land/about.xml +++ b/app/src/main/res/layout-land/about.xml @@ -5,130 +5,130 @@ android:orientation="vertical"> + android:layout_gravity="center" + android:layout_weight="1" + android:background="@color/colorC" + android:baselineAligned="false" + android:orientation="horizontal"> + android:orientation="vertical"> + android:layout_gravity="center" + android:src="@drawable/splashscreen" /> + android:layout_gravity="center" + android:paddingTop="5dp" + android:text="@string/app_name" + android:visibility="gone" /> + android:layout_gravity="center" + android:text="@string/app_description" /> + android:orientation="vertical"> + android:layout_height="wrap_content" + android:layout_gravity="left" + android:text="@string/about_version" /> + android:layout_height="wrap_content" + android:layout_gravity="left" + android:text="@string/about_liblinphone_version" /> + android:background="@color/colorH" + android:orientation="vertical" + android:padding="10dp"> + android:layout_height="wrap_content" + android:layout_gravity="center" + android:autoLink="web" + android:gravity="center" + android:text="@string/about_link" + android:textColorLink="@color/colorA" /> + android:text="@string/about_text" + android:textSize="18sp" /> + android:layout_height="1dp" + android:background="@color/colorE" /> + android:layout_gravity="center" + android:orientation="horizontal"> + android:layout_width="fill_parent" + android:layout_height="fill_parent" + android:orientation="vertical"> - - - + + + + + + + + + + + + - - - - + diff --git a/app/src/main/res/layout/hidden.xml b/app/src/main/res/layout/hidden.xml index 28b0414e0..e14c67df5 100644 --- a/app/src/main/res/layout/hidden.xml +++ b/app/src/main/res/layout/hidden.xml @@ -1,4 +1,5 @@ - + android:layout_width="fill_parent" + android:layout_height="fill_parent" + android:visibility="gone"> diff --git a/app/src/main/res/layout/history.xml b/app/src/main/res/layout/history.xml index f7825f9b2..533dd52fe 100644 --- a/app/src/main/res/layout/history.xml +++ b/app/src/main/res/layout/history.xml @@ -1,8 +1,8 @@ + android:layout_width="match_parent" + android:layout_height="match_parent" + android:background="@color/colorH"> + android:layout_height="60dp" + android:background="@color/colorF" + android:orientation="horizontal"> + android:src="@drawable/history_all" /> + android:layout_alignParentBottom="true" + android:background="@color/colorA" /> + android:src="@drawable/history_missed" /> + android:layout_alignParentBottom="true" + android:background="@color/colorA" + android:visibility="gone" /> + android:layout_weight="0.4" /> + android:background="@drawable/toolbar_button" + android:contentDescription="@string/content_description_edit_list" + android:padding="15dp" + android:src="@drawable/delete" /> - + - + - + diff --git a/app/src/main/res/layout/history_cell.xml b/app/src/main/res/layout/history_cell.xml index 9081e91ca..b40ff88f5 100644 --- a/app/src/main/res/layout/history_cell.xml +++ b/app/src/main/res/layout/history_cell.xml @@ -1,103 +1,103 @@ + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:background="@color/colorH" + android:gravity="center_vertical" + android:orientation="vertical"> - + - + - + - + - + - + - + - + - + - + - + - + - - + + - + \ No newline at end of file diff --git a/app/src/main/res/layout/history_detail.xml b/app/src/main/res/layout/history_detail.xml index 0a682c071..a7960f5b0 100644 --- a/app/src/main/res/layout/history_detail.xml +++ b/app/src/main/res/layout/history_detail.xml @@ -4,53 +4,53 @@ android:layout_height="match_parent"> + android:background="@color/colorH" + android:orientation="vertical"> + android:layout_height="60dp" + android:background="@color/colorF" + android:orientation="horizontal"> + android:background="@drawable/toolbar_button" + android:contentDescription="@string/content_description_back" + android:padding="18dp" + android:src="@drawable/back" /> + android:layout_weight="0.6" /> + android:background="@drawable/toolbar_button" + android:contentDescription="@string/content_description_add_contact" + android:padding="15dp" + android:src="@drawable/contact_add" /> + android:background="@drawable/toolbar_button" + android:contentDescription="@string/content_description_contacts" + android:padding="15dp" + android:src="@drawable/contact" + android:visibility="gone" /> + android:orientation="vertical" + android:padding="20dp"> + android:layout_height="100dp" + android:contentDescription="@string/content_description_contact_picture" + android:src="@drawable/avatar" /> + android:layout_height="100dp" + android:src="@drawable/avatar_mask" /> + android:layout_height="wrap_content" + android:gravity="center_horizontal" /> + android:layout_height="wrap_content" /> + android:layout_margin="10dp" + android:background="@drawable/round_orange_button_background" + android:contentDescription="@string/content_description_call" + android:src="@drawable/call_start_default" /> + android:layout_margin="10dp" + android:background="@drawable/round_orange_button_background" + android:contentDescription="@string/content_description_chat" + android:src="@drawable/chat_start_default" /> @@ -131,45 +131,45 @@ android:orientation="vertical"> + android:layout_height="1dp" + android:background="@color/colorE" /> + android:layout_height="wrap_content" + android:layout_gravity="center" + android:layout_marginTop="2dp" + android:text="@string/call" + android:textAllCaps="true" /> + android:layout_height="wrap_content" + android:paddingLeft="10dp" + android:paddingRight="10dp" /> + android:layout_height="wrap_content" + android:paddingRight="10dp" /> + android:layout_height="wrap_content" /> @@ -181,6 +181,8 @@ - + \ No newline at end of file diff --git a/app/src/main/res/layout/image_upload_cell.xml b/app/src/main/res/layout/image_upload_cell.xml index 01fe3e63e..ba0d30e4a 100644 --- a/app/src/main/res/layout/image_upload_cell.xml +++ b/app/src/main/res/layout/image_upload_cell.xml @@ -7,16 +7,16 @@ + android:layout_height="match_parent" + android:adjustViewBounds="true" /> + android:src="@drawable/clean_field" /> \ No newline at end of file diff --git a/app/src/main/res/layout/in_app.xml b/app/src/main/res/layout/in_app.xml index 64e33a927..78f937b03 100644 --- a/app/src/main/res/layout/in_app.xml +++ b/app/src/main/res/layout/in_app.xml @@ -1,70 +1,70 @@ + xmlns:tools="http://schemas.android.com/tools" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:background="@color/colorH" + android:orientation="vertical"> - + - + - + - + - - + + - + - + diff --git a/app/src/main/res/layout/in_app_list.xml b/app/src/main/res/layout/in_app_list.xml index d4f95743a..c927fb700 100644 --- a/app/src/main/res/layout/in_app_list.xml +++ b/app/src/main/res/layout/in_app_list.xml @@ -1,16 +1,15 @@ - + - + \ No newline at end of file diff --git a/app/src/main/res/layout/in_app_purchase_item.xml b/app/src/main/res/layout/in_app_purchase_item.xml index f9ca899c3..0e026a0d1 100644 --- a/app/src/main/res/layout/in_app_purchase_item.xml +++ b/app/src/main/res/layout/in_app_purchase_item.xml @@ -1,49 +1,48 @@ - + - + - + - + - + - + - + \ No newline at end of file diff --git a/app/src/main/res/layout/in_app_store.xml b/app/src/main/res/layout/in_app_store.xml index 573d25a52..aeed49f85 100644 --- a/app/src/main/res/layout/in_app_store.xml +++ b/app/src/main/res/layout/in_app_store.xml @@ -1,89 +1,89 @@ + android:background="@color/colorH" + android:orientation="vertical"> + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:gravity="center" + android:orientation="vertical" + android:padding="30dp"> - + - + - + - + - + - + - + - + -