1 /* 2 * Copyright (C) 2022 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package com.android.intentresolver.shortcuts 17 18 import android.app.prediction.AppPredictionContext 19 import android.app.prediction.AppPredictionManager 20 import android.app.prediction.AppPredictor 21 import android.content.Context 22 import android.content.IntentFilter 23 import android.os.Bundle 24 import android.os.UserHandle 25 26 // TODO(b/123088566) Share these in a better way. 27 private const val APP_PREDICTION_SHARE_UI_SURFACE = "share" 28 private const val APP_PREDICTION_SHARE_TARGET_QUERY_PACKAGE_LIMIT = 20 29 private const val APP_PREDICTION_INTENT_FILTER_KEY = "intent_filter" 30 private const val SHARED_TEXT_KEY = "shared_text" 31 32 /** 33 * A factory to create an AppPredictor instance for a profile, if available. 34 * @param context, application context 35 * @param sharedText, a shared text associated with the Chooser's target intent 36 * (see [android.content.Intent.EXTRA_TEXT]). 37 * Will be mapped to app predictor's "shared_text" parameter. 38 * @param targetIntentFilter, an IntentFilter to match direct share targets against. 39 * Will be mapped app predictor's "intent_filter" parameter. 40 */ 41 class AppPredictorFactory( 42 private val context: Context, 43 private val sharedText: String?, 44 private val targetIntentFilter: IntentFilter? 45 ) { 46 private val mIsComponentAvailable = 47 context.packageManager.appPredictionServicePackageName != null 48 49 /** 50 * Creates an AppPredictor instance for a profile or `null` if app predictor is not available. 51 */ createnull52 fun create(userHandle: UserHandle): AppPredictor? { 53 if (!mIsComponentAvailable) return null 54 val contextAsUser = context.createContextAsUser(userHandle, 0 /* flags */) 55 val extras = Bundle().apply { 56 putParcelable(APP_PREDICTION_INTENT_FILTER_KEY, targetIntentFilter) 57 putString(SHARED_TEXT_KEY, sharedText) 58 } 59 val appPredictionContext = AppPredictionContext.Builder(contextAsUser) 60 .setUiSurface(APP_PREDICTION_SHARE_UI_SURFACE) 61 .setPredictedTargetCount(APP_PREDICTION_SHARE_TARGET_QUERY_PACKAGE_LIMIT) 62 .setExtras(extras) 63 .build() 64 return contextAsUser.getSystemService(AppPredictionManager::class.java) 65 ?.createAppPredictionSession(appPredictionContext) 66 } 67 } 68