termux-app

Форк
0
137 строк · 6.3 Кб
1
package com.termux.shared.activity;
2

3
import android.app.Activity;
4
import android.content.Context;
5
import android.content.Intent;
6

7
import androidx.activity.result.ActivityResultLauncher;
8
import androidx.annotation.NonNull;
9
import androidx.annotation.Nullable;
10
import androidx.appcompat.app.AppCompatActivity;
11

12
import com.termux.shared.errors.Error;
13
import com.termux.shared.errors.FunctionErrno;
14

15

16
public class ActivityUtils {
17

18
    private static final String LOG_TAG = "ActivityUtils";
19

20
    /**
21
     * Wrapper for {@link #startActivity(Context, Intent, boolean, boolean)}.
22
     */
23
    public static Error startActivity(@NonNull Context context, @NonNull Intent intent) {
24
        return startActivity(context, intent, true, true);
25
    }
26

27
    /**
28
     * Start an {@link Activity}.
29
     *
30
     * @param context The context for operations.
31
     * @param intent The {@link Intent} to send to start the activity.
32
     * @param logErrorMessage If an error message should be logged if failed to start activity.
33
     * @param showErrorMessage If an error message toast should be shown if failed to start activity
34
     *                         in addition to logging a message. The {@code context} must not be
35
     *                         {@code null}.
36
     * @return Returns the {@code error} if starting activity was not successful, otherwise {@code null}.
37
     */
38
    public static Error startActivity(Context context, @NonNull Intent intent,
39
                                      boolean logErrorMessage, boolean showErrorMessage) {
40
        Error error;
41
        String activityName = intent.getComponent() != null ? intent.getComponent().getClassName() : "Unknown";
42

43
        if (context == null) {
44
            error = ActivityErrno.ERRNO_STARTING_ACTIVITY_WITH_NULL_CONTEXT.getError(activityName);
45
            if (logErrorMessage)
46
                error.logErrorAndShowToast(null, LOG_TAG);
47
            return error;
48
        }
49

50
        try {
51
            context.startActivity(intent);
52
        } catch (Exception e) {
53
            error = ActivityErrno.ERRNO_START_ACTIVITY_FAILED_WITH_EXCEPTION.getError(e, activityName, e.getMessage());
54
            if (logErrorMessage)
55
                error.logErrorAndShowToast(showErrorMessage ? context : null, LOG_TAG);
56
            return error;
57
        }
58

59
        return null;
60
    }
61

62

63

64
    /**
65
     * Wrapper for {@link #startActivityForResult(Context, int, Intent, boolean, boolean, ActivityResultLauncher)}.
66
     */
67
    public static Error startActivityForResult(Context context, int requestCode, @NonNull Intent intent) {
68
        return startActivityForResult(context, requestCode, intent, true, true, null);
69
    }
70

71
    /**
72
     * Wrapper for {@link #startActivityForResult(Context, int, Intent, boolean, boolean, ActivityResultLauncher)}.
73
     */
74
    public static Error startActivityForResult(Context context, int requestCode, @NonNull Intent intent,
75
                                               boolean logErrorMessage, boolean showErrorMessage) {
76
        return startActivityForResult(context, requestCode, intent, logErrorMessage, showErrorMessage, null);
77
    }
78

79
    /**
80
     * Start an {@link Activity} for result.
81
     *
82
     * @param context The context for operations. It must be an instance of {@link Activity} or
83
     *               {@link AppCompatActivity}. It is ignored if {@code activityResultLauncher}
84
     *                is not {@code null}.
85
     * @param requestCode The request code to use while sending intent. This must be >= 0, otherwise
86
     *                    exception will be raised. This is ignored if {@code activityResultLauncher}
87
     *                    is {@code null}.
88
     * @param intent The {@link Intent} to send to start the activity.
89
     * @param logErrorMessage If an error message should be logged if failed to start activity.
90
     * @param showErrorMessage If an error message toast should be shown if failed to start activity
91
     *                         in addition to logging a message. The {@code context} must not be
92
     *                         {@code null}.
93
     * @param activityResultLauncher The {@link ActivityResultLauncher<Intent>} to use for start the
94
     *                               activity. If this is {@code null}, then
95
     *                               {@link Activity#startActivityForResult(Intent, int)} will be
96
     *                               used instead.
97
     *                               Note that later is deprecated.
98
     * @return Returns the {@code error} if starting activity was not successful, otherwise {@code null}.
99
     */
100
    public static Error startActivityForResult(Context context, int requestCode, @NonNull Intent intent,
101
                                               boolean logErrorMessage, boolean showErrorMessage,
102
                                               @Nullable ActivityResultLauncher<Intent> activityResultLauncher) {
103
        Error error;
104
        String activityName = intent.getComponent() != null ? intent.getComponent().getClassName() : "Unknown";
105
        try {
106
            if (activityResultLauncher != null) {
107
                activityResultLauncher.launch(intent);
108
            } else {
109
                if (context == null) {
110
                    error = ActivityErrno.ERRNO_STARTING_ACTIVITY_WITH_NULL_CONTEXT.getError(activityName);
111
                    if (logErrorMessage)
112
                        error.logErrorAndShowToast(null, LOG_TAG);
113
                    return error;
114
                }
115

116
                if (context instanceof AppCompatActivity)
117
                    ((AppCompatActivity) context).startActivityForResult(intent, requestCode);
118
                else if (context instanceof Activity)
119
                    ((Activity) context).startActivityForResult(intent, requestCode);
120
                else {
121
                    error = FunctionErrno.ERRNO_PARAMETER_NOT_INSTANCE_OF.getError("context", "startActivityForResult", "Activity or AppCompatActivity");
122
                    if (logErrorMessage)
123
                        error.logErrorAndShowToast(showErrorMessage ? context : null, LOG_TAG);
124
                    return error;
125
                }
126
            }
127
        } catch (Exception e) {
128
            error = ActivityErrno.ERRNO_START_ACTIVITY_FOR_RESULT_FAILED_WITH_EXCEPTION.getError(e, activityName, e.getMessage());
129
            if (logErrorMessage)
130
                error.logErrorAndShowToast(showErrorMessage ? context : null, LOG_TAG);
131
            return error;
132
        }
133

134
        return null;
135
    }
136

137
}
138

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.