Search in sources :

Example 1 with OnSubscriptionsChangedListener

use of android.telephony.SubscriptionManager.OnSubscriptionsChangedListener in project kdeconnect-android by KDE.

the class TelephonyHelper method listenActiveSubscriptionIDs.

/**
 * Registers a listener for changes in subscriptionIDs for the device.
 * This lets you identify additions/removals of SIM cards.
 * Make sure to call `cancelActiveSubscriptionIDsListener` with the return value of this once you're done.
 */
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
public static OnSubscriptionsChangedListener listenActiveSubscriptionIDs(@NonNull Context context, SubscriptionCallback onAdd, SubscriptionCallback onRemove) {
    SubscriptionManager sm = ContextCompat.getSystemService(context, SubscriptionManager.class);
    if (sm == null) {
        // I don't know why or when this happens...
        Log.w(LOGGING_TAG, "Could not get SubscriptionManager");
        return null;
    }
    HashSet<Integer> activeIDs = new HashSet<>();
    OnSubscriptionsChangedListener listener = new OnSubscriptionsChangedListener() {

        @Override
        public void onSubscriptionsChanged() {
            HashSet<Integer> nextSubs = new HashSet<>(getActiveSubscriptionIDs(context));
            HashSet<Integer> addedSubs = new HashSet<>(nextSubs);
            addedSubs.removeAll(activeIDs);
            HashSet<Integer> removedSubs = new HashSet<>(activeIDs);
            removedSubs.removeAll(nextSubs);
            activeIDs.removeAll(removedSubs);
            activeIDs.addAll(addedSubs);
            // Delete old listeners
            for (Integer subID : removedSubs) {
                onRemove.run(subID);
            }
            // Create new listeners
            for (Integer subID : addedSubs) {
                onAdd.run(subID);
            }
        }
    };
    sm.addOnSubscriptionsChangedListener(listener);
    return listener;
}
Also used : OnSubscriptionsChangedListener(android.telephony.SubscriptionManager.OnSubscriptionsChangedListener) SubscriptionManager(android.telephony.SubscriptionManager) HashSet(java.util.HashSet) RequiresApi(androidx.annotation.RequiresApi)

Aggregations

SubscriptionManager (android.telephony.SubscriptionManager)1 OnSubscriptionsChangedListener (android.telephony.SubscriptionManager.OnSubscriptionsChangedListener)1 RequiresApi (androidx.annotation.RequiresApi)1 HashSet (java.util.HashSet)1