-
Notifications
You must be signed in to change notification settings - Fork 299
/
Copy pathSplashImageTransferTask.java
184 lines (162 loc) · 6.96 KB
/
SplashImageTransferTask.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
// Copyright 2019 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.androidbrowserhelper.trusted.splashscreens;
import android.annotation.SuppressLint;
import android.app.UiModeManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import androidx.annotation.Nullable;
import androidx.browser.customtabs.CustomTabsSession;
import androidx.browser.customtabs.TrustedWebUtils;
import androidx.core.content.FileProvider;
/**
* Saves the splash image to a file and transfers it to Custom Tabs provider.
*/
public class SplashImageTransferTask {
private static final String TAG = "SplashImageTransferTask";
private static final String FOLDER_NAME = "twa_splash";
private static final String FILE_NAME = "splash_image.png";
private static final String PREFS_FILE = "splashImagePrefs";
private static final String PREF_LAST_UPDATE_TIME = "lastUpdateTime";
private static final String PREF_THEME_MODE = "themeMode";
private static final String DEFAULT_THEME_MODE = "light"; // Default to light for compatibility
private final Context mContext;
private final Bitmap mBitmap;
private final String mAuthority;
private final CustomTabsSession mSession;
private final String mProviderPackage;
@Nullable
private Callback mCallback;
/**
* @param context {@link Context} to use.
* @param bitmap image to transfer.
* @param authority {@link FileProvider} authority.
* @param session {@link CustomTabsSession} to use for transferring the file.
* @param providerPackage Package name of the Custom Tabs provider.
*/
public SplashImageTransferTask(Context context, Bitmap bitmap, String authority,
CustomTabsSession session, String providerPackage) {
mContext = context.getApplicationContext();
mBitmap = bitmap;
mAuthority = authority;
mSession = session;
mProviderPackage = providerPackage;
}
/**
* Get the current theme mode.
*
* @param context Context to get the UiModeManager service.
* @return The current theme mode, either "light" or "dark".
*/
private String getCurrentThemeMode(Context context) {
UiModeManager uiModeManager = (UiModeManager) context.getSystemService(Context.UI_MODE_SERVICE);
int nightModeFlags = context.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
switch (nightModeFlags) {
case Configuration.UI_MODE_NIGHT_YES:
return "dark";
case Configuration.UI_MODE_NIGHT_NO:
case Configuration.UI_MODE_NIGHT_UNDEFINED:
default:
return "light";
}
}
/**
* Executes the task. Should be called only once.
* @param callback {@link Callback} to be called when done.
*/
public void execute(Callback callback) {
assert mAsyncTask.getStatus() == AsyncTask.Status.PENDING;
mCallback = callback;
mAsyncTask.execute();
}
/**
* Cancels the execution. The callback passed into {@link #execute} won't be called, and
* the references to it will be released.
*/
public void cancel() {
mAsyncTask.cancel(true);
mCallback = null;
}
@SuppressLint("StaticFieldLeak") // No leaking should happen
private final AsyncTask<Void, Void, Boolean> mAsyncTask = new AsyncTask<Void, Void, Boolean>() {
@Override
protected Boolean doInBackground(Void... args) {
if (isCancelled()) return false;
File dir = new File(mContext.getFilesDir(), FOLDER_NAME);
if (!dir.exists()) {
boolean mkDirSuccessful = dir.mkdir();
if (!mkDirSuccessful) {
Log.w(TAG, "Failed to create a directory for storing a splash image");
return false;
}
}
File file = new File(dir, FILE_NAME);
SharedPreferences prefs =
mContext.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE);
long lastUpdateTime = getLastAppUpdateTime();
String currentThemeMode = getCurrentThemeMode(mContext);
long savedLastUpdateTime = prefs.getLong(PREF_LAST_UPDATE_TIME, 0);
String savedThemeMode = prefs.getString(PREF_THEME_MODE, DEFAULT_THEME_MODE);
if (file.exists() && lastUpdateTime == savedLastUpdateTime && currentThemeMode.equals(savedThemeMode)) {
// Don't overwrite existing file, if it was saved later than the last time app was
// updated
return transferToCustomTabsProvider(file);
}
try(OutputStream os = new FileOutputStream(file)) {
if (isCancelled()) return false;
mBitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
os.flush();
prefs.edit()
.putLong(PREF_LAST_UPDATE_TIME, lastUpdateTime)
.putString(PREF_THEME_MODE, currentThemeMode)
.apply();
if (isCancelled()) return false;
return transferToCustomTabsProvider(file);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private boolean transferToCustomTabsProvider(File file) {
return TrustedWebUtils.transferSplashImage(mContext, file, mAuthority, mProviderPackage,
mSession);
}
private long getLastAppUpdateTime() {
try {
return mContext.getPackageManager()
.getPackageInfo(mContext.getPackageName(), 0).lastUpdateTime;
} catch (PackageManager.NameNotFoundException e) {
// Should not happen
throw new RuntimeException(e);
}
}
@Override
protected void onPostExecute(Boolean success) {
if (mCallback != null && !isCancelled()) {
mCallback.onFinished(success);
}
}
};
/** Callback to be called when the file is saved and transferred to Custom Tabs provider. */
public interface Callback {
void onFinished(boolean successfully);
}
}