001// SPDX-License-Identifier: GPL-3.0-or-later
002// Copyright © 2026 Aurélien Pierre
003
004package com.aurelienpierre.sioul;
005
006import android.app.Activity;
007import android.app.role.RoleManager;
008import android.content.ActivityNotFoundException;
009import android.content.Intent;
010import android.os.Build;
011import android.os.Bundle;
012import android.util.Log;
013
014/**
015 * Android's question "Set Sioul as your default caller ID & spam app?"
016 * (docs/android.md, "Calls"), asked from Settings ▸ Calls: Android answers
017 * only an activity that asks for a result, so this one, never seen, asks
018 * and goes. Its answer is read again by Sioul when its window comes back.
019 */
020public final class CallsSetup extends Activity
021{
022    private static final int ASK = 0x5139;
023
024    @Override
025    protected void onCreate(Bundle saved)
026    {
027        super.onCreate(saved);
028        if (saved != null)
029            return;
030        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
031            RoleManager roles = getSystemService(RoleManager.class);
032            if (roles != null && roles.isRoleAvailable(RoleManager.ROLE_CALL_SCREENING) && !roles.isRoleHeld(RoleManager.ROLE_CALL_SCREENING)) {
033                try {
034                    startActivityForResult(roles.createRequestRoleIntent(RoleManager.ROLE_CALL_SCREENING), ASK);
035                    return;
036                } catch (ActivityNotFoundException | SecurityException e) {
037                    Log.w(Calls.TAG, "Calls: Android's question could not be asked: " + e);
038                }
039            }
040        }
041        finish();
042    }
043
044    @Override
045    protected void onActivityResult(int request, int result, Intent data)
046    {
047        super.onActivityResult(request, result, data);
048        if (request == ASK)
049            Log.i(Calls.TAG, "Calls: the screening role " + (result == RESULT_OK ? "given." : "not given."));
050        finish();
051    }
052}