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 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
|
/*
* Copyright 2020 The Android Open Source Project
*
* 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 android.service.quickaccesswallet;
import static android.service.quickaccesswallet.QuickAccessWalletService.ACTION_VIEW_WALLET;
import static android.service.quickaccesswallet.QuickAccessWalletService.ACTION_VIEW_WALLET_SETTINGS;
import static android.service.quickaccesswallet.QuickAccessWalletService.SERVICE_INTERFACE;
import android.annotation.CallbackExecutor;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.app.ActivityManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.RemoteException;
import android.os.UserHandle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import com.android.internal.widget.LockPatternUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.UUID;
import java.util.concurrent.Executor;
/**
* Implements {@link QuickAccessWalletClient}. The client connects, performs requests, waits for
* responses, and disconnects automatically one minute after the last call is performed.
*
* @hide
*/
public class QuickAccessWalletClientImpl implements QuickAccessWalletClient, ServiceConnection {
private static final String TAG = "QAWalletSClient";
public static final String SETTING_KEY = "lockscreen_show_wallet";
private final Handler mHandler;
private final Context mContext;
private final Queue<ApiCaller> mRequestQueue;
private final Map<WalletServiceEventListener, String> mEventListeners;
private final Executor mLifecycleExecutor;
private boolean mIsConnected;
/** Timeout for active service connections (1 minute) */
private static final long SERVICE_CONNECTION_TIMEOUT_MS = 60 * 1000;
@Nullable
private IQuickAccessWalletService mService;
@Nullable
private final QuickAccessWalletServiceInfo mServiceInfo;
private static final int MSG_TIMEOUT_SERVICE = 5;
QuickAccessWalletClientImpl(@NonNull Context context, @Nullable Executor bgExecutor) {
mContext = context.getApplicationContext();
mServiceInfo = QuickAccessWalletServiceInfo.tryCreate(context);
mHandler = new Handler(Looper.getMainLooper());
mLifecycleExecutor = (bgExecutor == null) ? Runnable::run : bgExecutor;
mRequestQueue = new LinkedList<>();
mEventListeners = new HashMap<>(1);
}
@Override
public boolean isWalletServiceAvailable() {
return mServiceInfo != null;
}
@Override
public boolean isWalletFeatureAvailable() {
int currentUser = ActivityManager.getCurrentUser();
return currentUser == UserHandle.USER_SYSTEM
&& checkUserSetupComplete()
&& !new LockPatternUtils(mContext).isUserInLockdown(currentUser);
}
@Override
public boolean isWalletFeatureAvailableWhenDeviceLocked() {
return checkSecureSetting(SETTING_KEY);
}
@Override
public void getWalletCards(
@NonNull GetWalletCardsRequest request,
@NonNull OnWalletCardsRetrievedCallback callback) {
getWalletCards(mContext.getMainExecutor(), request, callback);
}
@Override
public void getWalletCards(
@NonNull @CallbackExecutor Executor executor,
@NonNull GetWalletCardsRequest request,
@NonNull OnWalletCardsRetrievedCallback callback) {
if (!isWalletServiceAvailable()) {
executor.execute(
() -> callback.onWalletCardRetrievalError(new GetWalletCardsError(null, null)));
return;
}
BaseCallbacks serviceCallback = new BaseCallbacks() {
@Override
public void onGetWalletCardsSuccess(GetWalletCardsResponse response) {
executor.execute(() -> callback.onWalletCardsRetrieved(response));
}
@Override
public void onGetWalletCardsFailure(GetWalletCardsError error) {
executor.execute(() -> callback.onWalletCardRetrievalError(error));
}
};
executeApiCall(new ApiCaller("onWalletCardsRequested") {
@Override
public void performApiCall(IQuickAccessWalletService service) throws RemoteException {
service.onWalletCardsRequested(request, serviceCallback);
}
@Override
public void onApiError() {
serviceCallback.onGetWalletCardsFailure(new GetWalletCardsError(null, null));
}
});
}
@Override
public void selectWalletCard(@NonNull SelectWalletCardRequest request) {
if (!isWalletServiceAvailable()) {
return;
}
executeApiCall(new ApiCaller("onWalletCardSelected") {
@Override
public void performApiCall(IQuickAccessWalletService service) throws RemoteException {
service.onWalletCardSelected(request);
}
});
}
@Override
public void notifyWalletDismissed() {
if (!isWalletServiceAvailable()) {
return;
}
executeApiCall(new ApiCaller("onWalletDismissed") {
@Override
public void performApiCall(IQuickAccessWalletService service) throws RemoteException {
service.onWalletDismissed();
}
});
}
@Override
public void addWalletServiceEventListener(WalletServiceEventListener listener) {
addWalletServiceEventListener(mContext.getMainExecutor(), listener);
}
@Override
public void addWalletServiceEventListener(
@NonNull @CallbackExecutor Executor executor,
@NonNull WalletServiceEventListener listener) {
if (!isWalletServiceAvailable()) {
return;
}
BaseCallbacks callback = new BaseCallbacks() {
@Override
public void onWalletServiceEvent(WalletServiceEvent event) {
executor.execute(() -> listener.onWalletServiceEvent(event));
}
};
executeApiCall(new ApiCaller("registerListener") {
@Override
public void performApiCall(IQuickAccessWalletService service) throws RemoteException {
String listenerId = UUID.randomUUID().toString();
WalletServiceEventListenerRequest request =
new WalletServiceEventListenerRequest(listenerId);
mEventListeners.put(listener, listenerId);
service.registerWalletServiceEventListener(request, callback);
}
});
}
@Override
public void removeWalletServiceEventListener(WalletServiceEventListener listener) {
if (!isWalletServiceAvailable()) {
return;
}
executeApiCall(new ApiCaller("unregisterListener") {
@Override
public void performApiCall(IQuickAccessWalletService service) throws RemoteException {
String listenerId = mEventListeners.remove(listener);
if (listenerId == null) {
return;
}
WalletServiceEventListenerRequest request =
new WalletServiceEventListenerRequest(listenerId);
service.unregisterWalletServiceEventListener(request);
}
});
}
@Override
public void close() throws IOException {
disconnect();
}
@Override
public void disconnect() {
mHandler.post(() -> disconnectInternal(true));
}
@Override
@Nullable
public Intent createWalletIntent() {
if (mServiceInfo == null) {
return null;
}
String packageName = mServiceInfo.getComponentName().getPackageName();
String walletActivity = mServiceInfo.getWalletActivity();
return createIntent(walletActivity, packageName, ACTION_VIEW_WALLET);
}
@Override
public void getWalletPendingIntent(
@NonNull @CallbackExecutor Executor executor,
@NonNull WalletPendingIntentCallback pendingIntentCallback) {
BaseCallbacks callbacks = new BaseCallbacks() {
@Override
public void onTargetActivityPendingIntentReceived(PendingIntent pendingIntent) {
executor.execute(
() -> pendingIntentCallback.onWalletPendingIntentRetrieved(pendingIntent));
}
};
executeApiCall(new ApiCaller("getTargetActivityPendingIntent") {
@Override
void performApiCall(IQuickAccessWalletService service) throws RemoteException {
service.onTargetActivityIntentRequested(callbacks);
}
});
}
@Override
@Nullable
public Intent createWalletSettingsIntent() {
if (mServiceInfo == null) {
return null;
}
String packageName = mServiceInfo.getComponentName().getPackageName();
String settingsActivity = mServiceInfo.getSettingsActivity();
return createIntent(settingsActivity, packageName, ACTION_VIEW_WALLET_SETTINGS);
}
@Nullable
private Intent createIntent(@Nullable String activityName, String packageName, String action) {
PackageManager pm = mContext.getPackageManager();
if (TextUtils.isEmpty(activityName)) {
activityName = queryActivityForAction(pm, packageName, action);
}
if (TextUtils.isEmpty(activityName)) {
return null;
}
ComponentName component = new ComponentName(packageName, activityName);
if (!isActivityEnabled(pm, component)) {
return null;
}
return new Intent(action).setComponent(component);
}
@Nullable
private static String queryActivityForAction(PackageManager pm, String packageName,
String action) {
Intent intent = new Intent(action).setPackage(packageName);
ResolveInfo resolveInfo = pm.resolveActivity(intent, 0);
if (resolveInfo == null
|| resolveInfo.activityInfo == null
|| !resolveInfo.activityInfo.exported) {
return null;
}
return resolveInfo.activityInfo.name;
}
private static boolean isActivityEnabled(PackageManager pm, ComponentName component) {
int setting = pm.getComponentEnabledSetting(component);
if (setting == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
return true;
}
if (setting != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) {
return false;
}
try {
return pm.getActivityInfo(component, 0).isEnabled();
} catch (NameNotFoundException e) {
return false;
}
}
@Override
@Nullable
public Drawable getLogo() {
return mServiceInfo == null ? null : mServiceInfo.getWalletLogo(mContext);
}
@Nullable
@Override
public Drawable getTileIcon() {
return mServiceInfo == null ? null : mServiceInfo.getTileIcon();
}
@Override
@Nullable
public CharSequence getServiceLabel() {
return mServiceInfo == null ? null : mServiceInfo.getServiceLabel(mContext);
}
@Override
@Nullable
public CharSequence getShortcutShortLabel() {
return mServiceInfo == null ? null : mServiceInfo.getShortcutShortLabel(mContext);
}
@Override
public CharSequence getShortcutLongLabel() {
return mServiceInfo == null ? null : mServiceInfo.getShortcutLongLabel(mContext);
}
private void connect() {
mHandler.post(this::connectInternal);
}
private void connectInternal() {
if (mServiceInfo == null) {
Log.w(TAG, "Wallet service unavailable");
return;
}
if (mIsConnected) {
return;
}
mIsConnected = true;
Intent intent = new Intent(SERVICE_INTERFACE);
intent.setComponent(mServiceInfo.getComponentName());
int flags = Context.BIND_AUTO_CREATE | Context.BIND_WAIVE_PRIORITY;
mLifecycleExecutor.execute(() -> mContext.bindService(intent, this, flags));
resetServiceConnectionTimeout();
}
private void onConnectedInternal(IQuickAccessWalletService service) {
if (!mIsConnected) {
Log.w(TAG, "onConnectInternal but connection closed");
mService = null;
return;
}
mService = service;
for (ApiCaller apiCaller : new ArrayList<>(mRequestQueue)) {
performApiCallInternal(apiCaller, mService);
mRequestQueue.remove(apiCaller);
}
}
/**
* Resets the idle timeout for this connection by removing any pending timeout messages and
* posting a new delayed message.
*/
private void resetServiceConnectionTimeout() {
mHandler.removeMessages(MSG_TIMEOUT_SERVICE);
mHandler.postDelayed(
() -> disconnectInternal(true),
MSG_TIMEOUT_SERVICE,
SERVICE_CONNECTION_TIMEOUT_MS);
}
private void disconnectInternal(boolean clearEventListeners) {
if (!mIsConnected) {
Log.w(TAG, "already disconnected");
return;
}
if (clearEventListeners && !mEventListeners.isEmpty()) {
for (WalletServiceEventListener listener : mEventListeners.keySet()) {
removeWalletServiceEventListener(listener);
}
mHandler.post(() -> disconnectInternal(false));
return;
}
mIsConnected = false;
mLifecycleExecutor.execute(() -> mContext.unbindService(/*conn=*/ this));
mService = null;
mEventListeners.clear();
mRequestQueue.clear();
}
private void executeApiCall(ApiCaller apiCaller) {
mHandler.post(() -> executeInternal(apiCaller));
}
private void executeInternal(ApiCaller apiCaller) {
if (mIsConnected && mService != null) {
performApiCallInternal(apiCaller, mService);
} else {
mRequestQueue.add(apiCaller);
connect();
}
}
private void performApiCallInternal(ApiCaller apiCaller, IQuickAccessWalletService service) {
if (service == null) {
apiCaller.onApiError();
return;
}
try {
apiCaller.performApiCall(service);
resetServiceConnectionTimeout();
} catch (RemoteException e) {
Log.w(TAG, "executeInternal error: " + apiCaller.mDesc, e);
apiCaller.onApiError();
disconnect();
}
}
private abstract static class ApiCaller {
private final String mDesc;
private ApiCaller(String desc) {
this.mDesc = desc;
}
abstract void performApiCall(IQuickAccessWalletService service)
throws RemoteException;
void onApiError() {
Log.w(TAG, "api error: " + mDesc);
}
}
@Override // ServiceConnection
public void onServiceConnected(ComponentName name, IBinder binder) {
IQuickAccessWalletService service = IQuickAccessWalletService.Stub.asInterface(binder);
mHandler.post(() -> onConnectedInternal(service));
}
@Override // ServiceConnection
public void onServiceDisconnected(ComponentName name) {
// Do not disconnect, as we may later be re-connected
}
@Override // ServiceConnection
public void onBindingDied(ComponentName name) {
// This is a recoverable error but the client will need to reconnect.
disconnect();
}
@Override // ServiceConnection
public void onNullBinding(ComponentName name) {
disconnect();
}
private boolean checkSecureSetting(String name) {
return Settings.Secure.getInt(mContext.getContentResolver(), name, 0) == 1;
}
private boolean checkUserSetupComplete() {
return Settings.Secure.getIntForUser(
mContext.getContentResolver(),
Settings.Secure.USER_SETUP_COMPLETE, 0,
UserHandle.USER_CURRENT) == 1;
}
private static class BaseCallbacks extends IQuickAccessWalletServiceCallbacks.Stub {
public void onGetWalletCardsSuccess(GetWalletCardsResponse response) {
throw new IllegalStateException();
}
public void onGetWalletCardsFailure(GetWalletCardsError error) {
throw new IllegalStateException();
}
public void onWalletServiceEvent(WalletServiceEvent event) {
throw new IllegalStateException();
}
public void onTargetActivityPendingIntentReceived(PendingIntent pendingIntent) {
throw new IllegalStateException();
}
}
}
|