001// SPDX-License-Identifier: GPL-3.0-or-later
002// Copyright © 2026 Aurélien Pierre
003
004package com.aurelienpierre.sioul;
005
006import android.Manifest;
007import android.app.Activity;
008import android.os.Bundle;
009import android.os.SystemClock;
010import android.util.Log;
011
012/**
013 * Android's question for the texts' permissions (docs/texts.md), asked from
014 * Settings ▸ This phone ▸ Texts: reading the texts (READ_SMS), hearing a new
015 * one (RECEIVE_SMS), sending one written on a computer (SEND_SMS), then,
016 * apart, the SIMs' names (READ_PHONE_STATE), which Android never keeps
017 * behind restricted settings: the first question's answer, timed, says
018 * whether Android showed one (`Texts.atOnce`). Android answers only an
019 * activity, so this one, never seen, asks and goes. Sioul never asks to be
020 * the SMS app.
021 */
022public final class TextsAsk extends Activity
023{
024    private static final int ASK = 0x5140;
025    /** The SIMs' names, asked after the texts' three. */
026    private static final int ASK_SIMS = 0x5141;
027    /** When the question was asked (elapsed time, ms): its answer at once means none was shown (`Texts.atOnce`). */
028    private long asked = -1;
029
030    @Override
031    protected void onCreate(Bundle saved)
032    {
033        super.onCreate(saved);
034        if (saved != null)
035            return;
036        asked = SystemClock.elapsedRealtime();
037        requestPermissions(new String[] { Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_SMS, Manifest.permission.SEND_SMS }, ASK);
038    }
039
040    @Override
041    public void onRequestPermissionsResult(int request, String[] permissions, int[] results)
042    {
043        super.onRequestPermissionsResult(request, permissions, results);
044        if (request == ASK) {
045            int given = 0;
046            for (int result : results)
047                if (result == android.content.pm.PackageManager.PERMISSION_GRANTED)
048                    given++;
049            long took = asked < 0 ? -1 : SystemClock.elapsedRealtime() - asked;
050            Log.i(Texts.TAG, "Texts: " + given + " of " + results.length + " permissions given" + (Texts.atOnce(given, took) ? ", at once: no question was shown." : "."));
051            Texts.remember(this, given, results.length, took);
052            if (checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != android.content.pm.PackageManager.PERMISSION_GRANTED) {
053                requestPermissions(new String[] { Manifest.permission.READ_PHONE_STATE }, ASK_SIMS);
054                return;
055            }
056        }
057        finish();
058    }
059}