diff --git a/src/android/support/v7/mms/DefaultApnSettingsLoader.java b/src/android/support/v7/mms/DefaultApnSettingsLoader.java index 2721ee1..0a91e85 100644 --- a/src/android/support/v7/mms/DefaultApnSettingsLoader.java +++ b/src/android/support/v7/mms/DefaultApnSettingsLoader.java @@ -17,7 +17,6 @@ package android.support.v7.mms; -import android.content.ContentValues; import android.content.Context; import android.content.res.Resources; import android.content.res.XmlResourceParser; @@ -403,28 +402,25 @@ class DefaultApnSettingsLoader implements ApnSettingsLoader { XmlResourceParser xml = null; try { xml = mContext.getResources().getXml(R.xml.apns); - new ApnsXmlParser(xml, new ApnsXmlParser.ApnProcessor() { - @Override - public void process(ContentValues apnValues) { - final String mcc = trimWithNullCheck(apnValues.getAsString(APN_MCC)); - final String mnc = trimWithNullCheck(apnValues.getAsString(APN_MNC)); - final String apn = trimWithNullCheck(apnValues.getAsString(APN_APN)); - try { - if (mccMnc[0] == Integer.parseInt(mcc) && - mccMnc[1] == Integer.parseInt(mnc) && - (TextUtils.isEmpty(apnName) || apnName.equalsIgnoreCase(apn))) { - final String type = apnValues.getAsString(APN_TYPE); - final String mmsc = apnValues.getAsString(APN_MMSC); - final String mmsproxy = apnValues.getAsString(APN_MMSPROXY); - final String mmsport = apnValues.getAsString(APN_MMSPORT); - final Apn newApn = MemoryApn.from(apns, type, mmsc, mmsproxy, mmsport); - if (newApn != null) { - apns.add(newApn); - } + new ApnsXmlParser(xml, apnValues -> { + final String mcc = trimWithNullCheck(apnValues.getAsString(APN_MCC)); + final String mnc = trimWithNullCheck(apnValues.getAsString(APN_MNC)); + final String apn = trimWithNullCheck(apnValues.getAsString(APN_APN)); + try { + if (mccMnc[0] == Integer.parseInt(mcc) && + mccMnc[1] == Integer.parseInt(mnc) && + (TextUtils.isEmpty(apnName) || apnName.equalsIgnoreCase(apn))) { + final String type = apnValues.getAsString(APN_TYPE); + final String mmsc = apnValues.getAsString(APN_MMSC); + final String mmsproxy = apnValues.getAsString(APN_MMSPROXY); + final String mmsport = apnValues.getAsString(APN_MMSPORT); + final Apn newApn = MemoryApn.from(apns, type, mmsc, mmsproxy, mmsport); + if (newApn != null) { + apns.add(newApn); } - } catch (final NumberFormatException e) { - // Ignore } + } catch (final NumberFormatException e) { + // Ignore } }).parse(); } catch (final Resources.NotFoundException e) { diff --git a/src/android/support/v7/mms/DefaultCarrierConfigValuesLoader.java b/src/android/support/v7/mms/DefaultCarrierConfigValuesLoader.java index 2deef9d..f3f263b 100644 --- a/src/android/support/v7/mms/DefaultCarrierConfigValuesLoader.java +++ b/src/android/support/v7/mms/DefaultCarrierConfigValuesLoader.java @@ -95,21 +95,18 @@ class DefaultCarrierConfigValuesLoader implements CarrierConfigValuesLoader { XmlResourceParser xml = null; try { xml = subContext.getResources().getXml(R.xml.mms_config); - new CarrierConfigXmlParser(xml, new CarrierConfigXmlParser.KeyValueProcessor() { - @Override - public void process(String type, String key, String value) { - try { - if (KEY_TYPE_INT.equals(type)) { - values.putInt(key, Integer.parseInt(value)); - } else if (KEY_TYPE_BOOL.equals(type)) { - values.putBoolean(key, Boolean.parseBoolean(value)); - } else if (KEY_TYPE_STRING.equals(type)) { - values.putString(key, value); - } - } catch (final NumberFormatException e) { - Log.w(MmsService.TAG, "Load carrier value from resources: " - + "invalid " + key + "," + value + "," + type); + new CarrierConfigXmlParser(xml, (type, key, value) -> { + try { + if (KEY_TYPE_INT.equals(type)) { + values.putInt(key, Integer.parseInt(value)); + } else if (KEY_TYPE_BOOL.equals(type)) { + values.putBoolean(key, Boolean.parseBoolean(value)); + } else if (KEY_TYPE_STRING.equals(type)) { + values.putString(key, value); } + } catch (final NumberFormatException e) { + Log.w(MmsService.TAG, "Load carrier value from resources: " + + "invalid " + key + "," + value + "," + type); } }).parse(); } catch (final Resources.NotFoundException e) { diff --git a/src/android/support/v7/mms/DownloadRequest.java b/src/android/support/v7/mms/DownloadRequest.java index a71bc55..7c6ad86 100644 --- a/src/android/support/v7/mms/DownloadRequest.java +++ b/src/android/support/v7/mms/DownloadRequest.java @@ -82,25 +82,23 @@ class DownloadRequest extends MmsRequest { if (contentUri == null || pdu == null) { return false; } - final Callable copyDownloadedPduToOutput = new Callable() { - public Boolean call() { - ParcelFileDescriptor.AutoCloseOutputStream outStream = null; - try { - final ContentResolver cr = context.getContentResolver(); - final ParcelFileDescriptor pduFd = cr.openFileDescriptor(contentUri, "w"); - outStream = new ParcelFileDescriptor.AutoCloseOutputStream(pduFd); - outStream.write(pdu); - return true; - } catch (IOException e) { - Log.e(MmsService.TAG, "Writing PDU to downloader: IO exception", e); - return false; - } finally { - if (outStream != null) { - try { - outStream.close(); - } catch (IOException ex) { - // Ignore - } + final Callable copyDownloadedPduToOutput = () -> { + ParcelFileDescriptor.AutoCloseOutputStream outStream = null; + try { + final ContentResolver cr = context.getContentResolver(); + final ParcelFileDescriptor pduFd = cr.openFileDescriptor(contentUri, "w"); + outStream = new ParcelFileDescriptor.AutoCloseOutputStream(pduFd); + outStream.write(pdu); + return true; + } catch (IOException e) { + Log.e(MmsService.TAG, "Writing PDU to downloader: IO exception", e); + return false; + } finally { + if (outStream != null) { + try { + outStream.close(); + } catch (IOException ex) { + // Ignore } } } diff --git a/src/android/support/v7/mms/MmsService.java b/src/android/support/v7/mms/MmsService.java index 5330e08..0a14de1 100644 --- a/src/android/support/v7/mms/MmsService.java +++ b/src/android/support/v7/mms/MmsService.java @@ -251,12 +251,7 @@ public class MmsService extends Service { // Handler for scheduling service stop private final Handler mHandler = new Handler(); // Service stop task - private final Runnable mServiceStopRunnable = new Runnable() { - @Override - public void run() { - tryStopService(); - } - }; + private final Runnable mServiceStopRunnable = this::tryStopService; /** * Start the service with a request @@ -325,24 +320,21 @@ public class MmsService extends Service { final MmsRequest request = intent.getParcelableExtra(EXTRA_REQUEST); if (request != null) { try { - retainService(request, new Runnable() { - @Override - public void run() { - try { - request.execute( - MmsService.this, - mNetworkManager, - getApnSettingsLoader(), - getCarrierConfigValuesLoader(), - getUserAgentInfoLoader()); - } catch (Exception e) { - Log.w(TAG, "Unexpected execution failure", e); - } finally { - if (request.getUseWakeLock()) { - releaseWakeLock(); - } - releaseService(); + retainService(request, () -> { + try { + request.execute( + MmsService.this, + mNetworkManager, + getApnSettingsLoader(), + getCarrierConfigValuesLoader(), + getUserAgentInfoLoader()); + } catch (Exception e) { + Log.w(TAG, "Unexpected execution failure", e); + } finally { + if (request.getUseWakeLock()) { + releaseWakeLock(); } + releaseService(); } }); scheduled = true; diff --git a/src/android/support/v7/mms/SendRequest.java b/src/android/support/v7/mms/SendRequest.java index 14723be..3e498a3 100644 --- a/src/android/support/v7/mms/SendRequest.java +++ b/src/android/support/v7/mms/SendRequest.java @@ -101,38 +101,36 @@ class SendRequest extends MmsRequest { if (contentUri == null) { return null; } - final Callable copyPduToArray = new Callable() { - public byte[] call() { - ParcelFileDescriptor.AutoCloseInputStream inStream = null; - try { - final ContentResolver cr = context.getContentResolver(); - final ParcelFileDescriptor pduFd = cr.openFileDescriptor(contentUri, "r"); - inStream = new ParcelFileDescriptor.AutoCloseInputStream(pduFd); - // Request one extra byte to make sure file not bigger than maxSize - final byte[] readBuf = new byte[maxSize+1]; - final int bytesRead = inStream.read(readBuf, 0, maxSize+1); - if (bytesRead <= 0) { - Log.e(MmsService.TAG, "Reading PDU from sender: empty PDU"); - return null; - } - if (bytesRead > maxSize) { - Log.e(MmsService.TAG, "Reading PDU from sender: PDU too large"); - return null; - } - // Copy and return the exact length of bytes - final byte[] result = new byte[bytesRead]; - System.arraycopy(readBuf, 0, result, 0, bytesRead); - return result; - } catch (IOException e) { - Log.e(MmsService.TAG, "Reading PDU from sender: IO exception", e); + final Callable copyPduToArray = () -> { + ParcelFileDescriptor.AutoCloseInputStream inStream = null; + try { + final ContentResolver cr = context.getContentResolver(); + final ParcelFileDescriptor pduFd = cr.openFileDescriptor(contentUri, "r"); + inStream = new ParcelFileDescriptor.AutoCloseInputStream(pduFd); + // Request one extra byte to make sure file not bigger than maxSize + final byte[] readBuf = new byte[maxSize+1]; + final int bytesRead = inStream.read(readBuf, 0, maxSize+1); + if (bytesRead <= 0) { + Log.e(MmsService.TAG, "Reading PDU from sender: empty PDU"); return null; - } finally { - if (inStream != null) { - try { - inStream.close(); - } catch (IOException ex) { - // Ignore - } + } + if (bytesRead > maxSize) { + Log.e(MmsService.TAG, "Reading PDU from sender: PDU too large"); + return null; + } + // Copy and return the exact length of bytes + final byte[] result = new byte[bytesRead]; + System.arraycopy(readBuf, 0, result, 0, bytesRead); + return result; + } catch (IOException e) { + Log.e(MmsService.TAG, "Reading PDU from sender: IO exception", e); + return null; + } finally { + if (inStream != null) { + try { + inStream.close(); + } catch (IOException ex) { + // Ignore } } } diff --git a/src/com/android/messaging/BugleApplication.java b/src/com/android/messaging/BugleApplication.java index a699c9d..7d1f7e0 100644 --- a/src/com/android/messaging/BugleApplication.java +++ b/src/com/android/messaging/BugleApplication.java @@ -127,14 +127,10 @@ public class BugleApplication extends Application implements UncaughtExceptionHa MmsManager.setForceLegacyMms(!bugleGservices.getBoolean( BugleGservicesKeys.USE_MMS_API_IF_PRESENT, BugleGservicesKeys.USE_MMS_API_IF_PRESENT_DEFAULT)); - bugleGservices.registerForChanges(new Runnable() { - @Override - public void run() { - MmsManager.setForceLegacyMms(!bugleGservices.getBoolean( + bugleGservices.registerForChanges(() -> MmsManager.setForceLegacyMms( + !bugleGservices.getBoolean( BugleGservicesKeys.USE_MMS_API_IF_PRESENT, - BugleGservicesKeys.USE_MMS_API_IF_PRESENT_DEFAULT)); - } - }); + BugleGservicesKeys.USE_MMS_API_IF_PRESENT_DEFAULT))); } public static void updateAppConfig(final Context context) { @@ -168,13 +164,7 @@ public class BugleApplication extends Application implements UncaughtExceptionHa LogUtil.e(TAG, "Uncaught exception in background thread " + thread, ex); final Handler handler = new Handler(getMainLooper()); - handler.post(new Runnable() { - - @Override - public void run() { - sSystemUncaughtExceptionHandler.uncaughtException(thread, ex); - } - }); + handler.post(() -> sSystemUncaughtExceptionHandler.uncaughtException(thread, ex)); } else { sSystemUncaughtExceptionHandler.uncaughtException(thread, ex); } @@ -192,17 +182,13 @@ public class BugleApplication extends Application implements UncaughtExceptionHa final File file = DebugUtils.getDebugFile("startup.trace", true); if (file != null) { android.os.Debug.startMethodTracing(file.getAbsolutePath(), 160 * 1024 * 1024); - new Handler(Looper.getMainLooper()).postDelayed( - new Runnable() { - @Override - public void run() { - android.os.Debug.stopMethodTracing(); - // Allow world to see trace file - DebugUtils.ensureReadable(file); - LogUtil.d(LogUtil.PROFILE_TAG, "Tracing complete - " - + file.getAbsolutePath()); - } - }, 30000); + new Handler(Looper.getMainLooper()).postDelayed(() -> { + android.os.Debug.stopMethodTracing(); + // Allow world to see trace file + DebugUtils.ensureReadable(file); + LogUtil.d(LogUtil.PROFILE_TAG, "Tracing complete - " + + file.getAbsolutePath()); + }, 30000); } } } @@ -219,13 +205,8 @@ public class BugleApplication extends Application implements UncaughtExceptionHa // Perform upgrade on application-wide prefs. factory.getApplicationPrefs().onUpgrade(existingVersion, targetVersion); // Perform upgrade on each subscription's prefs. - PhoneUtils.forEachActiveSubscription(new PhoneUtils.SubscriptionRunnable() { - @Override - public void runForSubscription(final int subId) { - factory.getSubscriptionPrefs(subId) - .onUpgrade(existingVersion, targetVersion); - } - }); + PhoneUtils.forEachActiveSubscription(subId -> factory.getSubscriptionPrefs(subId) + .onUpgrade(existingVersion, targetVersion)); factory.getApplicationPrefs().putInt(BuglePrefsKeys.SHARED_PREFERENCES_VERSION, targetVersion); } catch (final Exception ex) { diff --git a/src/com/android/messaging/FactoryImpl.java b/src/com/android/messaging/FactoryImpl.java index 5048b06..7901ae5 100644 --- a/src/com/android/messaging/FactoryImpl.java +++ b/src/com/android/messaging/FactoryImpl.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -117,13 +118,10 @@ class FactoryImpl extends Factory { mApplication.initializeSync(this); - final Thread asyncInitialization = new Thread() { - @Override - public void run() { - Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); - mApplication.initializeAsync(FactoryImpl.this); - } - }; + final Thread asyncInitialization = new Thread(() -> { + Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); + mApplication.initializeAsync(FactoryImpl.this); + }); asyncInitialization.start(); } diff --git a/src/com/android/messaging/datamodel/BugleNotifications.java b/src/com/android/messaging/datamodel/BugleNotifications.java index 25e08a7..b4be6fe 100644 --- a/src/com/android/messaging/datamodel/BugleNotifications.java +++ b/src/com/android/messaging/datamodel/BugleNotifications.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -1085,12 +1086,7 @@ public class BugleNotifications { OBSERVABLE_CONVERSATION_NOTIFICATION_VOLUME); // Stop the sound after five seconds to handle continuous ringtones - ThreadUtil.getMainThreadHandler().postDelayed(new Runnable() { - @Override - public void run() { - player.stop(); - } - }, 5000); + ThreadUtil.getMainThreadHandler().postDelayed(player::stop, 5000); } public static boolean isWearCompanionAppInstalled() { diff --git a/src/com/android/messaging/datamodel/DataModelImpl.java b/src/com/android/messaging/datamodel/DataModelImpl.java index 60f4152..471c868 100644 --- a/src/com/android/messaging/datamodel/DataModelImpl.java +++ b/src/com/android/messaging/datamodel/DataModelImpl.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -235,17 +236,14 @@ public class DataModelImpl extends DataModel { } private void createConnectivityUtilForEachActiveSubscription() { - PhoneUtils.forEachActiveSubscription(new PhoneUtils.SubscriptionRunnable() { - @Override - public void runForSubscription(int subId) { - // Create the ConnectivityUtil instance for given subId if absent. - if (subId <= ParticipantData.DEFAULT_SELF_SUB_ID) { - subId = PhoneUtils.getDefault().getDefaultSmsSubscriptionId(); - } - if (!sConnectivityUtilInstanceCacheN.containsKey(subId)) { - sConnectivityUtilInstanceCacheN.put( - subId, new ConnectivityUtil(mContext, subId)); - } + PhoneUtils.forEachActiveSubscription(subId -> { + // Create the ConnectivityUtil instance for given subId if absent. + if (subId <= ParticipantData.DEFAULT_SELF_SUB_ID) { + subId = PhoneUtils.getDefault().getDefaultSmsSubscriptionId(); + } + if (!sConnectivityUtilInstanceCacheN.containsKey(subId)) { + sConnectivityUtilInstanceCacheN.put( + subId, new ConnectivityUtil(mContext, subId)); } }); } diff --git a/src/com/android/messaging/datamodel/DatabaseWrapper.java b/src/com/android/messaging/datamodel/DatabaseWrapper.java index 4fce3a0..7e62132 100644 --- a/src/com/android/messaging/datamodel/DatabaseWrapper.java +++ b/src/com/android/messaging/datamodel/DatabaseWrapper.java @@ -67,12 +67,7 @@ public class DatabaseWrapper { // track transaction on a per thread basis private static final ThreadLocal> sTransactionDepth = - new ThreadLocal>() { - @Override - public Stack initialValue() { - return new Stack(); - } - }; + ThreadLocal.withInitial(() -> new Stack()); private static final String[] sFormatStrings = new String[] { "took %d ms to %s", diff --git a/src/com/android/messaging/datamodel/FrequentContactsCursorBuilder.java b/src/com/android/messaging/datamodel/FrequentContactsCursorBuilder.java index fad4040..1fb9aa9 100644 --- a/src/com/android/messaging/datamodel/FrequentContactsCursorBuilder.java +++ b/src/com/android/messaging/datamodel/FrequentContactsCursorBuilder.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +26,6 @@ import com.android.messaging.util.ContactUtil; import java.util.ArrayList; import java.util.Collections; -import java.util.Comparator; /** * A cursor builder that takes the frequent contacts cursor and aggregate it with the all contacts @@ -155,37 +155,34 @@ public class FrequentContactsCursorBuilder { // Now we have a list of rows containing frequent contacts in alphabetical order. // Therefore, sort all the rows according to their actual ranks in the frequents list. - Collections.sort(rows, new Comparator() { - @Override - public int compare(final Object[] lhs, final Object[] rhs) { - final String lookupKeyLhs = (String) lhs[ContactUtil.INDEX_LOOKUP_KEY]; - final String lookupKeyRhs = (String) rhs[ContactUtil.INDEX_LOOKUP_KEY]; - Assert.isTrue(lookupKeyToRankMap.containsKey(lookupKeyLhs) && - lookupKeyToRankMap.containsKey(lookupKeyRhs)); - final int rankLhs = lookupKeyToRankMap.get(lookupKeyLhs); - final int rankRhs = lookupKeyToRankMap.get(lookupKeyRhs); - if (rankLhs < rankRhs) { + Collections.sort(rows, (lhs, rhs) -> { + final String lookupKeyLhs = (String) lhs[ContactUtil.INDEX_LOOKUP_KEY]; + final String lookupKeyRhs = (String) rhs[ContactUtil.INDEX_LOOKUP_KEY]; + Assert.isTrue(lookupKeyToRankMap.containsKey(lookupKeyLhs) && + lookupKeyToRankMap.containsKey(lookupKeyRhs)); + final int rankLhs = lookupKeyToRankMap.get(lookupKeyLhs); + final int rankRhs = lookupKeyToRankMap.get(lookupKeyRhs); + if (rankLhs < rankRhs) { + return -1; + } else if (rankLhs > rankRhs) { + return 1; + } else { + // Same rank, so it's two contact records for the same contact. + // Perform secondary sorting on the phone type. Always place + // mobile before everything else. + final int phoneTypeLhs = (int) lhs[ContactUtil.INDEX_PHONE_EMAIL_TYPE]; + final int phoneTypeRhs = (int) rhs[ContactUtil.INDEX_PHONE_EMAIL_TYPE]; + if (phoneTypeLhs == Phone.TYPE_MOBILE && + phoneTypeRhs == Phone.TYPE_MOBILE) { + return 0; + } else if (phoneTypeLhs == Phone.TYPE_MOBILE) { return -1; - } else if (rankLhs > rankRhs) { + } else if (phoneTypeRhs == Phone.TYPE_MOBILE) { return 1; } else { - // Same rank, so it's two contact records for the same contact. - // Perform secondary sorting on the phone type. Always place - // mobile before everything else. - final int phoneTypeLhs = (int) lhs[ContactUtil.INDEX_PHONE_EMAIL_TYPE]; - final int phoneTypeRhs = (int) rhs[ContactUtil.INDEX_PHONE_EMAIL_TYPE]; - if (phoneTypeLhs == Phone.TYPE_MOBILE && - phoneTypeRhs == Phone.TYPE_MOBILE) { - return 0; - } else if (phoneTypeLhs == Phone.TYPE_MOBILE) { - return -1; - } else if (phoneTypeRhs == Phone.TYPE_MOBILE) { - return 1; - } else { - // Use the default sort order, i.e. sort by phoneType value. - return phoneTypeLhs < phoneTypeRhs ? -1 : - (phoneTypeLhs == phoneTypeRhs ? 0 : 1); - } + // Use the default sort order, i.e. sort by phoneType value. + return phoneTypeLhs < phoneTypeRhs ? -1 : + (phoneTypeLhs == phoneTypeRhs ? 0 : 1); } } }); diff --git a/src/com/android/messaging/datamodel/ParticipantRefresh.java b/src/com/android/messaging/datamodel/ParticipantRefresh.java index 2346168..002e10d 100644 --- a/src/com/android/messaging/datamodel/ParticipantRefresh.java +++ b/src/com/android/messaging/datamodel/ParticipantRefresh.java @@ -96,20 +96,13 @@ public class ParticipantRefresh { private static volatile boolean sObserverInitialized = false; private static final Object sLock = new Object(); private static final AtomicBoolean sFullRefreshScheduled = new AtomicBoolean(false); - private static final Runnable sFullRefreshRunnable = new Runnable() { - @Override - public void run() { - final boolean oldScheduled = sFullRefreshScheduled.getAndSet(false); - Assert.isTrue(oldScheduled); - refreshParticipants(REFRESH_MODE_FULL); - } + private static final Runnable sFullRefreshRunnable = () -> { + final boolean oldScheduled = sFullRefreshScheduled.getAndSet(false); + Assert.isTrue(oldScheduled); + refreshParticipants(REFRESH_MODE_FULL); }; - private static final Runnable sSelfOnlyRefreshRunnable = new Runnable() { - @Override - public void run() { + private static final Runnable sSelfOnlyRefreshRunnable = () -> refreshParticipants(REFRESH_MODE_SELF_ONLY); - } - }; /** * A customized content resolver to track contact changes. diff --git a/src/com/android/messaging/datamodel/action/ActionMonitor.java b/src/com/android/messaging/datamodel/action/ActionMonitor.java index db20de8..0edd75b 100644 --- a/src/com/android/messaging/datamodel/action/ActionMonitor.java +++ b/src/com/android/messaging/datamodel/action/ActionMonitor.java @@ -303,24 +303,21 @@ public class ActionMonitor { } if (completedListener != null) { // Marshal to UI thread - mHandler.post(new Runnable() { - @Override - public void run() { - ActionCompletedListener listener = null; - synchronized (mLock) { - if (mCompletedListener != null) { - listener = mCompletedListener; - } - mCompletedListener = null; + mHandler.post(() -> { + ActionCompletedListener listener = null; + synchronized (mLock) { + if (mCompletedListener != null) { + listener = mCompletedListener; } - if (listener != null) { - if (succeeded) { - listener.onActionSucceeded(ActionMonitor.this, - action, mData, result); - } else { - listener.onActionFailed(ActionMonitor.this, - action, mData, result); - } + mCompletedListener = null; + } + if (listener != null) { + if (succeeded) { + listener.onActionSucceeded(ActionMonitor.this, + action, mData, result); + } else { + listener.onActionFailed(ActionMonitor.this, + action, mData, result); } } }); @@ -372,21 +369,18 @@ public class ActionMonitor { } if (executedListener != null) { // Marshal to UI thread - mHandler.post(new Runnable() { - @Override - public void run() { - ActionExecutedListener listener = null; - synchronized (mLock) { - if (mExecutedListener != null) { - listener = mExecutedListener; - mExecutedListener = null; - } - } - if (listener != null) { - listener.onActionExecuted(ActionMonitor.this, - action, mData, result); + mHandler.post(() -> { + ActionExecutedListener listener = null; + synchronized (mLock) { + if (mExecutedListener != null) { + listener = mExecutedListener; + mExecutedListener = null; } } + if (listener != null) { + listener.onActionExecuted(ActionMonitor.this, + action, mData, result); + } }); } } diff --git a/src/com/android/messaging/datamodel/action/BugleActionToasts.java b/src/com/android/messaging/datamodel/action/BugleActionToasts.java index 17d15f2..fa51911 100644 --- a/src/com/android/messaging/datamodel/action/BugleActionToasts.java +++ b/src/com/android/messaging/datamodel/action/BugleActionToasts.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -117,22 +118,13 @@ public class BugleActionToasts { } private static void showToast(final int messageResId) { - ThreadUtil.getMainThreadHandler().post(new Runnable() { - @Override - public void run() { - Toast.makeText(getApplicationContext(), - getApplicationContext().getString(messageResId), Toast.LENGTH_LONG).show(); - } - }); + ThreadUtil.getMainThreadHandler().post(() -> Toast.makeText(getApplicationContext(), + getApplicationContext().getString(messageResId), Toast.LENGTH_LONG).show()); } private static void showToast(final String message) { - ThreadUtil.getMainThreadHandler().post(new Runnable() { - @Override - public void run() { - Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show(); - } - }); + ThreadUtil.getMainThreadHandler().post(() -> + Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show()); } private static Context getApplicationContext() { diff --git a/src/com/android/messaging/datamodel/action/ProcessPendingMessagesAction.java b/src/com/android/messaging/datamodel/action/ProcessPendingMessagesAction.java index 607f0ab..5172af4 100644 --- a/src/com/android/messaging/datamodel/action/ProcessPendingMessagesAction.java +++ b/src/com/android/messaging/datamodel/action/ProcessPendingMessagesAction.java @@ -61,18 +61,15 @@ public class ProcessPendingMessagesAction extends Action implements Parcelable { private static final String KEY_SUB_ID = "sub_id"; public static void processFirstPendingMessage() { - PhoneUtils.forEachActiveSubscription(new PhoneUtils.SubscriptionRunnable() { - @Override - public void runForSubscription(final int subId) { - // Clear any pending alarms or connectivity events - unregister(subId); - // Clear retry count - setRetry(0, subId); - // Start action - final ProcessPendingMessagesAction action = new ProcessPendingMessagesAction(); - action.actionParameters.putInt(KEY_SUB_ID, subId); - action.start(); - } + PhoneUtils.forEachActiveSubscription(subId -> { + // Clear any pending alarms or connectivity events + unregister(subId); + // Clear retry count + setRetry(0, subId); + // Start action + final ProcessPendingMessagesAction action = new ProcessPendingMessagesAction(); + action.actionParameters.putInt(KEY_SUB_ID, subId); + action.start(); }); } @@ -114,23 +111,20 @@ public class ProcessPendingMessagesAction extends Action implements Parcelable { } if (getHavePendingMessages(subId) || scheduleAlarm) { // Still have a pending message that needs to be queued for processing - final ConnectivityListener listener = new ConnectivityListener() { - @Override - public void onPhoneStateChanged(final int serviceState) { - if (serviceState == ServiceState.STATE_IN_SERVICE) { - LogUtil.i(TAG, "ProcessPendingMessagesAction: Now connected for subId " - + subId + ", starting action"); + final ConnectivityListener listener = serviceState -> { + if (serviceState == ServiceState.STATE_IN_SERVICE) { + LogUtil.i(TAG, "ProcessPendingMessagesAction: Now connected for subId " + + subId + ", starting action"); - // Clear any pending alarms or connectivity events but leave attempt count - // alone - unregister(subId); + // Clear any pending alarms or connectivity events but leave attempt count + // alone + unregister(subId); - // Start action - final ProcessPendingMessagesAction action = - new ProcessPendingMessagesAction(); - action.actionParameters.putInt(KEY_SUB_ID, subId); - action.start(); - } + // Start action + final ProcessPendingMessagesAction action = + new ProcessPendingMessagesAction(); + action.actionParameters.putInt(KEY_SUB_ID, subId); + action.start(); } }; // Read and increment attempt number from shared prefs diff --git a/src/com/android/messaging/datamodel/data/ConversationData.java b/src/com/android/messaging/datamodel/data/ConversationData.java index 740365f..07c32c6 100644 --- a/src/com/android/messaging/datamodel/data/ConversationData.java +++ b/src/com/android/messaging/datamodel/data/ConversationData.java @@ -627,21 +627,18 @@ public class ConversationData extends BindableData { } if (ContactUtil.hasReadContactsPermission()) { - SafeAsyncTask.executeOnThreadPool(new Runnable() { - @Override - public void run() { - final DataUsageStatUpdater updater = new DataUsageStatUpdater( - Factory.get().getApplicationContext()); - try { - if (!phones.isEmpty()) { - updater.updateWithPhoneNumber(phones); - } - if (!emails.isEmpty()) { - updater.updateWithAddress(emails); - } - } catch (final SQLiteFullException ex) { - LogUtil.w(TAG, "Unable to update contact", ex); + SafeAsyncTask.executeOnThreadPool(() -> { + final DataUsageStatUpdater updater = new DataUsageStatUpdater( + Factory.get().getApplicationContext()); + try { + if (!phones.isEmpty()) { + updater.updateWithPhoneNumber(phones); } + if (!emails.isEmpty()) { + updater.updateWithAddress(emails); + } + } catch (final SQLiteFullException ex) { + LogUtil.w(TAG, "Unable to update contact", ex); } }); } diff --git a/src/com/android/messaging/datamodel/data/MessagePartData.java b/src/com/android/messaging/datamodel/data/MessagePartData.java index 0017ba7..4e0c577 100644 --- a/src/com/android/messaging/datamodel/data/MessagePartData.java +++ b/src/com/android/messaging/datamodel/data/MessagePartData.java @@ -445,13 +445,9 @@ public class MessagePartData implements Parcelable { public void destroyAsync() { final Uri contentUri = shouldDestroy(); if (contentUri != null) { - SafeAsyncTask.executeOnThreadPool(new Runnable() { - @Override - public void run() { + SafeAsyncTask.executeOnThreadPool(() -> Factory.get().getApplicationContext().getContentResolver().delete( - contentUri, null, null); - } - }); + contentUri, null, null)); } } diff --git a/src/com/android/messaging/datamodel/data/SelfParticipantsData.java b/src/com/android/messaging/datamodel/data/SelfParticipantsData.java index cc27642..e646de5 100644 --- a/src/com/android/messaging/datamodel/data/SelfParticipantsData.java +++ b/src/com/android/messaging/datamodel/data/SelfParticipantsData.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +21,6 @@ import android.database.Cursor; import androidx.collection.ArrayMap; import java.util.ArrayList; -import java.util.Collections; import java.util.Comparator; import java.util.List; @@ -61,15 +61,11 @@ public class SelfParticipantsData { list.add(self); } } - Collections.sort( - list, - new Comparator() { - public int compare(Object o1, Object o2) { - int slotId1 = ((ParticipantData) o1).getSlotId(); - int slotId2 = ((ParticipantData) o2).getSlotId(); - return slotId1 > slotId2 ? 1 : -1; - } - }); + list.sort((Comparator) (o1, o2) -> { + int slotId1 = ((ParticipantData) o1).getSlotId(); + int slotId2 = ((ParticipantData) o2).getSlotId(); + return slotId1 > slotId2 ? 1 : -1; + }); return list; } diff --git a/src/com/android/messaging/datamodel/media/MediaResourceManager.java b/src/com/android/messaging/datamodel/media/MediaResourceManager.java index 13f7291..2c7c8f8 100644 --- a/src/com/android/messaging/datamodel/media/MediaResourceManager.java +++ b/src/com/android/messaging/datamodel/media/MediaResourceManager.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,7 +28,6 @@ import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.Executors; -import java.util.concurrent.ThreadFactory; /** *

Loads and maintains a set of in-memory LRU caches for different types of media resources. @@ -104,13 +104,10 @@ public class MediaResourceManager { // These tasks are run on a single worker thread with low priority so as not to contend with the // media loading tasks. private static final Executor MEDIA_BACKGROUND_EXECUTOR = Executors.newSingleThreadExecutor( - new ThreadFactory() { - @Override - public Thread newThread(final Runnable runnable) { - final Thread encodingThread = new Thread(runnable); - encodingThread.setPriority(Thread.MIN_PRIORITY); - return encodingThread; - } + runnable -> { + final Thread encodingThread = new Thread(runnable); + encodingThread.setPriority(Thread.MIN_PRIORITY); + return encodingThread; }); /** diff --git a/src/com/android/messaging/datamodel/media/VCardResourceEntry.java b/src/com/android/messaging/datamodel/media/VCardResourceEntry.java index f0f7591..5e30ec2 100644 --- a/src/com/android/messaging/datamodel/media/VCardResourceEntry.java +++ b/src/com/android/messaging/datamodel/media/VCardResourceEntry.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,13 +72,9 @@ public class VCardResourceEntry { void close() { // If the avatar image was temporarily saved in the scratch folder, remove that. if (MediaScratchFileProvider.isMediaScratchSpaceUri(mAvatarUri)) { - SafeAsyncTask.executeOnThreadPool(new Runnable() { - @Override - public void run() { + SafeAsyncTask.executeOnThreadPool(() -> Factory.get().getApplicationContext().getContentResolver().delete( - mAvatarUri, null, null); - } - }); + mAvatarUri, null, null)); } } diff --git a/src/com/android/messaging/sms/ApnDatabase.java b/src/com/android/messaging/sms/ApnDatabase.java index a8d0d0c..6be2bf7 100644 --- a/src/com/android/messaging/sms/ApnDatabase.java +++ b/src/com/android/messaging/sms/ApnDatabase.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -336,12 +337,8 @@ public class ApnDatabase extends SQLiteOpenHelper { final Resources r = sContext.getResources(); final XmlResourceParser parser = r.getXml(R.xml.apns); final ApnsXmlProcessor processor = ApnsXmlProcessor.get(parser); - processor.setApnHandler(new ApnsXmlProcessor.ApnHandler() { - @Override - public void process(final ContentValues apnValues) { - db.insert(APN_TABLE, null/*nullColumnHack*/, apnValues); - } - }); + processor.setApnHandler(apnValues -> db.insert(APN_TABLE, null/*nullColumnHack*/, + apnValues)); try { processor.process(); } catch (final Exception e) { diff --git a/src/com/android/messaging/sms/BugleCarrierConfigValuesLoader.java b/src/com/android/messaging/sms/BugleCarrierConfigValuesLoader.java index ad3efee..a333849 100644 --- a/src/com/android/messaging/sms/BugleCarrierConfigValuesLoader.java +++ b/src/com/android/messaging/sms/BugleCarrierConfigValuesLoader.java @@ -129,13 +129,8 @@ public class BugleCarrierConfigValuesLoader implements CarrierConfigValuesLoader try { parser = subContext.getResources().getXml(R.xml.mms_config); final ApnsXmlProcessor processor = ApnsXmlProcessor.get(parser); - processor.setMmsConfigHandler(new ApnsXmlProcessor.MmsConfigHandler() { - @Override - public void process(final String mccMnc, final String key, final String value, - final String type) { - update(values, type, key, value); - } - }); + processor.setMmsConfigHandler((mccMnc, key, value, type) -> + update(values, type, key, value)); processor.process(); } catch (final Resources.NotFoundException e) { LogUtil.w(LogUtil.BUGLE_TAG, "Can not find mms_config.xml"); diff --git a/src/com/android/messaging/sms/MmsConfig.java b/src/com/android/messaging/sms/MmsConfig.java index 8651697..c157b05 100644 --- a/src/com/android/messaging/sms/MmsConfig.java +++ b/src/com/android/messaging/sms/MmsConfig.java @@ -134,12 +134,7 @@ public class MmsConfig { * Same as load() but doing it using an async thread from SafeAsyncTask thread pool. */ public static void loadAsync() { - SafeAsyncTask.executeOnThreadPool(new Runnable() { - @Override - public void run() { - load(); - } - }); + SafeAsyncTask.executeOnThreadPool(MmsConfig::load); } /** diff --git a/src/com/android/messaging/ui/AsyncImageView.java b/src/com/android/messaging/ui/AsyncImageView.java index cb6ab2e..2376c8d 100644 --- a/src/com/android/messaging/ui/AsyncImageView.java +++ b/src/com/android/messaging/ui/AsyncImageView.java @@ -85,7 +85,7 @@ public class AsyncImageView extends ImageView implements MediaResourceLoadListen // setting is null (no placeholder). private final Drawable mPlaceholderDrawable; protected ImageResource mImageResource; - private final Runnable mDisposeRunnable = new Runnable() { + private final Runnable mDisposeRunnable = () -> new Runnable() { @Override public void run() { if (mImageRequestBinding.isBound()) { diff --git a/src/com/android/messaging/ui/AttachmentPreview.java b/src/com/android/messaging/ui/AttachmentPreview.java index acac58c..31a83f1 100644 --- a/src/com/android/messaging/ui/AttachmentPreview.java +++ b/src/com/android/messaging/ui/AttachmentPreview.java @@ -71,35 +71,22 @@ public class AttachmentPreview extends ScrollView implements OnAttachmentClickLi protected void onFinishInflate() { super.onFinishInflate(); mCloseButton = (ImageButton) findViewById(R.id.close_button); - mCloseButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(final View view) { - mComposeMessageView.clearAttachments(); - } - }); + mCloseButton.setOnClickListener(view -> mComposeMessageView.clearAttachments()); mAttachmentView = (FrameLayout) findViewById(R.id.attachment_view); // The attachment preview is a scroll view so that it can show the bottom portion of the // attachment whenever the space is tight (e.g. when in landscape mode). Per design // request we'd like to make the attachment view always scrolled to the bottom. - addOnLayoutChangeListener(new OnLayoutChangeListener() { - @Override - public void onLayoutChange(final View v, final int left, final int top, final int right, - final int bottom, final int oldLeft, final int oldTop, final int oldRight, - final int oldBottom) { - post(new Runnable() { - @Override - public void run() { - final int childCount = getChildCount(); - if (childCount > 0) { - final View lastChild = getChildAt(childCount - 1); - scrollTo(getScrollX(), lastChild.getBottom() - getHeight()); - } - } - }); + addOnLayoutChangeListener((v, left, top, right, bottom, oldLeft, oldTop, oldRight, + oldBottom) -> post(() -> + { + final int childCount = getChildCount(); + if (childCount > 0) { + final View lastChild = getChildAt(childCount - 1); + scrollTo(getScrollX(), lastChild.getBottom() - getHeight()); } - }); + })); mPendingFirstUpdate = true; } @@ -129,18 +116,14 @@ public class AttachmentPreview extends ScrollView implements OnAttachmentClickLi mPendingHideCanceled = false; final View viewToHide = mAttachmentView.getChildCount() > 1 ? mAttachmentView : mAttachmentView.getChildAt(0); - UiUtils.revealOrHideViewWithAnimation(viewToHide, INVISIBLE, - new Runnable() { - @Override - public void run() { - // Only hide if we are didn't get overruled by showing - if (!mPendingHideCanceled) { - stopPopupAnimation(); - mAttachmentView.removeAllViews(); - setVisibility(GONE); - } - } - }); + UiUtils.revealOrHideViewWithAnimation(viewToHide, INVISIBLE, () -> { + // Only hide if we are didn't get overruled by showing + if (!mPendingHideCanceled) { + stopPopupAnimation(); + mAttachmentView.removeAllViews(); + setVisibility(GONE); + } + }); } else { mAttachmentView.removeAllViews(); setVisibility(GONE); @@ -164,14 +147,11 @@ public class AttachmentPreview extends ScrollView implements OnAttachmentClickLi .getQuantityString(R.plurals.attachment_preview_close_content_description, combinedAttachmentCount)); if (combinedAttachmentCount == 0) { - mHideRunnable = new Runnable() { - @Override - public void run() { - mHideRunnable = null; - // Only start the hiding if there are still no attachments - if (attachments.size() + pendingAttachments.size() == 0) { - hideAttachmentPreview(); - } + mHideRunnable = () -> { + mHideRunnable = null; + // Only start the hiding if there are still no attachments + if (attachments.size() + pendingAttachments.size() == 0) { + hideAttachmentPreview(); } }; if (draftMessageData.isSending()) { @@ -196,13 +176,11 @@ public class AttachmentPreview extends ScrollView implements OnAttachmentClickLi if (!isFirstUpdate) { // Reveal the close button after the view animates in. mCloseButton.setVisibility(INVISIBLE); - ThreadUtil.getMainThreadHandler().postDelayed(new Runnable() { - @Override - public void run() { + ThreadUtil.getMainThreadHandler().postDelayed(() -> UiUtils.revealOrHideViewWithAnimation(mCloseButton, VISIBLE, - null /* onFinishRunnable */); - } - }, UiUtils.MEDIAPICKER_TRANSITION_DURATION + CLOSE_BUTTON_REVEAL_STAGGER_MILLIS); + null /* onFinishRunnable */), + UiUtils.MEDIAPICKER_TRANSITION_DURATION + + CLOSE_BUTTON_REVEAL_STAGGER_MILLIS); } } diff --git a/src/com/android/messaging/ui/AttachmentPreviewFactory.java b/src/com/android/messaging/ui/AttachmentPreviewFactory.java index e801fe0..232e298 100644 --- a/src/com/android/messaging/ui/AttachmentPreviewFactory.java +++ b/src/com/android/messaging/ui/AttachmentPreviewFactory.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,8 +24,6 @@ import androidx.annotation.Nullable; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; -import android.view.View.OnClickListener; -import android.view.View.OnLongClickListener; import android.view.ViewGroup; import android.widget.FrameLayout.LayoutParams; import android.widget.ImageView; @@ -93,22 +92,16 @@ public class AttachmentPreviewFactory { } if (attachmentView != null && clickListener != null) { - attachmentView.setOnClickListener(new OnClickListener() { - @Override - public void onClick(final View view) { - final Rect bounds = UiUtils.getMeasuredBoundsOnScreen(view); - clickListener.onAttachmentClick(attachmentData, bounds, - false /* longPress */); - } - }); - attachmentView.setOnLongClickListener(new OnLongClickListener() { - @Override - public boolean onLongClick(final View view) { - final Rect bounds = UiUtils.getMeasuredBoundsOnScreen(view); - return clickListener.onAttachmentClick(attachmentData, bounds, - true /* longPress */); - } - }); + attachmentView.setOnClickListener(view -> { + final Rect bounds = UiUtils.getMeasuredBoundsOnScreen(view); + clickListener.onAttachmentClick(attachmentData, bounds, + false /* longPress */); + }); + attachmentView.setOnLongClickListener(view -> { + final Rect bounds = UiUtils.getMeasuredBoundsOnScreen(view); + return clickListener.onAttachmentClick(attachmentData, bounds, + true /* longPress */); + }); } return attachmentView; } diff --git a/src/com/android/messaging/ui/AudioAttachmentView.java b/src/com/android/messaging/ui/AudioAttachmentView.java index fec26a8..d2a69d2 100644 --- a/src/com/android/messaging/ui/AudioAttachmentView.java +++ b/src/com/android/messaging/ui/AudioAttachmentView.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,9 +23,6 @@ import android.graphics.Path; import android.graphics.RectF; import android.media.AudioManager; import android.media.MediaPlayer; -import android.media.MediaPlayer.OnCompletionListener; -import android.media.MediaPlayer.OnErrorListener; -import android.media.MediaPlayer.OnPreparedListener; import android.net.Uri; import android.os.SystemClock; import android.text.TextUtils; @@ -106,32 +104,29 @@ public class AudioAttachmentView extends LinearLayout { mPlayPauseButton = (AudioAttachmentPlayPauseButton) findViewById(R.id.play_pause_button); mChronometer = (PausableChronometer) findViewById(R.id.timer); mProgressBar = (AudioPlaybackProgressBar) findViewById(R.id.progress); - mPlayPauseButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(final View v) { - // Has the MediaPlayer already been prepared? - if (mMediaPlayer != null && mPrepared) { - if (mMediaPlayer.isPlaying()) { - mMediaPlayer.pause(); - mChronometer.pause(); - mProgressBar.pause(); - } else { - playAudio(); - } + mPlayPauseButton.setOnClickListener(v -> { + // Has the MediaPlayer already been prepared? + if (mMediaPlayer != null && mPrepared) { + if (mMediaPlayer.isPlaying()) { + mMediaPlayer.pause(); + mChronometer.pause(); + mProgressBar.pause(); } else { - // Either eager preparation is still going on (the user must have clicked - // the Play button immediately after the view is bound) or this is lazy - // preparation. - if (mStartPlayAfterPrepare) { - // The user is (starting and) pausing before the MediaPlayer is prepared - mStartPlayAfterPrepare = false; - } else { - mStartPlayAfterPrepare = true; - setupMediaPlayer(); - } + playAudio(); + } + } else { + // Either eager preparation is still going on (the user must have clicked + // the Play button immediately after the view is bound) or this is lazy + // preparation. + if (mStartPlayAfterPrepare) { + // The user is (starting and) pausing before the MediaPlayer is prepared + mStartPlayAfterPrepare = false; + } else { + mStartPlayAfterPrepare = true; + setupMediaPlayer(); } - updatePlayPauseButtonState(); } + updatePlayPauseButtonState(); }); updatePlayPauseButtonState(); initializeViewsForMode(); @@ -217,47 +212,38 @@ public class AudioAttachmentView extends LinearLayout { try { mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mMediaPlayer.setDataSource(Factory.get().getApplicationContext(), mDataSourceUri); - mMediaPlayer.setOnCompletionListener(new OnCompletionListener() { - @Override - public void onCompletion(final MediaPlayer mp) { - updatePlayPauseButtonState(); - mChronometer.reset(); - mChronometer.setBase(SystemClock.elapsedRealtime() - - mMediaPlayer.getDuration()); - updateChronometerVisibility(false /* playing */); - mProgressBar.reset(); + mMediaPlayer.setOnCompletionListener(mp -> { + updatePlayPauseButtonState(); + mChronometer.reset(); + mChronometer.setBase(SystemClock.elapsedRealtime() - + mMediaPlayer.getDuration()); + updateChronometerVisibility(false /* playing */); + mProgressBar.reset(); - mPlaybackFinished = true; - } + mPlaybackFinished = true; }); - mMediaPlayer.setOnPreparedListener(new OnPreparedListener() { - @Override - public void onPrepared(final MediaPlayer mp) { - // Set base on the chronometer so we can show the full length of the audio. - mChronometer.setBase(SystemClock.elapsedRealtime() - - mMediaPlayer.getDuration()); - mProgressBar.setDuration(mMediaPlayer.getDuration()); - mMediaPlayer.seekTo(0); - mPrepared = true; + mMediaPlayer.setOnPreparedListener(mp -> { + // Set base on the chronometer so we can show the full length of the audio. + mChronometer.setBase(SystemClock.elapsedRealtime() - + mMediaPlayer.getDuration()); + mProgressBar.setDuration(mMediaPlayer.getDuration()); + mMediaPlayer.seekTo(0); + mPrepared = true; - if (mStartPlayAfterPrepare) { - mStartPlayAfterPrepare = false; - playAudio(); - updatePlayPauseButtonState(); - } - } - }); - - mMediaPlayer.setOnErrorListener(new OnErrorListener() { - @Override - public boolean onError(final MediaPlayer mp, final int what, final int extra) { + if (mStartPlayAfterPrepare) { mStartPlayAfterPrepare = false; - onAudioReplayError(what, extra, null); - return true; + playAudio(); + updatePlayPauseButtonState(); } }); + mMediaPlayer.setOnErrorListener((mp, what, extra) -> { + mStartPlayAfterPrepare = false; + onAudioReplayError(what, extra, null); + return true; + }); + mMediaPlayer.prepareAsync(); } catch (final Exception exception) { onAudioReplayError(0, 0, exception); diff --git a/src/com/android/messaging/ui/AudioPlaybackProgressBar.java b/src/com/android/messaging/ui/AudioPlaybackProgressBar.java index a5b3a57..3003d4d 100644 --- a/src/com/android/messaging/ui/AudioPlaybackProgressBar.java +++ b/src/com/android/messaging/ui/AudioPlaybackProgressBar.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +18,6 @@ package com.android.messaging.ui; import android.animation.ObjectAnimator; import android.animation.TimeAnimator; -import android.animation.TimeAnimator.TimeListener; import android.content.Context; import android.graphics.drawable.ClipDrawable; import android.graphics.drawable.Drawable; @@ -41,18 +41,14 @@ public class AudioPlaybackProgressBar extends ProgressBar implements PlaybackSta mUpdateAnimator = new TimeAnimator(); mUpdateAnimator.setRepeatCount(ObjectAnimator.INFINITE); - mUpdateAnimator.setTimeListener(new TimeListener() { - @Override - public void onTimeUpdate(final TimeAnimator animation, final long totalTime, - final long deltaTime) { - int progress = 0; - if (mDurationInMillis > 0) { - progress = (int) (((mCumulativeTime + SystemClock.elapsedRealtime() - - mCurrentPlayStartTime) * 1.0f / mDurationInMillis) * 100); - progress = Math.max(Math.min(progress, 100), 0); - } - setProgress(progress); + mUpdateAnimator.setTimeListener((animation, totalTime, deltaTime) -> { + int progress = 0; + if (mDurationInMillis > 0) { + progress = (int) (((mCumulativeTime + SystemClock.elapsedRealtime() - + mCurrentPlayStartTime) * 1.0f / mDurationInMillis) * 100); + progress = Math.max(Math.min(progress, 100), 0); } + setProgress(progress); }); updateAppearance(); } diff --git a/src/com/android/messaging/ui/BlockedParticipantListItemView.java b/src/com/android/messaging/ui/BlockedParticipantListItemView.java index 9654e70..a4d047c 100644 --- a/src/com/android/messaging/ui/BlockedParticipantListItemView.java +++ b/src/com/android/messaging/ui/BlockedParticipantListItemView.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +20,6 @@ import android.content.Context; import androidx.core.text.BidiFormatter; import androidx.core.text.TextDirectionHeuristicsCompat; import android.util.AttributeSet; -import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; @@ -44,12 +44,7 @@ public class BlockedParticipantListItemView extends LinearLayout { protected void onFinishInflate() { mNameTextView = (TextView) findViewById(R.id.name); mContactIconView = (ContactIconView) findViewById(R.id.contact_icon); - setOnClickListener(new OnClickListener() { - @Override - public void onClick(final View v) { - mData.unblock(getContext()); - } - }); + setOnClickListener(v -> mData.unblock(getContext())); } public void bind(final ParticipantListItemData data) { diff --git a/src/com/android/messaging/ui/ClassZeroActivity.java b/src/com/android/messaging/ui/ClassZeroActivity.java index 08da0a2..a1ea035 100644 --- a/src/com/android/messaging/ui/ClassZeroActivity.java +++ b/src/com/android/messaging/ui/ClassZeroActivity.java @@ -20,7 +20,6 @@ package com.android.messaging.ui; import android.app.Activity; import android.app.AlertDialog; import android.content.ContentValues; -import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.os.Bundle; @@ -188,21 +187,15 @@ public class ClassZeroActivity extends Activity { } } - private final OnClickListener mCancelListener = new OnClickListener() { - @Override - public void onClick(final DialogInterface dialog, final int whichButton) { - dialog.dismiss(); - processNextMessage(); - } + private final OnClickListener mCancelListener = (dialog, whichButton) -> { + dialog.dismiss(); + processNextMessage(); }; - private final OnClickListener mSaveListener = new OnClickListener() { - @Override - public void onClick(final DialogInterface dialog, final int whichButton) { - mRead = true; - saveMessage(); - dialog.dismiss(); - processNextMessage(); - } + private final OnClickListener mSaveListener = (dialog, whichButton) -> { + mRead = true; + saveMessage(); + dialog.dismiss(); + processNextMessage(); }; } diff --git a/src/com/android/messaging/ui/ContactIconView.java b/src/com/android/messaging/ui/ContactIconView.java index 44983ab..db15d20 100644 --- a/src/com/android/messaging/ui/ContactIconView.java +++ b/src/com/android/messaging/ui/ContactIconView.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +23,6 @@ import android.net.Uri; import android.text.TextUtils; import android.util.AttributeSet; import android.view.MotionEvent; -import android.view.View; import com.android.messaging.R; import com.android.messaging.datamodel.data.ParticipantData; @@ -134,13 +134,8 @@ public class ContactIconView extends AsyncImageView { && !TextUtils.isEmpty(mContactLookupKey)) || !TextUtils.isEmpty(mNormalizedDestination)) { if (!mDisableClickHandler) { - setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(final View view) { - ContactUtil.showOrAddContact(view, mContactId, mContactLookupKey, - mAvatarUri, mNormalizedDestination); - } - }); + setOnClickListener(view -> ContactUtil.showOrAddContact(view, mContactId, + mContactLookupKey, mAvatarUri, mNormalizedDestination)); } } else { // This should happen when the phone number is not in the user's contacts or it is a diff --git a/src/com/android/messaging/ui/PermissionCheckActivity.java b/src/com/android/messaging/ui/PermissionCheckActivity.java index 6a95acd..dd10e1d 100644 --- a/src/com/android/messaging/ui/PermissionCheckActivity.java +++ b/src/com/android/messaging/ui/PermissionCheckActivity.java @@ -24,7 +24,6 @@ import android.os.Bundle; import android.os.SystemClock; import android.provider.Settings; import android.view.View; -import android.view.View.OnClickListener; import android.widget.TextView; import androidx.annotation.NonNull; @@ -57,29 +56,16 @@ public class PermissionCheckActivity extends Activity { setContentView(R.layout.permission_check_activity); UiUtils.setStatusBarColor(this, getColor(R.color.permission_check_activity_background)); - findViewById(R.id.exit).setOnClickListener(new OnClickListener() { - @Override - public void onClick(final View view) { - finish(); - } - }); + findViewById(R.id.exit).setOnClickListener(view -> finish()); mNextView = (TextView) findViewById(R.id.next); - mNextView.setOnClickListener(new OnClickListener() { - @Override - public void onClick(final View view) { - tryRequestPermission(); - } - }); + mNextView.setOnClickListener(view -> tryRequestPermission()); mSettingsView = (TextView) findViewById(R.id.settings); - mSettingsView.setOnClickListener(new OnClickListener() { - @Override - public void onClick(final View view) { - final Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, - Uri.parse(PACKAGE_URI_PREFIX + getPackageName())); - startActivity(intent); - } + mSettingsView.setOnClickListener(view -> { + final Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, + Uri.parse(PACKAGE_URI_PREFIX + getPackageName())); + startActivity(intent); }); } diff --git a/src/com/android/messaging/ui/PersonItemView.java b/src/com/android/messaging/ui/PersonItemView.java index 2db1219..964d6c4 100644 --- a/src/com/android/messaging/ui/PersonItemView.java +++ b/src/com/android/messaging/ui/PersonItemView.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -168,22 +169,16 @@ public class PersonItemView extends LinearLayout implements PersonItemDataListen if (mListener == null) { return; } - setOnClickListener(new OnClickListener() { - @Override - public void onClick(final View v) { - if (mListener != null && mBinding.isBound()) { - mListener.onPersonClicked(mBinding.getData()); - } + setOnClickListener(v -> { + if (mListener != null && mBinding.isBound()) { + mListener.onPersonClicked(mBinding.getData()); } }); - final OnLongClickListener onLongClickListener = new OnLongClickListener() { - @Override - public boolean onLongClick(View v) { - if (mListener != null && mBinding.isBound()) { - return mListener.onPersonLongClicked(mBinding.getData()); - } - return false; + final OnLongClickListener onLongClickListener = v -> { + if (mListener != null && mBinding.isBound()) { + return mListener.onPersonLongClicked(mBinding.getData()); } + return false; }; setOnLongClickListener(onLongClickListener); mContactIconView.setOnLongClickListener(onLongClickListener); diff --git a/src/com/android/messaging/ui/SmsStorageLowWarningFragment.java b/src/com/android/messaging/ui/SmsStorageLowWarningFragment.java index f95e752..a40e0f5 100644 --- a/src/com/android/messaging/ui/SmsStorageLowWarningFragment.java +++ b/src/com/android/messaging/ui/SmsStorageLowWarningFragment.java @@ -28,7 +28,6 @@ import android.content.res.Resources; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; -import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; @@ -108,12 +107,7 @@ public class SmsStorageLowWarningFragment extends Fragment { builder.setTitle(R.string.sms_storage_low_title) .setView(dialogLayout) - .setNegativeButton(R.string.ignore, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int id) { - dialog.cancel(); - } - }); + .setNegativeButton(R.string.ignore, (dialog, id) -> dialog.cancel()); final Dialog dialog = builder.create(); dialog.setCanceledOnTouchOutside(false); @@ -145,12 +139,9 @@ public class SmsStorageLowWarningFragment extends Fragment { final String action = getItem(position); actionItemView.setText(action); - actionItemView.setOnClickListener(new OnClickListener() { - @Override - public void onClick(final View view) { - dismiss(); - ((SmsStorageLowWarningFragment) getTargetFragment()).confirm(position); - } + actionItemView.setOnClickListener(view1 -> { + dismiss(); + ((SmsStorageLowWarningFragment) getTargetFragment()).confirm(position); }); return actionItemView; } @@ -191,25 +182,15 @@ public class SmsStorageLowWarningFragment extends Fragment { final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.sms_storage_low_title) .setMessage(getConfirmDialogMessage(actionIndex)) - .setNegativeButton(android.R.string.cancel, - new DialogInterface.OnClickListener() { - @Override - public void onClick(final DialogInterface dialog, - final int button) { - dismiss(); - ((SmsStorageLowWarningFragment) getTargetFragment()).cancel(); - } + .setNegativeButton(android.R.string.cancel, (dialog, button) -> { + dismiss(); + ((SmsStorageLowWarningFragment) getTargetFragment()).cancel(); }) - .setPositiveButton(android.R.string.ok, - new DialogInterface.OnClickListener() { - @Override - public void onClick(final DialogInterface dialog, - final int button) { - dismiss(); - handleAction(actionIndex); - getActivity().finish(); - SmsStorageStatusManager.cancelStorageLowNotification(); - } + .setPositiveButton(android.R.string.ok, (dialog, button) -> { + dismiss(); + handleAction(actionIndex); + getActivity().finish(); + SmsStorageStatusManager.cancelStorageLowNotification(); }); return builder.create(); } diff --git a/src/com/android/messaging/ui/SnackBar.java b/src/com/android/messaging/ui/SnackBar.java index 1f50609..265ee86 100644 --- a/src/com/android/messaging/ui/SnackBar.java +++ b/src/com/android/messaging/ui/SnackBar.java @@ -22,7 +22,6 @@ import androidx.annotation.Nullable; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; -import android.view.View.OnClickListener; import android.view.ViewGroup.MarginLayoutParams; import android.widget.FrameLayout; import android.widget.TextView; @@ -292,13 +291,10 @@ public class SnackBar { } else { mActionTextView.setVisibility(View.VISIBLE); mActionTextView.setText(mAction.getActionLabel()); - mActionTextView.setOnClickListener(new OnClickListener() { - @Override - public void onClick(final View v) { - mAction.getActionRunnable().run(); - if (mListener != null) { - mListener.onActionClick(); - } + mActionTextView.setOnClickListener(v -> { + mAction.getActionRunnable().run(); + if (mListener != null) { + mListener.onActionClick(); } }); } diff --git a/src/com/android/messaging/ui/SnackBarManager.java b/src/com/android/messaging/ui/SnackBarManager.java index 4a3bdac..8e24547 100644 --- a/src/com/android/messaging/ui/SnackBarManager.java +++ b/src/com/android/messaging/ui/SnackBarManager.java @@ -23,7 +23,6 @@ import android.os.Handler; import android.text.TextUtils; import android.util.DisplayMetrics; import android.view.Gravity; -import android.view.MotionEvent; import android.view.View; import android.view.View.MeasureSpec; import android.view.View.OnAttachStateChangeListener; @@ -34,7 +33,6 @@ import android.view.ViewPropertyAnimator; import android.view.ViewTreeObserver.OnGlobalLayoutListener; import android.view.WindowManager; import android.widget.PopupWindow; -import android.widget.PopupWindow.OnDismissListener; import androidx.annotation.NonNull; @@ -66,28 +64,15 @@ public class SnackBarManager { return sInstance; } - private final Runnable mDismissRunnable = new Runnable() { - @Override - public void run() { - dismiss(); - } + private final Runnable mDismissRunnable = this::dismiss; + + private final OnTouchListener mDismissOnTouchListener = (view, event) -> { + // Dismiss the {@link SnackBar} but don't consume the event. + dismiss(); + return false; }; - private final OnTouchListener mDismissOnTouchListener = new OnTouchListener() { - @Override - public boolean onTouch(final View view, final MotionEvent event) { - // Dismiss the {@link SnackBar} but don't consume the event. - dismiss(); - return false; - } - }; - - private final SnackBarListener mDismissOnUserTapListener = new SnackBarListener() { - @Override - public void onActionClick() { - dismiss(); - } - }; + private final SnackBarListener mDismissOnUserTapListener = this::dismiss; private final OnAttachStateChangeListener mAttachStateChangeListener = new OnAttachStateChangeListener() { @@ -184,20 +169,12 @@ public class SnackBarManager { // You'd expect PopupWindow.showAsDropDown to ensure the popup moves with the anchor // view, which it does for scrolling, but not layout changes, so we have to manually // update while the snackbar is showing - final OnGlobalLayoutListener listener = new OnGlobalLayoutListener() { - @Override - public void onGlobalLayout() { + final OnGlobalLayoutListener listener = () -> mPopupWindow.update(anchorView, 0, getRelativeOffset(snackBar), anchorView.getWidth(), LayoutParams.WRAP_CONTENT); - } - }; anchorView.getViewTreeObserver().addOnGlobalLayoutListener(listener); - mPopupWindow.setOnDismissListener(new OnDismissListener() { - @Override - public void onDismiss() { - anchorView.getViewTreeObserver().removeOnGlobalLayoutListener(listener); - } - }); + mPopupWindow.setOnDismissListener(() -> + anchorView.getViewTreeObserver().removeOnGlobalLayoutListener(listener)); mPopupWindow.showAsDropDown(anchorView, 0, getRelativeOffset(snackBar)); } @@ -205,23 +182,20 @@ public class SnackBarManager { // Animate the toast bar into view. placeSnackBarOffScreen(snackBar); - animateSnackBarOnScreen(snackBar).withEndAction(new Runnable() { - @Override - public void run() { - mCurrentSnackBar.setEnabled(true); - makeCurrentSnackBarDismissibleOnTouch(); - // Fire an accessibility event as needed - String snackBarText = snackBar.getMessageText(); - if (!TextUtils.isEmpty(snackBarText) && - TextUtils.getTrimmedLength(snackBarText) > 0) { - snackBarText = snackBarText.trim(); - final String snackBarActionText = snackBar.getActionLabel(); - if (!TextUtil.isAllWhitespace(snackBarActionText)) { - snackBarText = Joiner.on(", ").join(snackBarText, snackBarActionText); - } - AccessibilityUtil.announceForAccessibilityCompat(snackBar.getSnackBarView(), - null /*accessibilityManager*/, snackBarText); + animateSnackBarOnScreen(snackBar).withEndAction(() -> { + mCurrentSnackBar.setEnabled(true); + makeCurrentSnackBarDismissibleOnTouch(); + // Fire an accessibility event as needed + String snackBarText = snackBar.getMessageText(); + if (!TextUtils.isEmpty(snackBarText) && + TextUtils.getTrimmedLength(snackBarText) > 0) { + snackBarText = snackBarText.trim(); + final String snackBarActionText = snackBar.getActionLabel(); + if (!TextUtil.isAllWhitespace(snackBarActionText)) { + snackBarText = Joiner.on(", ").join(snackBarText, snackBarActionText); } + AccessibilityUtil.announceForAccessibilityCompat(snackBar.getSnackBarView(), + null /*accessibilityManager*/, snackBarText); } }); @@ -249,28 +223,25 @@ public class SnackBarManager { // Animate the toast bar down. final View rootView = snackBar.getRootView(); - animateSnackBarOffScreen(snackBar).withEndAction(new Runnable() { - @Override - public void run() { - rootView.setVisibility(View.GONE); - try { - mPopupWindow.dismiss(); - } catch (IllegalArgumentException e) { - // PopupWindow.dismiss() will fire an IllegalArgumentException if the activity - // has already ended while we were animating - } - snackBar.getParentView() - .removeOnAttachStateChangeListener(mAttachStateChangeListener); + animateSnackBarOffScreen(snackBar).withEndAction(() -> { + rootView.setVisibility(View.GONE); + try { + mPopupWindow.dismiss(); + } catch (IllegalArgumentException e) { + // PopupWindow.dismiss() will fire an IllegalArgumentException if the activity + // has already ended while we were animating + } + snackBar.getParentView() + .removeOnAttachStateChangeListener(mAttachStateChangeListener); - mCurrentSnackBar = null; - mIsCurrentlyDismissing = false; + mCurrentSnackBar = null; + mIsCurrentlyDismissing = false; - // Show the next toast if one is waiting. - if (mNextSnackBar != null) { - final SnackBar localNextSnackBar = mNextSnackBar; - mNextSnackBar = null; - show(localNextSnackBar); - } + // Show the next toast if one is waiting. + if (mNextSnackBar != null) { + final SnackBar localNextSnackBar = mNextSnackBar; + mNextSnackBar = null; + show(localNextSnackBar); } }); diff --git a/src/com/android/messaging/ui/VCardDetailFragment.java b/src/com/android/messaging/ui/VCardDetailFragment.java index 1b2b88d..61ef347 100644 --- a/src/com/android/messaging/ui/VCardDetailFragment.java +++ b/src/com/android/messaging/ui/VCardDetailFragment.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,11 +26,9 @@ import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; -import android.view.View.OnLayoutChangeListener; import android.view.ViewGroup; import android.widget.ExpandableListAdapter; import android.widget.ExpandableListView; -import android.widget.ExpandableListView.OnChildClickListener; import com.android.messaging.R; import com.android.messaging.datamodel.DataModel; @@ -73,34 +72,27 @@ public class VCardDetailFragment extends Fragment implements PersonItemDataListe Assert.notNull(mVCardUri); final View view = inflater.inflate(R.layout.vcard_detail_fragment, container, false); mListView = (ExpandableListView) view.findViewById(R.id.list); - mListView.addOnLayoutChangeListener(new OnLayoutChangeListener() { - @Override - public void onLayoutChange(final View v, final int left, final int top, final int right, - final int bottom, final int oldLeft, final int oldTop, final int oldRight, - final int oldBottom) { - mListView.setIndicatorBounds(mListView.getWidth() - getResources() - .getDimensionPixelSize(R.dimen.vcard_detail_group_indicator_width), - mListView.getWidth()); - } + mListView.addOnLayoutChangeListener((v, left, top, right, bottom, oldLeft, oldTop, oldRight, + oldBottom) -> { + mListView.setIndicatorBounds(mListView.getWidth() - getResources(). + getDimensionPixelSize(R.dimen.vcard_detail_group_indicator_width), + mListView.getWidth()); }); - mListView.setOnChildClickListener(new OnChildClickListener() { - @Override - public boolean onChildClick(ExpandableListView expandableListView, View clickedView, - int groupPosition, int childPosition, long childId) { - if (!(clickedView instanceof PersonItemView)) { - return false; - } - final Intent intent = ((PersonItemView) clickedView).getClickIntent(); - if (intent != null) { - try { - startActivity(intent); - } catch (ActivityNotFoundException e) { - return false; - } - return true; - } + mListView.setOnChildClickListener((expandableListView, clickedView, groupPosition, + childPosition, childId) -> { + if (!(clickedView instanceof PersonItemView)) { return false; } + final Intent intent = ((PersonItemView) clickedView).getClickIntent(); + if (intent != null) { + try { + startActivity(intent); + } catch (ActivityNotFoundException e) { + return false; + } + return true; + } + return false; }); mBinding.bind(DataModel.get().createVCardContactItemData(getActivity(), mVCardUri)); mBinding.getData().setListener(this); diff --git a/src/com/android/messaging/ui/VideoThumbnailView.java b/src/com/android/messaging/ui/VideoThumbnailView.java index 9336ddc..c64b5a7 100644 --- a/src/com/android/messaging/ui/VideoThumbnailView.java +++ b/src/com/android/messaging/ui/VideoThumbnailView.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -95,15 +96,12 @@ public class VideoThumbnailView extends FrameLayout { mVideoView.clearFocus(); addView(mVideoView, 0, new ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); - mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { - @Override - public void onPrepared(final MediaPlayer mediaPlayer) { - mVideoLoaded = true; - mVideoWidth = mediaPlayer.getVideoWidth(); - mVideoHeight = mediaPlayer.getVideoHeight(); - mediaPlayer.setLooping(loop); - trySwitchToVideo(); - } + mVideoView.setOnPreparedListener(mediaPlayer -> { + mVideoLoaded = true; + mVideoWidth = mediaPlayer.getVideoWidth(); + mVideoHeight = mediaPlayer.getVideoHeight(); + mediaPlayer.setLooping(loop); + trySwitchToVideo(); }); mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override @@ -111,12 +109,7 @@ public class VideoThumbnailView extends FrameLayout { mPlayButton.setVisibility(View.VISIBLE); } }); - mVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener() { - @Override - public boolean onError(final MediaPlayer mediaPlayer, final int i, final int i2) { - return true; - } - }); + mVideoView.setOnErrorListener((mediaPlayer, i, i2) -> true); } else { mVideoView = null; } @@ -125,28 +118,22 @@ public class VideoThumbnailView extends FrameLayout { if (loop) { mPlayButton.setVisibility(View.GONE); } else { - mPlayButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(final View view) { - if (mVideoSource == null) { - return; - } + mPlayButton.setOnClickListener(view -> { + if (mVideoSource == null) { + return; + } - if (mMode == MODE_PLAYABLE_VIDEO) { - mVideoView.seekTo(0); - start(); - } else { - UIIntents.get().launchFullScreenVideoViewer(getContext(), mVideoSource); - } + if (mMode == MODE_PLAYABLE_VIDEO) { + mVideoView.seekTo(0); + start(); + } else { + UIIntents.get().launchFullScreenVideoViewer(getContext(), mVideoSource); } }); - mPlayButton.setOnLongClickListener(new OnLongClickListener() { - @Override - public boolean onLongClick(final View view) { - // Button prevents long click from propagating up, do it manually - VideoThumbnailView.this.performLongClick(); - return true; - } + mPlayButton.setOnLongClickListener(view -> { + // Button prevents long click from propagating up, do it manually + VideoThumbnailView.this.performLongClick(); + return true; }); } diff --git a/src/com/android/messaging/ui/ViewPagerTabs.java b/src/com/android/messaging/ui/ViewPagerTabs.java index 51e525c..81f4719 100644 --- a/src/com/android/messaging/ui/ViewPagerTabs.java +++ b/src/com/android/messaging/ui/ViewPagerTabs.java @@ -157,12 +157,7 @@ public class ViewPagerTabs extends HorizontalScrollView implements ViewPager.OnP textView.setText(tabTitle); textView.setBackgroundResource(R.drawable.contact_picker_tab_background_selector); textView.setGravity(Gravity.CENTER); - textView.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - mPager.setCurrentItem(getRtlPosition(position)); - } - }); + textView.setOnClickListener(v -> mPager.setCurrentItem(getRtlPosition(position))); // Assign various text appearance related attributes to child views. if (mTextStyle > 0) { diff --git a/src/com/android/messaging/ui/animation/PopupTransitionAnimation.java b/src/com/android/messaging/ui/animation/PopupTransitionAnimation.java index 5b7bd9b..87cab73 100644 --- a/src/com/android/messaging/ui/animation/PopupTransitionAnimation.java +++ b/src/com/android/messaging/ui/animation/PopupTransitionAnimation.java @@ -112,12 +112,8 @@ public class PopupTransitionAnimation extends Animation { } private final StringBuilder mEvents = new StringBuilder(); - private final Runnable mCleanupRunnable = new Runnable() { - @Override - public void run() { + private final Runnable mCleanupRunnable = () -> LogUtil.w(LogUtil.BUGLE_TAG, "PopupTransitionAnimation: " + mEvents); - } - }; /** * Ensures the animation is ready before starting the animation. @@ -210,17 +206,14 @@ public class PopupTransitionAnimation extends Animation { mViewToAnimate.setVisibility(View.VISIBLE); // Delay dismissing the popup window to let mViewToAnimate draw under it and reduce the // flash - ThreadUtil.getMainThreadHandler().post(new Runnable() { - @Override - public void run() { - try { - mPopupWindow.dismiss(); - } catch (IllegalArgumentException e) { - // PopupWindow.dismiss() will fire an IllegalArgumentException if the activity - // has already ended while we were animating - } - ThreadUtil.getMainThreadHandler().removeCallbacks(mCleanupRunnable); + ThreadUtil.getMainThreadHandler().post(() -> { + try { + mPopupWindow.dismiss(); + } catch (IllegalArgumentException e) { + // PopupWindow.dismiss() will fire an IllegalArgumentException if the activity + // has already ended while we were animating } + ThreadUtil.getMainThreadHandler().removeCallbacks(mCleanupRunnable); }); } diff --git a/src/com/android/messaging/ui/animation/ViewGroupItemVerticalExplodeAnimation.java b/src/com/android/messaging/ui/animation/ViewGroupItemVerticalExplodeAnimation.java index c757a83..83dc31f 100644 --- a/src/com/android/messaging/ui/animation/ViewGroupItemVerticalExplodeAnimation.java +++ b/src/com/android/messaging/ui/animation/ViewGroupItemVerticalExplodeAnimation.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -168,17 +169,14 @@ public class ViewGroupItemVerticalExplodeAnimation { expandLayer.animate().scaleY(scale) .setDuration(mDuration) .setInterpolator(UiUtils.EASE_IN_INTERPOLATOR) - .withEndAction(new Runnable() { - @Override - public void run() { - // Clean up the views added to overlay on animation finish. - overlay.remove(shadowContainerLayer); - mViewToAnimate.setBackground(oldBackground); - if (mViewBitmap != null) { - mViewBitmap.recycle(); - } + .withEndAction(() -> { + // Clean up the views added to overlay on animation finish. + overlay.remove(shadowContainerLayer); + mViewToAnimate.setBackground(oldBackground); + if (mViewBitmap != null) { + mViewBitmap.recycle(); } - }); + }); } } } diff --git a/src/com/android/messaging/ui/appsettings/GroupMmsSettingDialog.java b/src/com/android/messaging/ui/appsettings/GroupMmsSettingDialog.java index 739d2dc..5c2391f 100644 --- a/src/com/android/messaging/ui/appsettings/GroupMmsSettingDialog.java +++ b/src/com/android/messaging/ui/appsettings/GroupMmsSettingDialog.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +20,6 @@ import android.app.AlertDialog; import android.content.Context; import android.view.LayoutInflater; import android.view.View; -import android.view.View.OnClickListener; import android.widget.RadioButton; import com.android.messaging.R; @@ -70,18 +70,8 @@ public class GroupMmsSettingDialog { rootView.findViewById(R.id.disable_group_mms_button); final RadioButton enableButton = (RadioButton) rootView.findViewById(R.id.enable_group_mms_button); - disableButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View view) { - changeGroupMmsSettings(false); - } - }); - enableButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View view) { - changeGroupMmsSettings(true); - } - }); + disableButton.setOnClickListener(view -> changeGroupMmsSettings(false)); + enableButton.setOnClickListener(view -> changeGroupMmsSettings(true)); final boolean mmsEnabled = BuglePrefs.getSubscriptionPrefs(mSubId).getBoolean( mContext.getString(R.string.group_mms_pref_key), mContext.getResources().getBoolean(R.bool.group_mms_pref_default)); diff --git a/src/com/android/messaging/ui/appsettings/PerSubscriptionSettingsActivity.java b/src/com/android/messaging/ui/appsettings/PerSubscriptionSettingsActivity.java index 2b5cbd5..4a33920 100644 --- a/src/com/android/messaging/ui/appsettings/PerSubscriptionSettingsActivity.java +++ b/src/com/android/messaging/ui/appsettings/PerSubscriptionSettingsActivity.java @@ -125,12 +125,9 @@ public class PerSubscriptionSettingsActivity extends BugleActionBarActivity { // is being sent, making sure we will have a self number for group mms. mmsCategory.removePreference(mGroupMmsPreference); } else { - mGroupMmsPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() { - @Override - public boolean onPreferenceClick(Preference pref) { - GroupMmsSettingDialog.showDialog(getActivity(), mSubId); - return true; - } + mGroupMmsPreference.setOnPreferenceClickListener(pref -> { + GroupMmsSettingDialog.showDialog(getActivity(), mSubId); + return true; }); updateGroupMmsPrefSummary(); } diff --git a/src/com/android/messaging/ui/appsettings/SettingsActivity.java b/src/com/android/messaging/ui/appsettings/SettingsActivity.java index 8ca271e..3cc688f 100644 --- a/src/com/android/messaging/ui/appsettings/SettingsActivity.java +++ b/src/com/android/messaging/ui/appsettings/SettingsActivity.java @@ -27,7 +27,6 @@ import android.text.TextUtils; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; -import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; @@ -155,24 +154,21 @@ public class SettingsActivity extends BugleActionBarActivity { } else { subtitleTextView.setVisibility(View.GONE); } - itemView.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View view) { - switch (item.getType()) { - case SettingsItem.TYPE_GENERAL_SETTINGS: - UIIntents.get().launchApplicationSettingsActivity(getActivity(), - false /* topLevel */); - break; + itemView.setOnClickListener(view -> { + switch (item.getType()) { + case SettingsItem.TYPE_GENERAL_SETTINGS: + UIIntents.get().launchApplicationSettingsActivity(getActivity(), + false /* topLevel */); + break; - case SettingsItem.TYPE_PER_SUBSCRIPTION_SETTINGS: - UIIntents.get().launchPerSubscriptionSettingsActivity(getActivity(), - item.getSubId(), item.getActivityTitle()); - break; + case SettingsItem.TYPE_PER_SUBSCRIPTION_SETTINGS: + UIIntents.get().launchPerSubscriptionSettingsActivity(getActivity(), + item.getSubId(), item.getActivityTitle()); + break; - default: - Assert.fail("unrecognized setting type!"); - break; - } + default: + Assert.fail("unrecognized setting type!"); + break; } }); return itemView; diff --git a/src/com/android/messaging/ui/attachmentchooser/AttachmentGridItemView.java b/src/com/android/messaging/ui/attachmentchooser/AttachmentGridItemView.java index 8bb7356..f5f5fcf 100644 --- a/src/com/android/messaging/ui/attachmentchooser/AttachmentGridItemView.java +++ b/src/com/android/messaging/ui/attachmentchooser/AttachmentGridItemView.java @@ -1,5 +1,6 @@ /* - * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,30 +56,19 @@ public class AttachmentGridItemView extends FrameLayout { super.onFinishInflate(); mAttachmentViewContainer = (FrameLayout) findViewById(R.id.attachment_container); mCheckBox = (CheckBox) findViewById(R.id.checkbox); - mCheckBox.setOnClickListener(new OnClickListener() { - @Override - public void onClick(final View v) { - mHostInterface.onItemCheckedChanged(AttachmentGridItemView.this, mAttachmentData); - } - }); - setOnClickListener(new OnClickListener() { - @Override - public void onClick(final View v) { - mHostInterface.onItemClicked(AttachmentGridItemView.this, mAttachmentData); - } - }); - addOnLayoutChangeListener(new OnLayoutChangeListener() { - @Override - public void onLayoutChange(View v, int left, int top, int right, int bottom, - int oldLeft, int oldTop, int oldRight, int oldBottom) { - // Enlarge the clickable region for the checkbox. - final int touchAreaIncrease = getResources().getDimensionPixelOffset( - R.dimen.attachment_grid_checkbox_area_increase); - final Rect region = new Rect(); - mCheckBox.getHitRect(region); - region.inset(-touchAreaIncrease, -touchAreaIncrease); - setTouchDelegate(new TouchDelegate(region, mCheckBox)); - } + mCheckBox.setOnClickListener(v -> mHostInterface.onItemCheckedChanged( + AttachmentGridItemView.this, mAttachmentData)); + setOnClickListener(v -> mHostInterface.onItemClicked(AttachmentGridItemView.this, + mAttachmentData)); + addOnLayoutChangeListener((v, left, top, right, bottom, oldLeft, oldTop, oldRight, + oldBottom) -> { + // Enlarge the clickable region for the checkbox. + final int touchAreaIncrease = getResources().getDimensionPixelOffset( + R.dimen.attachment_grid_checkbox_area_increase); + final Rect region = new Rect(); + mCheckBox.getHitRect(region); + region.inset(-touchAreaIncrease, -touchAreaIncrease); + setTouchDelegate(new TouchDelegate(region, mCheckBox)); }); } diff --git a/src/com/android/messaging/ui/contact/ContactPickerFragment.java b/src/com/android/messaging/ui/contact/ContactPickerFragment.java index 1edf50b..7c41f7a 100644 --- a/src/com/android/messaging/ui/contact/ContactPickerFragment.java +++ b/src/com/android/messaging/ui/contact/ContactPickerFragment.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,7 +37,6 @@ import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; -import android.view.View.OnClickListener; import android.view.ViewGroup; import com.android.messaging.R; @@ -182,12 +182,7 @@ public class ContactPickerFragment extends Fragment implements ContactPickerData mToolbar = (Toolbar) view.findViewById(R.id.toolbar); mToolbar.setNavigationIcon(R.drawable.ic_arrow_back_light); mToolbar.setNavigationContentDescription(R.string.back); - mToolbar.setNavigationOnClickListener(new OnClickListener() { - @Override - public void onClick(final View v) { - mHost.onBackButtonPressed(); - } - }); + mToolbar.setNavigationOnClickListener(v -> mHost.onBackButtonPressed()); mToolbar.inflateMenu(R.menu.compose_menu); mToolbar.setOnMenuItemClickListener(this); @@ -325,13 +320,10 @@ public class ContactPickerFragment extends Fragment implements ContactPickerData // showImeKeyboard() won't work until the layout is ready, so wait until layout is complete // before showing the soft keyboard. - UiUtils.doOnceAfterLayoutChange(mRootView, new Runnable() { - @Override - public void run() { - final Activity activity = getActivity(); - if (activity != null) { - ImeUtil.get().showImeKeyboard(activity, mRecipientTextView); - } + UiUtils.doOnceAfterLayoutChange(mRootView, () -> { + final Activity activity = getActivity(); + if (activity != null) { + ImeUtil.get().showImeKeyboard(activity, mRecipientTextView); } }); mRecipientTextView.invalidate(); @@ -541,19 +533,13 @@ public class ContactPickerFragment extends Fragment implements ContactPickerData mCustomHeaderViewPager.animate().alpha(show ? 1F : 0F) .setStartDelay(!show ? UiUtils.COMPOSE_TRANSITION_DURATION : 0) - .withStartAction(new Runnable() { - @Override - public void run() { - mCustomHeaderViewPager.setVisibility(View.VISIBLE); - mCustomHeaderViewPager.setAlpha(show ? 0F : 1F); - } + .withStartAction(() -> { + mCustomHeaderViewPager.setVisibility(View.VISIBLE); + mCustomHeaderViewPager.setAlpha(show ? 0F : 1F); }) - .withEndAction(new Runnable() { - @Override - public void run() { - mCustomHeaderViewPager.setVisibility(show ? View.VISIBLE : View.GONE); - mCustomHeaderViewPager.setAlpha(1F); - } + .withEndAction(() -> { + mCustomHeaderViewPager.setVisibility(show ? View.VISIBLE : View.GONE); + mCustomHeaderViewPager.setAlpha(1F); }); } diff --git a/src/com/android/messaging/ui/contact/ContactRecipientPhotoManager.java b/src/com/android/messaging/ui/contact/ContactRecipientPhotoManager.java index d69ba64..a2b54a3 100644 --- a/src/com/android/messaging/ui/contact/ContactRecipientPhotoManager.java +++ b/src/com/android/messaging/ui/contact/ContactRecipientPhotoManager.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,38 +60,35 @@ public class ContactRecipientPhotoManager implements PhotoManager { public void populatePhotoBytesAsync(final RecipientEntry entry, final PhotoManagerCallback callback) { // Post all media resource request to the main thread. - ThreadUtil.getMainThreadHandler().post(new Runnable() { - @Override - public void run() { - final Uri avatarUri = AvatarUriUtil.createAvatarUri( - ParticipantData.getFromRecipientEntry(entry)); - final AvatarRequestDescriptor descriptor = - new AvatarRequestDescriptor(avatarUri, mIconSize, mIconSize); - final BindableMediaRequest req = descriptor.buildAsyncMediaRequest( - mContext, - new MediaResourceLoadListener() { - @Override - public void onMediaResourceLoaded(final MediaRequest request, - final ImageResource resource, final boolean isCached) { - entry.setPhotoBytes(resource.getBytes()); - callback.onPhotoBytesAsynchronouslyPopulated(); - } + ThreadUtil.getMainThreadHandler().post(() -> { + final Uri avatarUri = AvatarUriUtil.createAvatarUri( + ParticipantData.getFromRecipientEntry(entry)); + final AvatarRequestDescriptor descriptor = + new AvatarRequestDescriptor(avatarUri, mIconSize, mIconSize); + final BindableMediaRequest req = descriptor.buildAsyncMediaRequest( + mContext, + new MediaResourceLoadListener() { + @Override + public void onMediaResourceLoaded(final MediaRequest request, + final ImageResource resource, final boolean isCached) { + entry.setPhotoBytes(resource.getBytes()); + callback.onPhotoBytesAsynchronouslyPopulated(); + } - @Override - public void onMediaResourceLoadError(final MediaRequest request, - final Exception exception) { - LogUtil.e(LogUtil.BUGLE_TAG, "Photo bytes loading failed due to " + - exception + " request key=" + request.getKey()); + @Override + public void onMediaResourceLoadError(final MediaRequest request, + final Exception exception) { + LogUtil.e(LogUtil.BUGLE_TAG, "Photo bytes loading failed due to " + + exception + " request key=" + request.getKey()); - // Fall back to the default avatar image. - callback.onPhotoBytesAsyncLoadFailed(); - }}); + // Fall back to the default avatar image. + callback.onPhotoBytesAsyncLoadFailed(); + }}); - // Statically bind the request since it's not bound to any specific piece of UI. - req.bind(IMAGE_BYTES_REQUEST_STATIC_BINDING_ID); + // Statically bind the request since it's not bound to any specific piece of UI. + req.bind(IMAGE_BYTES_REQUEST_STATIC_BINDING_ID); - Factory.get().getMediaResourceManager().requestMediaResourceAsync(req); - } + Factory.get().getMediaResourceManager().requestMediaResourceAsync(req); }); } } diff --git a/src/com/android/messaging/ui/conversation/ComposeMessageView.java b/src/com/android/messaging/ui/conversation/ComposeMessageView.java index c0e0d99..025b634 100644 --- a/src/com/android/messaging/ui/conversation/ComposeMessageView.java +++ b/src/com/android/messaging/ui/conversation/ComposeMessageView.java @@ -51,7 +51,6 @@ import com.android.messaging.datamodel.data.ConversationData.ConversationDataLis import com.android.messaging.datamodel.data.ConversationData.SimpleConversationDataListener; import com.android.messaging.datamodel.data.DraftMessageData; import com.android.messaging.datamodel.data.DraftMessageData.CheckDraftForSendTask; -import com.android.messaging.datamodel.data.DraftMessageData.CheckDraftTaskCallback; import com.android.messaging.datamodel.data.DraftMessageData.DraftMessageDataListener; import com.android.messaging.datamodel.data.MessageData; import com.android.messaging.datamodel.data.MessagePartData; @@ -197,20 +196,14 @@ public class ComposeMessageView extends LinearLayout R.id.compose_message_text); mComposeEditText.setOnEditorActionListener(this); mComposeEditText.addTextChangedListener(this); - mComposeEditText.setOnFocusChangeListener(new OnFocusChangeListener() { - @Override - public void onFocusChange(final View v, final boolean hasFocus) { - if (v == mComposeEditText && hasFocus) { - mHost.onComposeEditTextFocused(); - } + mComposeEditText.setOnFocusChangeListener((v, hasFocus) -> { + if (v == mComposeEditText && hasFocus) { + mHost.onComposeEditTextFocused(); } }); - mComposeEditText.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View arg0) { - if (mHost.shouldHideAttachmentsWhenSimSelectorShown()) { - hideSimSelector(); - } + mComposeEditText.setOnClickListener(arg0 -> { + if (mHost.shouldHideAttachmentsWhenSimSelectorShown()) { + hideSimSelector(); } }); @@ -221,26 +214,20 @@ public class ComposeMessageView extends LinearLayout .getMaxTextLimit()) }); mSelfSendIcon = (SimIconView) findViewById(R.id.self_send_icon); - mSelfSendIcon.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { + mSelfSendIcon.setOnClickListener(v -> { + boolean shown = mInputManager.toggleSimSelector(true /* animate */, + getSelfSubscriptionListEntry()); + hideAttachmentsWhenShowingSims(shown); + }); + mSelfSendIcon.setOnLongClickListener(v -> { + if (mHost.shouldShowSubjectEditor()) { + showSubjectEditor(); + } else { boolean shown = mInputManager.toggleSimSelector(true /* animate */, getSelfSubscriptionListEntry()); hideAttachmentsWhenShowingSims(shown); } - }); - mSelfSendIcon.setOnLongClickListener(new OnLongClickListener() { - @Override - public boolean onLongClick(final View v) { - if (mHost.shouldShowSubjectEditor()) { - showSubjectEditor(); - } else { - boolean shown = mInputManager.toggleSimSelector(true /* animate */, - getSelfSubscriptionListEntry()); - hideAttachmentsWhenShowingSims(shown); - } - return true; - } + return true; }); mComposeSubjectText = (PlainTextEditText) findViewById( @@ -255,35 +242,25 @@ public class ComposeMessageView extends LinearLayout .getMaxSubjectLength())}); mDeleteSubjectButton = (ImageButton) findViewById(R.id.delete_subject_button); - mDeleteSubjectButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(final View clickView) { - hideSubjectEditor(); - mComposeSubjectText.setText(null); - mBinding.getData().setMessageSubject(null); - } + mDeleteSubjectButton.setOnClickListener(clickView -> { + hideSubjectEditor(); + mComposeSubjectText.setText(null); + mBinding.getData().setMessageSubject(null); }); mSubjectView = findViewById(R.id.subject_view); mSendButton = (ImageButton) findViewById(R.id.send_message_button); - mSendButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(final View clickView) { - sendMessageInternal(true /* checkMessageSize */); - } - }); - mSendButton.setOnLongClickListener(new OnLongClickListener() { - @Override - public boolean onLongClick(final View arg0) { - boolean shown = mInputManager.toggleSimSelector(true /* animate */, - getSelfSubscriptionListEntry()); - hideAttachmentsWhenShowingSims(shown); - if (mHost.shouldShowSubjectEditor()) { - showSubjectEditor(); - } - return true; + mSendButton.setOnClickListener(clickView -> + sendMessageInternal(true /* checkMessageSize */)); + mSendButton.setOnLongClickListener(arg0 -> { + boolean shown = mInputManager.toggleSimSelector(true /* animate */, + getSelfSubscriptionListEntry()); + hideAttachmentsWhenShowingSims(shown); + if (mHost.shouldShowSubjectEditor()) { + showSubjectEditor(); } + return true; }); mSendButton.setAccessibilityDelegate(new AccessibilityDelegate() { @Override @@ -306,12 +283,9 @@ public class ComposeMessageView extends LinearLayout mAttachMediaButton = (ImageButton) findViewById(R.id.attach_media_button); - mAttachMediaButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(final View clickView) { - // Showing the media picker is treated as starting to compose the message. - mInputManager.showHideMediaPicker(true /* show */, true /* animate */); - } + mAttachMediaButton.setOnClickListener(clickView -> { + // Showing the media picker is treated as starting to compose the message. + mInputManager.showHideMediaPicker(true /* show */, true /* animate */); }); mAttachmentPreview = (AttachmentPreview) findViewById(R.id.attachment_draft_view); @@ -394,69 +368,60 @@ public class ComposeMessageView extends LinearLayout mBinding.getData().setMessageSubject(subject); // Asynchronously check the draft against various requirements before sending. mBinding.getData().checkDraftForAction(checkMessageSize, - mHost.getConversationSelfSubId(), new CheckDraftTaskCallback() { - @Override - public void onDraftChecked(DraftMessageData data, int result) { - mBinding.ensureBound(data); - switch (result) { - case CheckDraftForSendTask.RESULT_PASSED: - // Continue sending after check succeeded. - final MessageData message = mBinding.getData() - .prepareMessageForSending(mBinding); - if (message != null && message.hasContent()) { - playSentSound(); - mHost.sendMessage(message); - hideSubjectEditor(); - if (AccessibilityUtil.isTouchExplorationEnabled(getContext())) { - AccessibilityUtil.announceForAccessibilityCompat( - ComposeMessageView.this, null, - R.string.sending_message); + mHost.getConversationSelfSubId(), (data, result) -> { + mBinding.ensureBound(data); + switch (result) { + case CheckDraftForSendTask.RESULT_PASSED: + // Continue sending after check succeeded. + final MessageData message = mBinding.getData() + .prepareMessageForSending(mBinding); + if (message != null && message.hasContent()) { + playSentSound(); + mHost.sendMessage(message); + hideSubjectEditor(); + if (AccessibilityUtil.isTouchExplorationEnabled(getContext())) { + AccessibilityUtil.announceForAccessibilityCompat( + ComposeMessageView.this, null, + R.string.sending_message); + } } - } - break; + break; - case CheckDraftForSendTask.RESULT_HAS_PENDING_ATTACHMENTS: - // Cannot send while there's still attachment(s) being loaded. - UiUtils.showToastAtBottom( - R.string.cant_send_message_while_loading_attachments); - break; + case CheckDraftForSendTask.RESULT_HAS_PENDING_ATTACHMENTS: + // Cannot send while there's still attachment(s) being loaded. + UiUtils.showToastAtBottom( + R.string.cant_send_message_while_loading_attachments); + break; - case CheckDraftForSendTask.RESULT_NO_SELF_PHONE_NUMBER_IN_GROUP_MMS: - mHost.promptForSelfPhoneNumber(); - break; + case CheckDraftForSendTask.RESULT_NO_SELF_PHONE_NUMBER_IN_GROUP_MMS: + mHost.promptForSelfPhoneNumber(); + break; - case CheckDraftForSendTask.RESULT_MESSAGE_OVER_LIMIT: - Assert.isTrue(checkMessageSize); - mHost.warnOfExceedingMessageLimit( - true /*sending*/, false /* tooManyVideos */); - break; + case CheckDraftForSendTask.RESULT_MESSAGE_OVER_LIMIT: + Assert.isTrue(checkMessageSize); + mHost.warnOfExceedingMessageLimit( + true /*sending*/, false /* tooManyVideos */); + break; - case CheckDraftForSendTask.RESULT_VIDEO_ATTACHMENT_LIMIT_EXCEEDED: - Assert.isTrue(checkMessageSize); - mHost.warnOfExceedingMessageLimit( - true /*sending*/, true /* tooManyVideos */); - break; + case CheckDraftForSendTask.RESULT_VIDEO_ATTACHMENT_LIMIT_EXCEEDED: + Assert.isTrue(checkMessageSize); + mHost.warnOfExceedingMessageLimit( + true /*sending*/, true /* tooManyVideos */); + break; - case CheckDraftForSendTask.RESULT_SIM_NOT_READY: - // Cannot send if there is no active subscription - UiUtils.showToastAtBottom( - R.string.cant_send_message_without_active_subscription); - break; + case CheckDraftForSendTask.RESULT_SIM_NOT_READY: + // Cannot send if there is no active subscription + UiUtils.showToastAtBottom( + R.string.cant_send_message_without_active_subscription); + break; - default: - break; - } - } - }, mBinding); - } else { - mHost.warnOfMissingActionConditions(true /*sending*/, - new Runnable() { - @Override - public void run() { - sendMessageInternal(checkMessageSize); + default: + break; } - - }); + }, mBinding); + } else { + mHost.warnOfMissingActionConditions(true /*sending*/, () -> + sendMessageInternal(checkMessageSize)); } } diff --git a/src/com/android/messaging/ui/conversation/ConversationFastScroller.java b/src/com/android/messaging/ui/conversation/ConversationFastScroller.java index e1f73c8..b60dff3 100644 --- a/src/com/android/messaging/ui/conversation/ConversationFastScroller.java +++ b/src/com/android/messaging/ui/conversation/ConversationFastScroller.java @@ -110,12 +110,9 @@ public class ConversationFastScroller extends RecyclerView.OnScrollListener impl private AnimatorSet mHideAnimation; private ObjectAnimator mHidePreviewAnimation; - private final Runnable mHideTrackRunnable = new Runnable() { - @Override - public void run() { - hide(true /* animate */); - mPendingHide = false; - } + private final Runnable mHideTrackRunnable = () -> { + hide(true /* animate */); + mPendingHide = false; }; private ConversationFastScroller(RecyclerView rv, int position) { diff --git a/src/com/android/messaging/ui/conversation/ConversationFragment.java b/src/com/android/messaging/ui/conversation/ConversationFragment.java index 053a57b..b6f8820 100644 --- a/src/com/android/messaging/ui/conversation/ConversationFragment.java +++ b/src/com/android/messaging/ui/conversation/ConversationFragment.java @@ -28,10 +28,6 @@ import android.content.BroadcastReceiver; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; -import android.content.DialogInterface; -import android.content.DialogInterface.OnCancelListener; -import android.content.DialogInterface.OnClickListener; -import android.content.DialogInterface.OnDismissListener; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Configuration; @@ -420,19 +416,13 @@ public class ConversationFragment extends Fragment implements ConversationDataLi mAdapter = new ConversationMessageAdapter(getActivity(), null, this, null, // Sets the item click listener on the Recycler item views. - new View.OnClickListener() { - @Override - public void onClick(final View v) { - final ConversationMessageView messageView = (ConversationMessageView) v; - handleMessageClick(messageView); - } + v -> { + final ConversationMessageView messageView = (ConversationMessageView) v; + handleMessageClick(messageView); }, - new View.OnLongClickListener() { - @Override - public boolean onLongClick(final View view) { - selectMessage((ConversationMessageView) view); - return true; - } + view -> { + selectMessage((ConversationMessageView) view); + return true; } ); } @@ -555,23 +545,17 @@ public class ConversationFragment extends Fragment implements ConversationDataLi view.setAlpha(0); mPopupTransitionAnimation = new PopupTransitionAnimation(startRect, view); - mPopupTransitionAnimation.setOnStartCallback(new Runnable() { - @Override - public void run() { - final int startWidth = composeBubbleRect.width(); - attachmentView.onMessageAnimationStart(); - messageBubble.kickOffMorphAnimation(startWidth, - messageBubble.findViewById(R.id.message_text_and_info) - .getMeasuredWidth()); - } - }); - mPopupTransitionAnimation.setOnStopCallback(new Runnable() { - @Override - public void run() { - view.setAlpha(1); - dispatchAddFinished(holder); - } - }); + mPopupTransitionAnimation.setOnStartCallback(() -> { + final int startWidth = composeBubbleRect.width(); + attachmentView.onMessageAnimationStart(); + messageBubble.kickOffMorphAnimation(startWidth, + messageBubble.findViewById(R.id.message_text_and_info) + .getMeasuredWidth()); + }); + mPopupTransitionAnimation.setOnStopCallback(() -> { + view.setAlpha(1); + dispatchAddFinished(holder); + }); mPopupTransitionAnimation.startAfterLayoutComplete(); mAddAnimations.add(holder); return true; @@ -827,13 +811,7 @@ public class ConversationFragment extends Fragment implements ConversationDataLi .setTitle(getResources().getQuantityString( R.plurals.delete_conversations_confirmation_dialog_title, 1)) .setPositiveButton(R.string.delete_conversation_confirmation_button, - new DialogInterface.OnClickListener() { - @Override - public void onClick(final DialogInterface dialog, - final int button) { - deleteConversation(); - } - }) + (dialog, button) -> deleteConversation()) .setNegativeButton(R.string.delete_conversation_decline_button, null) .show(); } else { @@ -894,12 +872,9 @@ public class ConversationFragment extends Fragment implements ConversationDataLi UiUtils.showSnackBarWithCustomAction(getActivity(), getView().getRootView(), getString(R.string.in_conversation_notify_new_message_text), - SnackBar.Action.createCustomAction(new Runnable() { - @Override - public void run() { - scrollToBottom(true /* smoothScroll */); - mComposeMessageView.hideAllComposeInputs(false /* animate */); - } + SnackBar.Action.createCustomAction(() -> { + scrollToBottom(true /* smoothScroll */); + mComposeMessageView.hideAllComposeInputs(false /* animate */); }, getString(R.string.in_conversation_notify_new_message_action)), null /* interactions */, @@ -1036,13 +1011,7 @@ public class ConversationFragment extends Fragment implements ConversationDataLi LogUtil.w(LogUtil.BUGLE_TAG, "Message can't be sent: conv participants not loaded"); } } else { - warnOfMissingActionConditions(true /*sending*/, - new Runnable() { - @Override - public void run() { - sendMessage(message); - } - }); + warnOfMissingActionConditions(true /*sending*/, () -> sendMessage(message)); } } @@ -1137,14 +1106,7 @@ public class ConversationFragment extends Fragment implements ConversationDataLi mBinding.getData().resendMessage(mBinding, messageId); } } else { - warnOfMissingActionConditions(true /*sending*/, - new Runnable() { - @Override - public void run() { - retrySend(messageId); - } - - }); + warnOfMissingActionConditions(true /*sending*/, () -> retrySend(messageId)); } } @@ -1154,12 +1116,8 @@ public class ConversationFragment extends Fragment implements ConversationDataLi .setTitle(R.string.delete_message_confirmation_dialog_title) .setMessage(R.string.delete_message_confirmation_dialog_text) .setPositiveButton(R.string.delete_message_confirmation_button, - new OnClickListener() { - @Override - public void onClick(final DialogInterface dialog, final int which) { - mBinding.getData().deleteMessage(mBinding, messageId); - } - }) + (dialog, which) -> + mBinding.getData().deleteMessage(mBinding, messageId)) .setNegativeButton(android.R.string.cancel, null); builder.setOnDismissListener(dialog -> mHost.dismissActionMode()); builder.create().show(); @@ -1506,19 +1464,11 @@ public class ConversationFragment extends Fragment implements ConversationDataLi } else { builder.setMessage(R.string.attachment_limit_reached_dialog_message_when_sending) .setNegativeButton(R.string.attachment_limit_reached_send_anyway, - new OnClickListener() { - @Override - public void onClick(final DialogInterface dialog, - final int which) { - composeMessageView.sendMessageIgnoreMessageSizeLimit(); - } - }); + (dialog, which) -> + composeMessageView.sendMessageIgnoreMessageSizeLimit()); } - builder.setPositiveButton(android.R.string.ok, new OnClickListener() { - @Override - public void onClick(final DialogInterface dialog, final int which) { - showAttachmentChooser(conversationId, activity); - }}); + builder.setPositiveButton(android.R.string.ok, (dialog, which) -> + showAttachmentChooser(conversationId, activity)); } else { builder.setMessage(R.string.attachment_limit_reached_dialog_message_when_composing) .setPositiveButton(android.R.string.ok, null); @@ -1557,12 +1507,7 @@ public class ConversationFragment extends Fragment implements ConversationDataLi final LayoutInflater inflator = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); customView = inflator.inflate(R.layout.action_bar_conversation_name, null); - customView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(final View v) { - onBackPressed(); - } - }); + customView.setOnClickListener(v -> onBackPressed()); actionBar.setCustomView(customView); } diff --git a/src/com/android/messaging/ui/conversation/ConversationMessageView.java b/src/com/android/messaging/ui/conversation/ConversationMessageView.java index 3c2f89a..bb2ceef 100644 --- a/src/com/android/messaging/ui/conversation/ConversationMessageView.java +++ b/src/com/android/messaging/ui/conversation/ConversationMessageView.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -123,12 +124,9 @@ public class ConversationMessageView extends FrameLayout implements View.OnClick @Override protected void onFinishInflate() { mContactIconView = (ContactIconView) findViewById(R.id.conversation_icon); - mContactIconView.setOnLongClickListener(new OnLongClickListener() { - @Override - public boolean onLongClick(final View view) { - ConversationMessageView.this.performLongClick(); - return true; - } + mContactIconView.setOnLongClickListener(view -> { + ConversationMessageView.this.performLongClick(); + return true; }); mMessageAttachmentsView = (LinearLayout) findViewById(R.id.message_attachments); @@ -1044,40 +1042,13 @@ public class ConversationMessageView extends FrameLayout implements View.OnClick } // Sort photos in MultiAttachLayout in the same order as the ConversationImagePartsView - static final Comparator sImageComparator = new Comparator(){ - @Override - public int compare(final MessagePartData x, final MessagePartData y) { - return x.getPartId().compareTo(y.getPartId()); - } - }; + static final Comparator sImageComparator = + Comparator.comparing(MessagePartData::getPartId); - static final Predicate sVideoFilter = new Predicate() { - @Override - public boolean apply(final MessagePartData part) { - return part.isVideo(); - } - }; - - static final Predicate sAudioFilter = new Predicate() { - @Override - public boolean apply(final MessagePartData part) { - return part.isAudio(); - } - }; - - static final Predicate sVCardFilter = new Predicate() { - @Override - public boolean apply(final MessagePartData part) { - return part.isVCard(); - } - }; - - static final Predicate sImageFilter = new Predicate() { - @Override - public boolean apply(final MessagePartData part) { - return part.isImage(); - } - }; + static final Predicate sVideoFilter = MessagePartData::isVideo; + static final Predicate sAudioFilter = MessagePartData::isAudio; + static final Predicate sVCardFilter = MessagePartData::isVCard; + static final Predicate sImageFilter = MessagePartData::isImage; interface AttachmentViewBinder { void bindView(View view, MessagePartData attachment); diff --git a/src/com/android/messaging/ui/conversation/ConversationSimSelector.java b/src/com/android/messaging/ui/conversation/ConversationSimSelector.java index 6d8f28f..3c11ecc 100644 --- a/src/com/android/messaging/ui/conversation/ConversationSimSelector.java +++ b/src/com/android/messaging/ui/conversation/ConversationSimSelector.java @@ -1,5 +1,6 @@ /* - * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,13 +49,10 @@ abstract class ConversationSimSelector extends ConversationInput { if (mPendingShow != null && mDataReady) { final boolean show = mPendingShow.first; final boolean animate = mPendingShow.second; - ThreadUtil.getMainThreadHandler().post(new Runnable() { - @Override - public void run() { - // This will No-Op if we are no longer attached to the host. - mConversationInputBase.showHideInternal(ConversationSimSelector.this, - show, animate); - } + ThreadUtil.getMainThreadHandler().post(() -> { + // This will No-Op if we are no longer attached to the host. + mConversationInputBase.showHideInternal(ConversationSimSelector.this, + show, animate); }); mPendingShow = null; } diff --git a/src/com/android/messaging/ui/conversation/EnterSelfPhoneNumberDialog.java b/src/com/android/messaging/ui/conversation/EnterSelfPhoneNumberDialog.java index e3ad601..4cf4d88 100644 --- a/src/com/android/messaging/ui/conversation/EnterSelfPhoneNumberDialog.java +++ b/src/com/android/messaging/ui/conversation/EnterSelfPhoneNumberDialog.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +20,6 @@ import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.Context; -import android.content.DialogInterface; import android.os.Bundle; import android.text.TextUtils; import android.view.LayoutInflater; @@ -53,30 +53,18 @@ public class EnterSelfPhoneNumberDialog extends DialogFragment { builder.setTitle(R.string.enter_phone_number_title) .setMessage(R.string.enter_phone_number_text) .setView(mEditText) - .setNegativeButton(android.R.string.cancel, - new DialogInterface.OnClickListener() { - @Override - public void onClick(final DialogInterface dialog, - final int button) { - dismiss(); - } - }) - .setPositiveButton(android.R.string.ok, - new DialogInterface.OnClickListener() { - @Override - public void onClick(final DialogInterface dialog, - final int button) { - final String newNumber = mEditText.getText().toString(); - dismiss(); - if (!TextUtils.isEmpty(newNumber)) { - savePhoneNumberInPrefs(newNumber); - // TODO: Remove this toast and just auto-send - // the message instead - UiUtils.showToast( - R.string - .toast_after_setting_default_sms_app_for_message_send); - } - } + .setNegativeButton(android.R.string.cancel, (dialog, button) -> dismiss()) + .setPositiveButton(android.R.string.ok, (dialog, button) -> { + final String newNumber = mEditText.getText().toString(); + dismiss(); + if (!TextUtils.isEmpty(newNumber)) { + savePhoneNumberInPrefs(newNumber); + // TODO: Remove this toast and just auto-send + // the message instead + UiUtils.showToast( + R.string + .toast_after_setting_default_sms_app_for_message_send); + } }); return builder.create(); } diff --git a/src/com/android/messaging/ui/conversation/SimSelectorItemView.java b/src/com/android/messaging/ui/conversation/SimSelectorItemView.java index 3058d31..a30d28d 100644 --- a/src/com/android/messaging/ui/conversation/SimSelectorItemView.java +++ b/src/com/android/messaging/ui/conversation/SimSelectorItemView.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +19,6 @@ package com.android.messaging.ui.conversation; import android.content.Context; import android.text.TextUtils; import android.util.AttributeSet; -import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; @@ -49,12 +49,7 @@ public class SimSelectorItemView extends LinearLayout { mNameTextView = (TextView) findViewById(R.id.name); mDetailsTextView = (TextView) findViewById(R.id.details); mSimIconView = (SimIconView) findViewById(R.id.sim_icon); - setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - mHost.onSimItemClicked(mData); - } - }); + setOnClickListener(v -> mHost.onSimItemClicked(mData)); } public void bind(final SubscriptionListEntry simEntry) { diff --git a/src/com/android/messaging/ui/conversation/SimSelectorView.java b/src/com/android/messaging/ui/conversation/SimSelectorView.java index bf4724d..d8f0f90 100644 --- a/src/com/android/messaging/ui/conversation/SimSelectorView.java +++ b/src/com/android/messaging/ui/conversation/SimSelectorView.java @@ -64,12 +64,7 @@ public class SimSelectorView extends FrameLayout implements SimSelectorItemView. mSimListView.setAdapter(mAdapter); // Clicking anywhere outside the switcher list should dismiss. - setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - showOrHide(false, true); - } - }); + setOnClickListener(v -> showOrHide(false, true)); } public void bind(final SubscriptionListData data) { @@ -102,12 +97,9 @@ public class SimSelectorView extends FrameLayout implements SimSelectorItemView. setAlpha(mShow ? 0.0f : 1.0f); animate().alpha(mShow ? 1.0f : 0.0f) .setDuration(UiUtils.REVEAL_ANIMATION_DURATION) - .withEndAction(new Runnable() { - @Override - public void run() { - setAlpha(1.0f); - setVisibility(mShow ? VISIBLE : GONE); - } + .withEndAction(() -> { + setAlpha(1.0f); + setVisibility(mShow ? VISIBLE : GONE); }); } else { setVisibility(mShow ? VISIBLE : GONE); diff --git a/src/com/android/messaging/ui/conversationlist/AbstractConversationListActivity.java b/src/com/android/messaging/ui/conversationlist/AbstractConversationListActivity.java index e7bfd66..5a72875 100644 --- a/src/com/android/messaging/ui/conversationlist/AbstractConversationListActivity.java +++ b/src/com/android/messaging/ui/conversationlist/AbstractConversationListActivity.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +20,6 @@ import android.app.Activity; import android.app.AlertDialog; import android.app.Fragment; import android.content.Context; -import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.net.Uri; @@ -118,14 +118,11 @@ public abstract class AbstractConversationListActivity extends BugleActionBarAc UiUtils.showSnackBarWithCustomAction(this, getWindow().getDecorView().getRootView(), getString(R.string.requires_default_sms_app), - SnackBar.Action.createCustomAction(new Runnable() { - @Override - public void run() { - final Intent intent = - UIIntents.get().getChangeDefaultSmsAppIntent(activity); - startActivityForResult(intent, REQUEST_SET_DEFAULT_SMS_APP); - } - }, + SnackBar.Action.createCustomAction(() -> { + final Intent intent = + UIIntents.get().getChangeDefaultSmsAppIntent(activity); + startActivityForResult(intent, REQUEST_SET_DEFAULT_SMS_APP); + }, getString(R.string.requires_default_sms_change_button)), null /* interactions */, null /* placement */); @@ -137,18 +134,14 @@ public abstract class AbstractConversationListActivity extends BugleActionBarAc R.plurals.delete_conversations_confirmation_dialog_title, conversations.size())) .setPositiveButton(R.string.delete_conversation_confirmation_button, - new DialogInterface.OnClickListener() { - @Override - public void onClick(final DialogInterface dialog, - final int button) { - for (final SelectedConversation conversation : conversations) { - DeleteConversationAction.deleteConversation( - conversation.conversationId, - conversation.timestamp); - } - exitMultiSelectState(); + (dialog, button) -> { + for (final SelectedConversation conversation : conversations) { + DeleteConversationAction.deleteConversation( + conversation.conversationId, + conversation.timestamp); } - }) + exitMultiSelectState(); + }) .setNegativeButton(R.string.delete_conversation_decline_button, null) .show(); } @@ -167,15 +160,12 @@ public abstract class AbstractConversationListActivity extends BugleActionBarAc } } - final Runnable undoRunnable = new Runnable() { - @Override - public void run() { - for (final String conversationId : conversationIds) { - if (isToArchive) { - UpdateConversationArchiveStatusAction.unarchiveConversation(conversationId); - } else { - UpdateConversationArchiveStatusAction.archiveConversation(conversationId); - } + final Runnable undoRunnable = () -> { + for (final String conversationId : conversationIds) { + if (isToArchive) { + UpdateConversationArchiveStatusAction.unarchiveConversation(conversationId); + } else { + UpdateConversationArchiveStatusAction.archiveConversation(conversationId); } } }; @@ -211,36 +201,29 @@ public abstract class AbstractConversationListActivity extends BugleActionBarAc conversation.otherParticipantNormalizedDestination)) .setMessage(res.getString(R.string.block_confirmation_message)) .setNegativeButton(android.R.string.cancel, null) - .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { - @Override - public void onClick(final DialogInterface arg0, final int arg1) { - final Context context = AbstractConversationListActivity.this; - final View listView = findViewById(android.R.id.list); - final List interactions = - mConversationListFragment.getSnackBarInteractions(); - final UpdateDestinationBlockedAction.UpdateDestinationBlockedActionListener - undoListener = - new UpdateDestinationBlockedActionSnackBar( - context, listView, null /* undoRunnable */, - interactions); - final Runnable undoRunnable = new Runnable() { - @Override - public void run() { - UpdateDestinationBlockedAction.updateDestinationBlocked( - conversation.otherParticipantNormalizedDestination, false, - conversation.conversationId, - undoListener); - } - }; - final UpdateDestinationBlockedAction.UpdateDestinationBlockedActionListener - listener = new UpdateDestinationBlockedActionSnackBar( - context, listView, undoRunnable, interactions); - UpdateDestinationBlockedAction.updateDestinationBlocked( - conversation.otherParticipantNormalizedDestination, true, - conversation.conversationId, - listener); - exitMultiSelectState(); - } + .setPositiveButton(android.R.string.ok, (arg0, arg1) -> { + final Context context = AbstractConversationListActivity.this; + final View listView = findViewById(android.R.id.list); + final List interactions = + mConversationListFragment.getSnackBarInteractions(); + final UpdateDestinationBlockedAction.UpdateDestinationBlockedActionListener + undoListener = + new UpdateDestinationBlockedActionSnackBar( + context, listView, null /* undoRunnable */, + interactions); + final Runnable undoRunnable = () -> + UpdateDestinationBlockedAction.updateDestinationBlocked( + conversation.otherParticipantNormalizedDestination, false, + conversation.conversationId, + undoListener); + final UpdateDestinationBlockedAction.UpdateDestinationBlockedActionListener + listener = new UpdateDestinationBlockedActionSnackBar( + context, listView, undoRunnable, interactions); + UpdateDestinationBlockedAction.updateDestinationBlocked( + conversation.otherParticipantNormalizedDestination, true, + conversation.conversationId, + listener); + exitMultiSelectState(); }) .create() .show(); diff --git a/src/com/android/messaging/ui/conversationlist/ConversationListFragment.java b/src/com/android/messaging/ui/conversationlist/ConversationListFragment.java index 1429a2d..89d05f0 100644 --- a/src/com/android/messaging/ui/conversationlist/ConversationListFragment.java +++ b/src/com/android/messaging/ui/conversationlist/ConversationListFragment.java @@ -35,7 +35,6 @@ import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; -import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.ViewGroup.MarginLayoutParams; import android.view.ViewPropertyAnimator; @@ -229,12 +228,8 @@ public class ConversationListFragment extends Fragment implements ConversationLi mStartNewConversationButton.setVisibility(View.GONE); } else { mStartNewConversationButton.setVisibility(View.VISIBLE); - mStartNewConversationButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(final View clickView) { - mHost.onCreateConversationClick(); - } - }); + mStartNewConversationButton.setOnClickListener(clickView -> + mHost.onCreateConversationClick()); } ViewCompat.setTransitionName(mStartNewConversationButton, BugleAnimationTags.TAG_FABICON); @@ -415,12 +410,9 @@ public class ConversationListFragment extends Fragment implements ConversationLi } public ViewPropertyAnimator showFab() { - return getNormalizedFabAnimator().translationX(0).withEndAction(new Runnable() { - @Override - public void run() { - // Re-enable clicks after the animation. - mStartNewConversationButton.setEnabled(true); - } + return getNormalizedFabAnimator().translationX(0).withEndAction(() -> { + // Re-enable clicks after the animation. + mStartNewConversationButton.setEnabled(true); }); } diff --git a/src/com/android/messaging/ui/conversationlist/ConversationListItemView.java b/src/com/android/messaging/ui/conversationlist/ConversationListItemView.java index 3e95299..50ca829 100644 --- a/src/com/android/messaging/ui/conversationlist/ConversationListItemView.java +++ b/src/com/android/messaging/ui/conversationlist/ConversationListItemView.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -552,12 +553,8 @@ public class ConversationListItemView extends FrameLayout implements OnClickList return; } UpdateConversationArchiveStatusAction.archiveConversation(conversationId); - final Runnable undoRunnable = new Runnable() { - @Override - public void run() { + final Runnable undoRunnable = () -> UpdateConversationArchiveStatusAction.unarchiveConversation(conversationId); - } - }; final String message = getResources().getString(R.string.archived_toast_message, 1); UiUtils.showSnackBar(getContext(), getRootView(), message, undoRunnable, SnackBar.Action.SNACK_BAR_UNDO, diff --git a/src/com/android/messaging/ui/conversationlist/ShareIntentFragment.java b/src/com/android/messaging/ui/conversationlist/ShareIntentFragment.java index e5d3c19..a99e46f 100644 --- a/src/com/android/messaging/ui/conversationlist/ShareIntentFragment.java +++ b/src/com/android/messaging/ui/conversationlist/ShareIntentFragment.java @@ -22,7 +22,6 @@ import android.app.AlertDialog.Builder; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; -import android.content.DialogInterface.OnClickListener; import android.database.Cursor; import android.os.Bundle; import androidx.recyclerview.widget.LinearLayoutManager; @@ -92,13 +91,10 @@ public class ShareIntentFragment extends DialogFragment implements ConversationL final Bundle arguments = getArguments(); if (arguments == null || !arguments.getBoolean(HIDE_NEW_CONVERSATION_BUTTON_KEY)) { - dialogBuilder.setPositiveButton(R.string.share_new_message, new OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - mDismissed = true; - mHost.onCreateConversationClick(); - } - }); + dialogBuilder.setPositiveButton(R.string.share_new_message, (dialog, which) -> { + mDismissed = true; + mHost.onCreateConversationClick(); + }); } return dialogBuilder.setNegativeButton(R.string.share_cancel, null) .create(); diff --git a/src/com/android/messaging/ui/conversationsettings/PeopleAndOptionsFragment.java b/src/com/android/messaging/ui/conversationsettings/PeopleAndOptionsFragment.java index e7be679..8ec63fb 100644 --- a/src/com/android/messaging/ui/conversationsettings/PeopleAndOptionsFragment.java +++ b/src/com/android/messaging/ui/conversationsettings/PeopleAndOptionsFragment.java @@ -21,7 +21,6 @@ import android.app.AlertDialog; import android.app.Fragment; import android.app.NotificationManager; import android.content.Context; -import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.database.Cursor; @@ -156,14 +155,10 @@ public class PeopleAndOptionsFragment extends Fragment item.getOtherParticipant().getDisplayDestination())) .setMessage(res.getString(R.string.block_confirmation_message)) .setNegativeButton(android.R.string.cancel, null) - .setPositiveButton(android.R.string.ok, - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface arg0, int arg1) { - mBinding.getData().setDestinationBlocked(mBinding, true); - activity.setResult(ConversationActivity.FINISH_RESULT_CODE); - activity.finish(); - } + .setPositiveButton(android.R.string.ok, (arg0, arg1) -> { + mBinding.getData().setDestinationBlocked(mBinding, true); + activity.setResult(ConversationActivity.FINISH_RESULT_CODE); + activity.finish(); }) .create() .show(); diff --git a/src/com/android/messaging/ui/conversationsettings/PeopleOptionsItemView.java b/src/com/android/messaging/ui/conversationsettings/PeopleOptionsItemView.java index 91fd10c..1d47b3b 100644 --- a/src/com/android/messaging/ui/conversationsettings/PeopleOptionsItemView.java +++ b/src/com/android/messaging/ui/conversationsettings/PeopleOptionsItemView.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +21,6 @@ import android.database.Cursor; import androidx.appcompat.widget.SwitchCompat; import android.text.TextUtils; import android.util.AttributeSet; -import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; @@ -55,12 +55,7 @@ public class PeopleOptionsItemView extends LinearLayout { @Override protected void onFinishInflate () { mTitle = (TextView) findViewById(R.id.title); - setOnClickListener(new OnClickListener() { - @Override - public void onClick(final View v) { - mHostInterface.onOptionsItemViewClicked(mData); - } - }); + setOnClickListener(v -> mHostInterface.onOptionsItemViewClicked(mData)); } public void bind(final Cursor cursor, final int columnIndex, ParticipantData otherParticipant, diff --git a/src/com/android/messaging/ui/debug/DebugMmsConfigItemView.java b/src/com/android/messaging/ui/debug/DebugMmsConfigItemView.java index 7b899c0..e6a4d9c 100644 --- a/src/com/android/messaging/ui/debug/DebugMmsConfigItemView.java +++ b/src/com/android/messaging/ui/debug/DebugMmsConfigItemView.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +19,6 @@ package com.android.messaging.ui.debug; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; -import android.content.DialogInterface.OnShowListener; import android.text.InputType; import android.util.AttributeSet; import android.view.View; @@ -115,14 +115,11 @@ public class DebugMmsConfigItemView extends LinearLayout implements OnClickListe .setPositiveButton(android.R.string.ok, this) .setNegativeButton(android.R.string.cancel, null) .create(); - dialog.setOnShowListener(new OnShowListener() { - @Override - public void onShow(DialogInterface dialog) { - mEditText.requestFocus(); - mEditText.selectAll(); - ((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE)) - .toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0); - } + dialog.setOnShowListener(dialog1 -> { + mEditText.requestFocus(); + mEditText.selectAll(); + ((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE)) + .toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0); }); dialog.show(); } diff --git a/src/com/android/messaging/ui/debug/DebugSmsMmsFromDumpFileDialogFragment.java b/src/com/android/messaging/ui/debug/DebugSmsMmsFromDumpFileDialogFragment.java index 4f46968..148dba1 100644 --- a/src/com/android/messaging/ui/debug/DebugSmsMmsFromDumpFileDialogFragment.java +++ b/src/com/android/messaging/ui/debug/DebugSmsMmsFromDumpFileDialogFragment.java @@ -29,7 +29,6 @@ import android.os.Environment; import android.telephony.SmsMessage; import android.view.LayoutInflater; import android.view.View; -import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; @@ -113,15 +112,12 @@ public class DebugSmsMmsFromDumpFileDialogFragment extends DialogFragment { final String file = getItem(position); actionItemView.setText(file); - actionItemView.setOnClickListener(new OnClickListener() { - @Override - public void onClick(final View view) { - dismiss(); - if (ACTION_LOAD.equals(mAction)) { - receiveFromDumpFile(file); - } else if (ACTION_EMAIL.equals(mAction)) { - emailDumpFile(file); - } + actionItemView.setOnClickListener(view1 -> { + dismiss(); + if (ACTION_LOAD.equals(mAction)) { + receiveFromDumpFile(file); + } else if (ACTION_EMAIL.equals(mAction)) { + emailDumpFile(file); } }); return actionItemView; diff --git a/src/com/android/messaging/ui/mediapicker/AudioRecordView.java b/src/com/android/messaging/ui/mediapicker/AudioRecordView.java index fba493f..7c5c980 100644 --- a/src/com/android/messaging/ui/mediapicker/AudioRecordView.java +++ b/src/com/android/messaging/ui/mediapicker/AudioRecordView.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -121,23 +122,20 @@ public class AudioRecordView extends FrameLayout implements mHintTextView = (TextView) findViewById(R.id.hint_text); mTimerTextView = (PausableChronometer) findViewById(R.id.timer_text); mSoundLevels.setLevelSource(mMediaRecorder.getLevelSource()); - mRecordButton.setOnTouchListener(new OnTouchListener() { - @Override - public boolean onTouch(final View v, final MotionEvent event) { - final int action = event.getActionMasked(); - switch (action) { - case MotionEvent.ACTION_DOWN: - onRecordButtonTouchDown(); + mRecordButton.setOnTouchListener((v, event) -> { + final int action = event.getActionMasked(); + switch (action) { + case MotionEvent.ACTION_DOWN: + onRecordButtonTouchDown(); - // Don't let the record button handle the down event to let it fall through - // so that we can handle it for the entire panel in onTouchEvent(). This is - // done so that: 1) the user taps on the record button to start recording - // 2) the entire panel owns the touch event so we'd keep recording even - // if the user moves outside the button region. - return false; - } - return false; + // Don't let the record button handle the down event to let it fall through + // so that we can handle it for the entire panel in onTouchEvent(). This is + // done so that: 1) the user taps on the record button to start recording + // 2) the entire panel owns the touch event so we'd keep recording even + // if the user moves outside the button region. + return false; } + return false; }); } @@ -242,18 +240,15 @@ public class AudioRecordView extends FrameLayout implements boolean onRecordButtonTouchDown() { if (!mMediaRecorder.isRecording() && mCurrentMode == MODE_IDLE) { setMode(MODE_STARTING); - playAudioStartSound(new OnCompletionListener() { - @Override - public void onCompletion() { - // Double-check the current mode before recording since the user may have - // lifted finger from the button before the beeping sound is played through. - final int maxSize = MmsConfig.get(mHostInterface.getConversationSelfSubId()) - .getMaxMessageSize(); - if (mCurrentMode == MODE_STARTING && - mMediaRecorder.startRecording(AudioRecordView.this, - AudioRecordView.this, maxSize)) { - setMode(MODE_RECORDING); - } + playAudioStartSound(() -> { + // Double-check the current mode before recording since the user may have + // lifted finger from the button before the beeping sound is played through. + final int maxSize = MmsConfig.get(mHostInterface.getConversationSelfSubId()) + .getMaxMessageSize(); + if (mCurrentMode == MODE_STARTING && + mMediaRecorder.startRecording(AudioRecordView.this, + AudioRecordView.this, maxSize)) { + setMode(MODE_RECORDING); } }); mAudioRecordStartTimeMillis = System.currentTimeMillis(); @@ -270,25 +265,17 @@ public class AudioRecordView extends FrameLayout implements // "tap+hold" to record audio. final Uri outputUri = stopRecording(); if (outputUri != null) { - SafeAsyncTask.executeOnThreadPool(new Runnable() { - @Override - public void run() { + SafeAsyncTask.executeOnThreadPool(() -> Factory.get().getApplicationContext().getContentResolver().delete( - outputUri, null, null); - } - }); + outputUri, null, null)); } setMode(MODE_IDLE); mHintTextView.setTypeface(null, Typeface.BOLD); } else if (isRecording()) { // Record for some extra time to ensure the ending part is saved. setMode(MODE_STOPPING); - ThreadUtil.getMainThreadHandler().postDelayed(new Runnable() { - @Override - public void run() { - onFinishedRecording(); - } - }, AUDIO_RECORD_ENDING_BUFFER_MILLIS); + ThreadUtil.getMainThreadHandler().postDelayed(this::onFinishedRecording, + AUDIO_RECORD_ENDING_BUFFER_MILLIS); } else { setMode(MODE_IDLE); } diff --git a/src/com/android/messaging/ui/mediapicker/CameraManager.java b/src/com/android/messaging/ui/mediapicker/CameraManager.java index c3ba751..68d7459 100644 --- a/src/com/android/messaging/ui/mediapicker/CameraManager.java +++ b/src/com/android/messaging/ui/mediapicker/CameraManager.java @@ -35,7 +35,6 @@ import android.util.DisplayMetrics; import android.view.MotionEvent; import android.view.OrientationEventListener; import android.view.Surface; -import android.view.View; import android.view.WindowManager; import com.android.messaging.datamodel.data.DraftMessageData.DraftMessageSubscriptionDataProvider; @@ -268,18 +267,15 @@ class CameraManager implements FocusOverlayManager.Listener { if (preview != null) { Assert.isTrue(preview.isValid()); - preview.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(final View view, final MotionEvent motionEvent) { - if ((motionEvent.getActionMasked() & MotionEvent.ACTION_UP) == - MotionEvent.ACTION_UP) { - mFocusOverlayManager.setPreviewSize(view.getWidth(), view.getHeight()); - mFocusOverlayManager.onSingleTapUp( - (int) motionEvent.getX() + view.getLeft(), - (int) motionEvent.getY() + view.getTop()); - } - return true; + preview.setOnTouchListener((view, motionEvent) -> { + if ((motionEvent.getActionMasked() & MotionEvent.ACTION_UP) == + MotionEvent.ACTION_UP) { + mFocusOverlayManager.setPreviewSize(view.getWidth(), view.getHeight()); + mFocusOverlayManager.onSingleTapUp( + (int) motionEvent.getX() + view.getLeft(), + (int) motionEvent.getY() + view.getTop()); } + return true; }); } mCameraPreview = preview; @@ -542,36 +538,33 @@ class CameraManager implements FocusOverlayManager.Listener { callback.onMediaFailed(null); return; } - final Camera.PictureCallback jpegCallback = new Camera.PictureCallback() { - @Override - public void onPictureTaken(final byte[] bytes, final Camera camera) { - mTakingPicture = false; - if (mCamera != camera) { - // This may happen if the camera was changed between front/back while the - // picture is being taken. - callback.onMediaInfo(MediaCallback.MEDIA_CAMERA_CHANGED); - return; - } - - if (bytes == null) { - callback.onMediaInfo(MediaCallback.MEDIA_NO_DATA); - return; - } - - final Camera.Size size = camera.getParameters().getPictureSize(); - int width; - int height; - if (mRotation == 90 || mRotation == 270) { - width = size.height; - height = size.width; - } else { - width = size.width; - height = size.height; - } - new ImagePersistTask( - width, height, heightPercent, bytes, mCameraPreview.getContext(), callback) - .executeOnThreadPool(); + final Camera.PictureCallback jpegCallback = (bytes, camera) -> { + mTakingPicture = false; + if (mCamera != camera) { + // This may happen if the camera was changed between front/back while the + // picture is being taken. + callback.onMediaInfo(MediaCallback.MEDIA_CAMERA_CHANGED); + return; } + + if (bytes == null) { + callback.onMediaInfo(MediaCallback.MEDIA_NO_DATA); + return; + } + + final Camera.Size size = camera.getParameters().getPictureSize(); + int width; + int height; + if (mRotation == 90 || mRotation == 270) { + width = size.height; + height = size.width; + } else { + width = size.width; + height = size.height; + } + new ImagePersistTask( + width, height, heightPercent, bytes, mCameraPreview.getContext(), callback) + .executeOnThreadPool(); }; mTakingPicture = true; @@ -757,12 +750,8 @@ class CameraManager implements FocusOverlayManager.Listener { mCamera.setParameters(params); mCameraPreview.startPreview(mCamera); mCamera.startPreview(); - mCamera.setAutoFocusMoveCallback(new Camera.AutoFocusMoveCallback() { - @Override - public void onAutoFocusMoving(final boolean start, final Camera camera) { - mFocusOverlayManager.onAutoFocusMoving(start); - } - }); + mCamera.setAutoFocusMoveCallback((start, camera) -> + mFocusOverlayManager.onAutoFocusMoving(start)); mFocusOverlayManager.setParameters(mCamera.getParameters()); mFocusOverlayManager.setMirror(mCameraInfo.facing == CameraInfo.CAMERA_FACING_BACK); mFocusOverlayManager.onPreviewStarted(); @@ -830,24 +819,17 @@ class CameraManager implements FocusOverlayManager.Listener { return; } - mMediaRecorder.setOnErrorListener(new MediaRecorder.OnErrorListener() { - @Override - public void onError(final MediaRecorder mediaRecorder, final int what, - final int extra) { - if (mListener != null) { - mListener.onCameraError(ERROR_RECORDING_VIDEO, null); - } - restoreRequestedOrientation(); + mMediaRecorder.setOnErrorListener((mediaRecorder, what, extra) -> { + if (mListener != null) { + mListener.onCameraError(ERROR_RECORDING_VIDEO, null); } + restoreRequestedOrientation(); }); - mMediaRecorder.setOnInfoListener(new MediaRecorder.OnInfoListener() { - @Override - public void onInfo(final MediaRecorder mediaRecorder, final int what, final int extra) { - if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED || - what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED) { - stopVideo(); - } + mMediaRecorder.setOnInfoListener((mediaRecorder, what, extra) -> { + if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED || + what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED) { + stopVideo(); } }); @@ -1094,12 +1076,8 @@ class CameraManager implements FocusOverlayManager.Listener { } try { - mCamera.autoFocus(new Camera.AutoFocusCallback() { - @Override - public void onAutoFocus(final boolean success, final Camera camera) { - mFocusOverlayManager.onAutoFocus(success, false /* shutterDown */); - } - }); + mCamera.autoFocus((success, camera) -> mFocusOverlayManager.onAutoFocus(success, + false /* shutterDown */)); } catch (final RuntimeException e) { LogUtil.e(TAG, "RuntimeException in CameraManager.autoFocus", e); // If autofocus fails, the camera should have called the callback with success=false, diff --git a/src/com/android/messaging/ui/mediapicker/CameraMediaChooser.java b/src/com/android/messaging/ui/mediapicker/CameraMediaChooser.java index 75f76ab..a1a8824 100644 --- a/src/com/android/messaging/ui/mediapicker/CameraMediaChooser.java +++ b/src/com/android/messaging/ui/mediapicker/CameraMediaChooser.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +25,6 @@ import android.hardware.Camera; import android.net.Uri; import android.os.SystemClock; import android.view.LayoutInflater; -import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; @@ -92,120 +92,98 @@ class CameraMediaChooser extends MediaChooser implements false /* attachToRoot */); mCameraPreviewHost = (CameraPreview.CameraPreviewHost) view.findViewById( R.id.camera_preview); - mCameraPreviewHost.getView().setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(final View view, final MotionEvent motionEvent) { - if (CameraManager.get().isVideoMode()) { - // Prevent the swipe down in video mode because video is always captured in - // full screen - return true; - } - - return false; + mCameraPreviewHost.getView().setOnTouchListener((view1, motionEvent) -> { + if (CameraManager.get().isVideoMode()) { + // Prevent the swipe down in video mode because video is always captured in + // full screen + return true; } + + return false; }); final View shutterVisual = view.findViewById(R.id.camera_shutter_visual); mFullScreenButton = (ImageButton) view.findViewById(R.id.camera_fullScreen_button); - mFullScreenButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(final View view) { - mMediaPicker.setFullScreen(true); - } - }); + mFullScreenButton.setOnClickListener(view12 -> mMediaPicker.setFullScreen(true)); mSwapCameraButton = (ImageButton) view.findViewById(R.id.camera_swapCamera_button); - mSwapCameraButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(final View view) { - CameraManager.get().swapCamera(); - } - }); + mSwapCameraButton.setOnClickListener(view13 -> CameraManager.get().swapCamera()); mCaptureButton = (ImageButton) view.findViewById(R.id.camera_capture_button); - mCaptureButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(final View v) { - final float heightPercent = Math.min(mMediaPicker.getViewPager().getHeight() / - (float) mCameraPreviewHost.getView().getHeight(), 1); + mCaptureButton.setOnClickListener(v -> { + final float heightPercent = Math.min(mMediaPicker.getViewPager().getHeight() / + (float) mCameraPreviewHost.getView().getHeight(), 1); - if (CameraManager.get().isRecording()) { - CameraManager.get().stopVideo(); - } else { - final CameraManager.MediaCallback callback = new CameraManager.MediaCallback() { - @Override - public void onMediaReady( - final Uri uriToVideo, final String contentType, - final int width, final int height) { - mVideoCounter.stop(); - if (mVideoCancelled || uriToVideo == null) { - mVideoCancelled = false; - } else { - final Rect startRect = new Rect(); - // It's possible to throw out the chooser while taking the - // picture/video. In that case, still use the attachment, just - // skip the startRect - if (mView != null) { - mView.getGlobalVisibleRect(startRect); - } - mMediaPicker.dispatchItemsSelected( - new MediaPickerMessagePartData(startRect, contentType, - uriToVideo, width, height), - true /* dismissMediaPicker */); + if (CameraManager.get().isRecording()) { + CameraManager.get().stopVideo(); + } else { + final MediaCallback callback = new MediaCallback() { + @Override + public void onMediaReady( + final Uri uriToVideo, final String contentType, + final int width, final int height) { + mVideoCounter.stop(); + if (mVideoCancelled || uriToVideo == null) { + mVideoCancelled = false; + } else { + final Rect startRect = new Rect(); + // It's possible to throw out the chooser while taking the + // picture/video. In that case, still use the attachment, just + // skip the startRect + if (mView != null) { + mView.getGlobalVisibleRect(startRect); } - updateViewState(); + mMediaPicker.dispatchItemsSelected( + new MediaPickerMessagePartData(startRect, contentType, + uriToVideo, width, height), + true /* dismissMediaPicker */); } - - @Override - public void onMediaFailed(final Exception exception) { - UiUtils.showToastAtBottom(R.string.camera_media_failure); - updateViewState(); - } - - @Override - public void onMediaInfo(final int what) { - if (what == MediaCallback.MEDIA_NO_DATA) { - UiUtils.showToastAtBottom(R.string.camera_media_failure); - } - updateViewState(); - } - }; - if (CameraManager.get().isVideoMode()) { - CameraManager.get().startVideo(callback); - mVideoCounter.setBase(SystemClock.elapsedRealtime()); - mVideoCounter.start(); - updateViewState(); - } else { - showShutterEffect(shutterVisual); - CameraManager.get().takePicture(heightPercent, callback); updateViewState(); } + + @Override + public void onMediaFailed(final Exception exception) { + UiUtils.showToastAtBottom(R.string.camera_media_failure); + updateViewState(); + } + + @Override + public void onMediaInfo(final int what) { + if (what == MediaCallback.MEDIA_NO_DATA) { + UiUtils.showToastAtBottom(R.string.camera_media_failure); + } + updateViewState(); + } + }; + if (CameraManager.get().isVideoMode()) { + CameraManager.get().startVideo(callback); + mVideoCounter.setBase(SystemClock.elapsedRealtime()); + mVideoCounter.start(); + updateViewState(); + } else { + showShutterEffect(shutterVisual); + CameraManager.get().takePicture(heightPercent, callback); + updateViewState(); } } }); mSwapModeButton = (ImageButton) view.findViewById(R.id.camera_swap_mode_button); - mSwapModeButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(final View view) { - final boolean isSwitchingToVideo = !CameraManager.get().isVideoMode(); - if (isSwitchingToVideo && !OsUtil.hasRecordAudioPermission()) { - requestRecordAudioPermission(); - } else { - onSwapMode(); - } + mSwapModeButton.setOnClickListener(view14 -> { + final boolean isSwitchingToVideo = !CameraManager.get().isVideoMode(); + if (isSwitchingToVideo && !OsUtil.hasRecordAudioPermission()) { + requestRecordAudioPermission(); + } else { + onSwapMode(); } }); mCancelVideoButton = (ImageButton) view.findViewById(R.id.camera_cancel_button); - mCancelVideoButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(final View view) { - mVideoCancelled = true; - CameraManager.get().stopVideo(); - mMediaPicker.dismiss(true); - } + mCancelVideoButton.setOnClickListener(view15 -> { + mVideoCancelled = true; + CameraManager.get().stopVideo(); + mMediaPicker.dismiss(true); }); mVideoCounter = (Chronometer) view.findViewById(R.id.camera_video_counter); diff --git a/src/com/android/messaging/ui/mediapicker/CameraMediaChooserView.java b/src/com/android/messaging/ui/mediapicker/CameraMediaChooserView.java index bc503d0..6cb2e37 100644 --- a/src/com/android/messaging/ui/mediapicker/CameraMediaChooserView.java +++ b/src/com/android/messaging/ui/mediapicker/CameraMediaChooserView.java @@ -83,23 +83,20 @@ public class CameraMediaChooserView extends FrameLayout implements PersistentIns if (!canvas.isHardwareAccelerated() && !mIsSoftwareFallbackActive) { mIsSoftwareFallbackActive = true; // Post modifying the tree since we can't modify the view tree during a draw pass - ThreadUtil.getMainThreadHandler().post(new Runnable() { - @Override - public void run() { - final HardwareCameraPreview cameraPreview = - (HardwareCameraPreview) findViewById(R.id.camera_preview); - if (cameraPreview == null) { - return; - } - final ViewGroup parent = ((ViewGroup) cameraPreview.getParent()); - final int index = parent.indexOfChild(cameraPreview); - final SoftwareCameraPreview softwareCameraPreview = - new SoftwareCameraPreview(getContext()); - // Be sure to remove the hardware view before adding the software view to - // prevent having 2 camera previews active at the same time - parent.removeView(cameraPreview); - parent.addView(softwareCameraPreview, index); + ThreadUtil.getMainThreadHandler().post(() -> { + final HardwareCameraPreview cameraPreview = + (HardwareCameraPreview) findViewById(R.id.camera_preview); + if (cameraPreview == null) { + return; } + final ViewGroup parent = ((ViewGroup) cameraPreview.getParent()); + final int index = parent.indexOfChild(cameraPreview); + final SoftwareCameraPreview softwareCameraPreview = + new SoftwareCameraPreview(getContext()); + // Be sure to remove the hardware view before adding the software view to + // prevent having 2 camera previews active at the same time + parent.removeView(cameraPreview); + parent.addView(softwareCameraPreview, index); }); } } diff --git a/src/com/android/messaging/ui/mediapicker/ContactMediaChooser.java b/src/com/android/messaging/ui/mediapicker/ContactMediaChooser.java index 3b337e8..ad05ca5 100644 --- a/src/com/android/messaging/ui/mediapicker/ContactMediaChooser.java +++ b/src/com/android/messaging/ui/mediapicker/ContactMediaChooser.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2020 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -77,14 +78,10 @@ class ContactMediaChooser extends MediaChooser { false /* attachToRoot */); mEnabledView = view.findViewById(R.id.mediapicker_enabled); mMissingPermissionView = view.findViewById(R.id.missing_permission_view); - mEnabledView.setOnClickListener( - new View.OnClickListener() { - @Override - public void onClick(final View v) { - // Launch an external picker to pick a contact as attachment. - UIIntents.get().launchContactCardPicker(mMediaPicker); - } - }); + mEnabledView.setOnClickListener(v -> { + // Launch an external picker to pick a contact as attachment. + UIIntents.get().launchContactCardPicker(mMediaPicker); + }); return view; } @@ -128,14 +125,11 @@ class ContactMediaChooser extends MediaChooser { } final Uri vCardUri = Uri.withAppendedPath(Contacts.CONTENT_VCARD_URI, lookupKey); if (vCardUri != null) { - SafeAsyncTask.executeOnThreadPool(new Runnable() { - @Override - public void run() { - final PendingAttachmentData pendingItem = - PendingAttachmentData.createPendingAttachmentData( - ContentType.TEXT_X_VCARD.toLowerCase(), vCardUri); - mMediaPicker.dispatchPendingItemAdded(pendingItem); - } + SafeAsyncTask.executeOnThreadPool(() -> { + final PendingAttachmentData pendingItem = + PendingAttachmentData.createPendingAttachmentData( + ContentType.TEXT_X_VCARD.toLowerCase(), vCardUri); + mMediaPicker.dispatchPendingItemAdded(pendingItem); }); } } diff --git a/src/com/android/messaging/ui/mediapicker/GalleryGridItemView.java b/src/com/android/messaging/ui/mediapicker/GalleryGridItemView.java index cf4357b..c336c01 100644 --- a/src/com/android/messaging/ui/mediapicker/GalleryGridItemView.java +++ b/src/com/android/messaging/ui/mediapicker/GalleryGridItemView.java @@ -92,12 +92,9 @@ public class GalleryGridItemView extends FrameLayout { mFileName = (TextView) findViewById(R.id.file_name); mFileType = (TextView) findViewById(R.id.file_type); setOnClickListener(mOnClickListener); - final OnLongClickListener longClickListener = new OnLongClickListener() { - @Override - public boolean onLongClick(final View v) { - mHostInterface.onItemClicked(v, mData, true /* longClick */); - return true; - } + final OnLongClickListener longClickListener = v -> { + mHostInterface.onItemClicked(v, mData, true /* longClick */); + return true; }; setOnLongClickListener(longClickListener); mCheckBox.setOnLongClickListener(longClickListener); diff --git a/src/com/android/messaging/ui/mediapicker/GalleryMediaChooser.java b/src/com/android/messaging/ui/mediapicker/GalleryMediaChooser.java index 9e9ffb1..29a1f5a 100644 --- a/src/com/android/messaging/ui/mediapicker/GalleryMediaChooser.java +++ b/src/com/android/messaging/ui/mediapicker/GalleryMediaChooser.java @@ -38,9 +38,7 @@ import com.android.messaging.datamodel.data.GalleryGridItemData; import com.android.messaging.datamodel.data.MediaPickerData; import com.android.messaging.datamodel.data.MessagePartData; import com.android.messaging.datamodel.data.MediaPickerData.MediaPickerDataListener; -import com.android.messaging.datamodel.data.PendingAttachmentData; import com.android.messaging.ui.UIIntents; -import com.android.messaging.ui.mediapicker.DocumentImagePicker.SelectionListener; import com.android.messaging.util.Assert; import com.android.messaging.util.OsUtil; @@ -59,15 +57,11 @@ class GalleryMediaChooser extends MediaChooser implements GalleryMediaChooser(final MediaPicker mediaPicker) { super(mediaPicker); mAdapter = new GalleryGridAdapter(Factory.get().getApplicationContext(), null); - mDocumentImagePicker = new DocumentImagePicker(mMediaPicker, - new SelectionListener() { - @Override - public void onDocumentSelected(final PendingAttachmentData data) { - if (mBindingRef.isBound()) { - mMediaPicker.dispatchPendingItemAdded(data); - } - } - }); + mDocumentImagePicker = new DocumentImagePicker(mMediaPicker, data -> { + if (mBindingRef.isBound()) { + mMediaPicker.dispatchPendingItemAdded(data); + } + }); } @Override diff --git a/src/com/android/messaging/ui/mediapicker/LevelTrackingMediaRecorder.java b/src/com/android/messaging/ui/mediapicker/LevelTrackingMediaRecorder.java index 06730a3..2507b36 100644 --- a/src/com/android/messaging/ui/mediapicker/LevelTrackingMediaRecorder.java +++ b/src/com/android/messaging/ui/mediapicker/LevelTrackingMediaRecorder.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -146,13 +147,9 @@ public class LevelTrackingMediaRecorder { "media recorder. " + ex); if (mOutputUri != null) { final Uri outputUri = mOutputUri; - SafeAsyncTask.executeOnThreadPool(new Runnable() { - @Override - public void run() { + SafeAsyncTask.executeOnThreadPool(() -> Factory.get().getApplicationContext().getContentResolver().delete( - outputUri, null, null); - } - }); + outputUri, null, null)); mOutputUri = null; } } finally { @@ -191,26 +188,23 @@ public class LevelTrackingMediaRecorder { private void startTrackingSoundLevel() { stopTrackingSoundLevel(); - mRefreshLevelThread = new Thread() { - @Override - public void run() { - try { - while (true) { - synchronized (LevelTrackingMediaRecorder.class) { - if (mRecorder != null) { - mLevelSource.setSpeechLevel(getAmplitude()); - } else { - // The recording session is over, finish the thread. - return; - } + mRefreshLevelThread = new Thread(() -> { + try { + while (true) { + synchronized (LevelTrackingMediaRecorder.class) { + if (mRecorder != null) { + mLevelSource.setSpeechLevel(getAmplitude()); + } else { + // The recording session is over, finish the thread. + return; } - Thread.sleep(REFRESH_INTERVAL_MILLIS); } - } catch (final InterruptedException e) { - Thread.currentThread().interrupt(); + Thread.sleep(REFRESH_INTERVAL_MILLIS); } + } catch (final InterruptedException e) { + Thread.currentThread().interrupt(); } - }; + }); mRefreshLevelThread.start(); } diff --git a/src/com/android/messaging/ui/mediapicker/MediaChooser.java b/src/com/android/messaging/ui/mediapicker/MediaChooser.java index e4a0941..d78760d 100644 --- a/src/com/android/messaging/ui/mediapicker/MediaChooser.java +++ b/src/com/android/messaging/ui/mediapicker/MediaChooser.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +25,6 @@ import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; -import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; @@ -93,12 +93,7 @@ abstract class MediaChooser extends BasePagerViewHolder mTabButton.setContentDescription( inflater.getContext().getResources().getString(getIconDescriptionResource())); setSelected(mSelected); - mTabButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(final View view) { - mMediaPicker.selectChooser(MediaChooser.this); - } - }); + mTabButton.setOnClickListener(view -> mMediaPicker.selectChooser(MediaChooser.this)); } protected Context getContext() { diff --git a/src/com/android/messaging/ui/mediapicker/MediaPicker.java b/src/com/android/messaging/ui/mediapicker/MediaPicker.java index 05dda18..2d81584 100644 --- a/src/com/android/messaging/ui/mediapicker/MediaPicker.java +++ b/src/com/android/messaging/ui/mediapicker/MediaPicker.java @@ -543,12 +543,7 @@ public class MediaPicker extends Fragment implements DraftMessageSubscriptionDat mOpen = true; mPagerAdapter.notifyDataSetChanged(); if (mListener != null) { - mListenerHandler.post(new Runnable() { - @Override - public void run() { - mListener.onOpened(); - } - }); + mListenerHandler.post(() -> mListener.onOpened()); } if (mSelectedChooser != null) { mSelectedChooser.onFullScreenChanged(false); @@ -560,12 +555,7 @@ public class MediaPicker extends Fragment implements DraftMessageSubscriptionDat setHasOptionsMenu(false); mOpen = false; if (mListener != null) { - mListenerHandler.post(new Runnable() { - @Override - public void run() { - mListener.onDismissed(); - } - }); + mListenerHandler.post(() -> mListener.onDismissed()); } if (mSelectedChooser != null) { mSelectedChooser.onOpenedChanged(false); @@ -575,12 +565,7 @@ public class MediaPicker extends Fragment implements DraftMessageSubscriptionDat void dispatchFullScreen(final boolean fullScreen) { setHasOptionsMenu(fullScreen); if (mListener != null) { - mListenerHandler.post(new Runnable() { - @Override - public void run() { - mListener.onFullScreenChanged(fullScreen); - } - }); + mListenerHandler.post(() -> mListener.onFullScreenChanged(fullScreen)); } if (mSelectedChooser != null) { mSelectedChooser.onFullScreenChanged(fullScreen); @@ -596,12 +581,7 @@ public class MediaPicker extends Fragment implements DraftMessageSubscriptionDat void dispatchItemsSelected(final Collection items, final boolean dismissMediaPicker) { if (mListener != null) { - mListenerHandler.post(new Runnable() { - @Override - public void run() { - mListener.onItemsSelected(items, dismissMediaPicker); - } - }); + mListenerHandler.post(() -> mListener.onItemsSelected(items, dismissMediaPicker)); } if (isFullScreen() && !dismissMediaPicker) { @@ -611,12 +591,7 @@ public class MediaPicker extends Fragment implements DraftMessageSubscriptionDat void dispatchItemUnselected(final MessagePartData item) { if (mListener != null) { - mListenerHandler.post(new Runnable() { - @Override - public void run() { - mListener.onItemUnselected(item); - } - }); + mListenerHandler.post(() -> mListener.onItemUnselected(item)); } if (isFullScreen()) { @@ -626,23 +601,13 @@ public class MediaPicker extends Fragment implements DraftMessageSubscriptionDat void dispatchConfirmItemSelection() { if (mListener != null) { - mListenerHandler.post(new Runnable() { - @Override - public void run() { - mListener.onConfirmItemSelection(); - } - }); + mListenerHandler.post(() -> mListener.onConfirmItemSelection()); } } void dispatchPendingItemAdded(final PendingAttachmentData pendingItem) { if (mListener != null) { - mListenerHandler.post(new Runnable() { - @Override - public void run() { - mListener.onPendingItemAdded(pendingItem); - } - }); + mListenerHandler.post(() -> mListener.onPendingItemAdded(pendingItem)); } if (isFullScreen()) { @@ -652,12 +617,7 @@ public class MediaPicker extends Fragment implements DraftMessageSubscriptionDat void dispatchChooserSelected(final int chooserIndex) { if (mListener != null) { - mListenerHandler.post(new Runnable() { - @Override - public void run() { - mListener.onChooserSelected(chooserIndex); - } - }); + mListenerHandler.post(() -> mListener.onChooserSelected(chooserIndex)); } } diff --git a/src/com/android/messaging/ui/mediapicker/MediaPickerPanel.java b/src/com/android/messaging/ui/mediapicker/MediaPickerPanel.java index de2be00..5f09db0 100644 --- a/src/com/android/messaging/ui/mediapicker/MediaPickerPanel.java +++ b/src/com/android/messaging/ui/mediapicker/MediaPickerPanel.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -250,12 +251,7 @@ public class MediaPickerPanel extends ViewGroup { } mFullScreen = false; mExpanded = expanded; - mHandler.post(new Runnable() { - @Override - public void run() { - setDesiredHeight(getDesiredHeight(), animate); - } - }); + mHandler.post(() -> setDesiredHeight(getDesiredHeight(), animate)); if (expanded) { setupViewPager(startingPage); mMediaPicker.dispatchOpened(); diff --git a/src/com/android/messaging/ui/mediapicker/MmsVideoRecorder.java b/src/com/android/messaging/ui/mediapicker/MmsVideoRecorder.java index 89241b7..4b1b4d6 100644 --- a/src/com/android/messaging/ui/mediapicker/MmsVideoRecorder.java +++ b/src/com/android/messaging/ui/mediapicker/MmsVideoRecorder.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -110,13 +111,9 @@ class MmsVideoRecorder extends MediaRecorder { void cleanupTempFile() { final Uri tempUri = mTempVideoUri; - SafeAsyncTask.executeOnThreadPool(new Runnable() { - @Override - public void run() { + SafeAsyncTask.executeOnThreadPool(() -> Factory.get().getApplicationContext().getContentResolver().delete( - tempUri, null, null); - } - }); + tempUri, null, null)); mTempVideoUri = null; } diff --git a/src/com/android/messaging/ui/mediapicker/SoundLevels.java b/src/com/android/messaging/ui/mediapicker/SoundLevels.java index 728d6be..c0785c9 100644 --- a/src/com/android/messaging/ui/mediapicker/SoundLevels.java +++ b/src/com/android/messaging/ui/mediapicker/SoundLevels.java @@ -18,7 +18,6 @@ package com.android.messaging.ui.mediapicker; import android.animation.ObjectAnimator; import android.animation.TimeAnimator; -import android.animation.TimeAnimator.TimeListener; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; @@ -107,13 +106,7 @@ public class SoundLevels extends View { // which might improve things further. mSpeechLevelsAnimator = new TimeAnimator(); mSpeechLevelsAnimator.setRepeatCount(ObjectAnimator.INFINITE); - mSpeechLevelsAnimator.setTimeListener(new TimeListener() { - @Override - public void onTimeUpdate(final TimeAnimator animation, final long totalTime, - final long deltaTime) { - invalidate(); - } - }); + mSpeechLevelsAnimator.setTimeListener((animation, totalTime, deltaTime) -> invalidate()); } @Override diff --git a/src/com/android/messaging/util/Assert.java b/src/com/android/messaging/util/Assert.java index d284b0f..69edf92 100644 --- a/src/com/android/messaging/util/Assert.java +++ b/src/com/android/messaging/util/Assert.java @@ -57,12 +57,7 @@ public final class Assert { // This is called from FactoryImpl once the Gservices class is initialized. public static void initializeGservices (final BugleGservices gservices) { - gservices.registerForChanges(new Runnable() { - @Override - public void run() { - refreshGservices(gservices); - } - }); + gservices.registerForChanges(() -> refreshGservices(gservices)); refreshGservices(gservices); } diff --git a/src/com/android/messaging/util/BugleActivityUtil.java b/src/com/android/messaging/util/BugleActivityUtil.java index d83e895..d475879 100644 --- a/src/com/android/messaging/util/BugleActivityUtil.java +++ b/src/com/android/messaging/util/BugleActivityUtil.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +21,6 @@ import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; -import android.content.DialogInterface; import android.os.UserManager; import android.text.TextUtils; @@ -68,13 +68,7 @@ public class BugleActivityUtil { .setMessage(R.string.requires_sms_permissions_message) .setCancelable(false) .setNegativeButton(R.string.requires_sms_permissions_close_button, - new DialogInterface.OnClickListener() { - @Override - public void onClick(final DialogInterface dialog, - final int button) { - System.exit(0); - } - }) + (dialog, button) -> System.exit(0)) .show(); return false; } diff --git a/src/com/android/messaging/util/DebugUtils.java b/src/com/android/messaging/util/DebugUtils.java index 99bacee..e25e62f 100644 --- a/src/com/android/messaging/util/DebugUtils.java +++ b/src/com/android/messaging/util/DebugUtils.java @@ -22,7 +22,6 @@ import android.app.AlertDialog; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.Context; -import android.content.DialogInterface; import android.content.Intent; import android.media.MediaPlayer; import android.net.Uri; @@ -50,7 +49,6 @@ import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; -import java.io.FilenameFilter; import java.io.IOException; import java.io.StreamCorruptedException; @@ -193,13 +191,7 @@ public class DebugUtils { } }); - builder.setAdapter(arrayAdapter, - new android.content.DialogInterface.OnClickListener() { - @Override - public void onClick(final DialogInterface arg0, final int pos) { - arrayAdapter.getItem(pos).run(); - } - }); + builder.setAdapter(arrayAdapter, (arg0, pos) -> arrayAdapter.getItem(pos).run()); builder.create().show(); } @@ -231,16 +223,11 @@ public class DebugUtils { @Override protected String[] doInBackgroundTimed(final Void... params) { final File dir = DebugUtils.getDebugFilesDir(); - return dir.list(new FilenameFilter() { - @Override - public boolean accept(final File dir, final String filename) { - return filename != null - && ((mAction == DebugSmsMmsFromDumpFileDialogFragment.ACTION_EMAIL - && filename.equals(DumpDatabaseAction.DUMP_NAME)) - || filename.startsWith(MmsUtils.MMS_DUMP_PREFIX) - || filename.startsWith(MmsUtils.SMS_DUMP_PREFIX)); - } - }); + return dir.list((dir1, filename) -> filename != null + && ((mAction == DebugSmsMmsFromDumpFileDialogFragment.ACTION_EMAIL + && filename.equals(DumpDatabaseAction.DUMP_NAME)) + || filename.startsWith(MmsUtils.MMS_DUMP_PREFIX) + || filename.startsWith(MmsUtils.SMS_DUMP_PREFIX))); } } diff --git a/src/com/android/messaging/util/LogUtil.java b/src/com/android/messaging/util/LogUtil.java index 021f39b..4204327 100644 --- a/src/com/android/messaging/util/LogUtil.java +++ b/src/com/android/messaging/util/LogUtil.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,12 +59,7 @@ public class LogUtil { // This is called from FactoryImpl once the Gservices class is initialized. public static void initializeGservices (final BugleGservices gservices) { - gservices.registerForChanges(new Runnable() { - @Override - public void run() { - refreshGservices(gservices); - } - }); + gservices.registerForChanges(() -> refreshGservices(gservices)); refreshGservices(gservices); } diff --git a/src/com/android/messaging/util/MediaUtilImpl.java b/src/com/android/messaging/util/MediaUtilImpl.java index 272a057..ae7d3ee 100644 --- a/src/com/android/messaging/util/MediaUtilImpl.java +++ b/src/com/android/messaging/util/MediaUtilImpl.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,15 +43,12 @@ public class MediaUtilImpl extends MediaUtil { afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); afd.close(); mediaPlayer.prepare(); - mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { - @Override - public void onCompletion(final MediaPlayer mp) { - if (completionListener != null) { - completionListener.onCompletion(); - } - mp.stop(); - mp.release(); + mediaPlayer.setOnCompletionListener(mp -> { + if (completionListener != null) { + completionListener.onCompletion(); } + mp.stop(); + mp.release(); }); mediaPlayer.seekTo(0); mediaPlayer.start(); @@ -63,4 +61,4 @@ public class MediaUtilImpl extends MediaUtil { completionListener.onCompletion(); } } -} \ No newline at end of file +} diff --git a/src/com/android/messaging/util/SafeAsyncTask.java b/src/com/android/messaging/util/SafeAsyncTask.java index 2344515..e2495ba 100644 --- a/src/com/android/messaging/util/SafeAsyncTask.java +++ b/src/com/android/messaging/util/SafeAsyncTask.java @@ -96,15 +96,12 @@ public abstract class SafeAsyncTask Assert.isTrue(mThreadPoolRequested); if (mCancelExecutionOnTimeout) { - ThreadUtil.getMainThreadHandler().postDelayed(new Runnable() { - @Override - public void run() { - if (getStatus() == Status.RUNNING) { - // Cancel the task if it's still running. - LogUtil.w(LogUtil.BUGLE_TAG, String.format("%s timed out and is canceled", - this)); - cancel(true /* mayInterruptIfRunning */); - } + ThreadUtil.getMainThreadHandler().postDelayed(() -> { + if (getStatus() == Status.RUNNING) { + // Cancel the task if it's still running. + LogUtil.w(LogUtil.BUGLE_TAG, String.format("%s timed out and is canceled", + this)); + cancel(true /* mayInterruptIfRunning */); } }, mMaxExecutionTimeMillis); } @@ -160,14 +157,11 @@ public abstract class SafeAsyncTask if (withWakeLock) { final Intent intent = new Intent(); sWakeLock.acquire(Factory.get().getApplicationContext(), intent, WAKELOCK_OP); - THREAD_POOL_EXECUTOR.execute(new Runnable() { - @Override - public void run() { - try { - runnable.run(); - } finally { - sWakeLock.release(intent, WAKELOCK_OP); - } + THREAD_POOL_EXECUTOR.execute(() -> { + try { + runnable.run(); + } finally { + sWakeLock.release(intent, WAKELOCK_OP); } }); } else { diff --git a/src/com/android/messaging/widget/BugleWidgetProvider.java b/src/com/android/messaging/widget/BugleWidgetProvider.java index 50c97b6..fd565ad 100644 --- a/src/com/android/messaging/widget/BugleWidgetProvider.java +++ b/src/com/android/messaging/widget/BugleWidgetProvider.java @@ -1,5 +1,6 @@ /* - * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,12 +43,7 @@ public class BugleWidgetProvider extends BaseWidgetProvider { @Override protected void updateWidget(final Context context, final int appWidgetId) { if (OsUtil.hasRequiredPermissions()) { - SafeAsyncTask.executeOnThreadPool(new Runnable() { - @Override - public void run() { - rebuildWidget(context, appWidgetId); - } - }); + SafeAsyncTask.executeOnThreadPool(() -> rebuildWidget(context, appWidgetId)); } else { AppWidgetManager.getInstance(context).updateAppWidget(appWidgetId, UiUtils.getWidgetMissingPermissionView(context)); diff --git a/src/com/android/messaging/widget/WidgetConversationProvider.java b/src/com/android/messaging/widget/WidgetConversationProvider.java index 6ae5614..d3e6128 100644 --- a/src/com/android/messaging/widget/WidgetConversationProvider.java +++ b/src/com/android/messaging/widget/WidgetConversationProvider.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -148,12 +149,7 @@ public class WidgetConversationProvider extends BaseWidgetProvider { // widget dependent on ConversationListItemData. However, we have to update // the widget regardless, even with those missing pieces. Here we update the // widget again in the background. - SafeAsyncTask.executeOnThreadPool(new Runnable() { - @Override - public void run() { - rebuildWidget(context, appWidgetId); - } - }); + SafeAsyncTask.executeOnThreadPool(() -> rebuildWidget(context, appWidgetId)); } }