1 /* 2 * Copyright (C) 2017 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.wallpaper.module; 17 18 import android.content.Context; 19 import android.content.Intent; 20 import android.content.pm.PackageManager; 21 import android.content.pm.ResolveInfo; 22 import android.net.Uri; 23 import android.os.AsyncTask; 24 25 import java.util.HashMap; 26 import java.util.List; 27 import java.util.Map; 28 29 import androidx.annotation.Nullable; 30 31 /** 32 * Checks whether an explore action can be taken for the given uri, i.e. whether any activity on 33 * the device is capable of handling it. 34 */ 35 public class DefaultExploreIntentChecker implements ExploreIntentChecker { 36 private Context mAppContext; 37 38 private Map<Uri, Intent> mUriToActionViewIntentMap; 39 DefaultExploreIntentChecker(Context appContext)40 public DefaultExploreIntentChecker(Context appContext) { 41 mAppContext = appContext; 42 mUriToActionViewIntentMap = new HashMap<>(); 43 } 44 45 @Override fetchValidActionViewIntent(Uri uri, IntentReceiver receiver)46 public void fetchValidActionViewIntent(Uri uri, IntentReceiver receiver) { 47 if (mUriToActionViewIntentMap.containsKey(uri)) { 48 receiver.onIntentReceived(mUriToActionViewIntentMap.get(uri)); 49 return; 50 } 51 52 new FetchActionViewIntentTask(mAppContext, uri, receiver).execute(); 53 } 54 55 private class FetchActionViewIntentTask extends AsyncTask<Void, Void, Intent> { 56 private Context mAppContext; 57 private Uri mUri; 58 private IntentReceiver mReceiver; 59 FetchActionViewIntentTask(Context appContext, Uri uri, IntentReceiver receiver)60 public FetchActionViewIntentTask(Context appContext, Uri uri, IntentReceiver receiver) { 61 mAppContext = appContext; 62 mUri = uri; 63 mReceiver = receiver; 64 } 65 66 @Nullable 67 @Override doInBackground(Void... params)68 protected Intent doInBackground(Void... params) { 69 Intent actionViewIntent = new Intent(Intent.ACTION_VIEW, mUri); 70 71 PackageManager pm = mAppContext.getPackageManager(); 72 List<ResolveInfo> activities = pm.queryIntentActivities(actionViewIntent, /* flags */ 0); 73 74 Intent result = activities.isEmpty() ? null : actionViewIntent; 75 mUriToActionViewIntentMap.put(mUri, result); 76 77 return result; 78 } 79 80 @Override onPostExecute(Intent intent)81 protected void onPostExecute(Intent intent) { 82 mReceiver.onIntentReceived(intent); 83 } 84 } 85 } 86 87