下面列出了android.content.Intent#getPackage ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@TargetApi(14)
private static void doCreateShortcut(Context context, String appName, Intent intent, String iconResourceName) {
Intent shortcutIntent = new Intent();
shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, appName);
if (iconResourceName != null) {
Intent.ShortcutIconResource ir = new Intent.ShortcutIconResource();
if (intent.getComponent() == null) {
ir.packageName = intent.getPackage();
} else {
ir.packageName = intent.getComponent().getPackageName();
}
ir.resourceName = iconResourceName;
shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, ir);
}
shortcutIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
context.sendBroadcast(shortcutIntent);
}
/**
* Returns true if the shortcuts already exists on the workspace. This must be called after
* the workspace has been loaded. We identify a shortcut by its intent.
*/
@Thunk boolean shortcutExists(Context context, Intent intent, UserHandleCompat user) {
assertWorkspaceLoaded();
final String intentWithPkg, intentWithoutPkg;
if (intent.getComponent() != null) {
// If component is not null, an intent with null package will produce
// the same result and should also be a match.
String packageName = intent.getComponent().getPackageName();
if (intent.getPackage() != null) {
intentWithPkg = intent.toUri(0);
intentWithoutPkg = new Intent(intent).setPackage(null).toUri(0);
} else {
intentWithPkg = new Intent(intent).setPackage(packageName).toUri(0);
intentWithoutPkg = intent.toUri(0);
}
} else {
intentWithPkg = intent.toUri(0);
intentWithoutPkg = intent.toUri(0);
}
synchronized (sBgLock) {
for (ItemInfo item : sBgItemsIdMap) {
if (item instanceof ShortcutInfo) {
ShortcutInfo info = (ShortcutInfo) item;
Intent targetIntent = info.promisedIntent == null
? info.intent : info.promisedIntent;
if (targetIntent != null && info.user.equals(user)) {
String s = targetIntent.toUri(0);
if (intentWithPkg.equals(s) || intentWithoutPkg.equals(s)) {
return true;
}
}
}
}
}
return false;
}
private void validateServiceIntent(Intent service) {
if (service.getComponent() == null && service.getPackage() == null) {
if (getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
IllegalArgumentException ex = new IllegalArgumentException(
"Service Intent must be explicit: " + service);
throw ex;
} else {
Log.w(TAG, "Implicit intents with startService are not safe: " + service
+ " " + Debug.getCallers(2, 3));
}
}
}
private void validateServiceIntent(Intent service) {
if (service.getComponent() == null && service.getPackage() == null) {
if (getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
IllegalArgumentException ex = new IllegalArgumentException(
"Service Intent must be explicit: " + service);
throw ex;
} else {
Log.w(TAG, "Implicit intents with startService are not safe: " + service
+ " " + Debug.getCallers(2, 3));
}
}
}
private void validateServiceIntent(Intent service) {
if (service.getComponent() == null && service.getPackage() == null) {
if (getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
IllegalArgumentException ex = new IllegalArgumentException(
"Service Intent must be explicit: " + service);
throw ex;
} else {
Log.w(TAG, "Implicit intents with startService are not safe: " + service
+ " " + Debug.getCallers(2, 3));
}
}
}
private void validateServiceIntent(Intent service) {
if (service.getComponent() == null && service.getPackage() == null) {
if (getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
IllegalArgumentException ex = new IllegalArgumentException(
"Service Intent must be explicit: " + service);
throw ex;
} else {
Log.w(TAG, "Implicit intents with startService are not safe: " + service
+ " " + Debug.getCallers(2, 3));
}
}
}
/**
* @return Whether the |url| could be handled by an external application on the system.
*/
public boolean canExternalAppHandleUrl(String url) {
if (url.startsWith(WTAI_MC_URL_PREFIX)) return true;
try {
Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
if (intent.getPackage() != null) return true;
List<ResolveInfo> resolvingInfos = mDelegate.queryIntentActivities(intent);
if (resolvingInfos != null && resolvingInfos.size() > 0) return true;
} catch (Exception ex) {
// Ignore the error.
Log.w(TAG, "Bad URI %s", url, ex);
}
return false;
}
private void validateServiceIntent(Intent service) {
if (service.getComponent() == null && service.getPackage() == null) {
if (getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
IllegalArgumentException ex = new IllegalArgumentException(
"Service Intent must be explicit: " + service);
throw ex;
} else {
Log.w(TAG, "Implicit intents with startService are not safe: " + service
+ " " + Debug.getCallers(2, 3));
}
}
}
private void validateServiceIntent(Intent service) {
if (service.getComponent() == null && service.getPackage() == null) {
if (getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
IllegalArgumentException ex = new IllegalArgumentException(
"Service Intent must be explicit: " + service);
throw ex;
} else {
Log.w(TAG, "Implicit intents with startService are not safe: " + service
+ " " + Debug.getCallers(2, 3));
}
}
}
/**
* Verifies if the intent should be restored.
*/
private void verifyIntent(String intentStr) throws Exception {
Intent intent = Intent.parseUri(intentStr, 0);
if (intent.getComponent() != null) {
verifyPackage(intent.getComponent().getPackageName());
} else if (intent.getPackage() != null) {
// Only verify package if the component was null.
verifyPackage(intent.getPackage());
}
}
@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
public List<ResolveInfo> queryIntentContentProviders(Intent intent, String resolvedType, int flags, int userId) {
checkUserId(userId);
ComponentName comp = intent.getComponent();
if (comp == null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
if (intent.getSelector() != null) {
intent = intent.getSelector();
comp = intent.getComponent();
}
}
}
if (comp != null) {
final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
final ProviderInfo pi = getProviderInfo(comp, flags, userId);
if (pi != null) {
final ResolveInfo ri = new ResolveInfo();
ri.providerInfo = pi;
list.add(ri);
}
return list;
}
// reader
synchronized (mPackages) {
String pkgName = intent.getPackage();
if (pkgName == null) {
return mProviders.queryIntent(intent, resolvedType, flags);
}
final PackageParser.Package pkg = mPackages.get(pkgName);
if (pkg != null) {
return mProviders.queryIntentForPackage(intent, resolvedType, flags, pkg.providers);
}
return null;
}
}
private void validateServiceIntent(Intent service) {
if (service.getComponent() == null && service.getPackage() == null) {
if (true || getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.KITKAT) {
Log.w(TAG, "Implicit intents with startService are not safe: " + service
+ " " + Debug.getCallers(2, 3));
//IllegalArgumentException ex = new IllegalArgumentException(
// "Service Intent must be explicit: " + service);
//Log.e(TAG, "This will become an error", ex);
//throw ex;
}
}
}
private void validateServiceIntent(Intent service) {
if (service.getComponent() == null && service.getPackage() == null) {
if (getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
IllegalArgumentException ex = new IllegalArgumentException(
"Service Intent must be explicit: " + service);
throw ex;
} else {
Log.w(TAG, "Implicit intents with startService are not safe: " + service
+ " " + Debug.getCallers(2, 3));
}
}
}
public ComponentName startService(Context context, Intent service) {
String packageName = service.getPackage();
if (TextUtils.isEmpty(packageName)) {
throw new NullPointerException("disallow null packageName.");
}
if (service.getComponent() == null) {
throw new NullPointerException("disallow null component");
}
String className = service.getComponent().getClassName();
return startPluginClientService(context, service, packageName,
className);
}
private static String getPackage(Intent intent) {
return intent.getComponent() != null ? intent.getComponent().getPackageName()
: intent.getPackage();
}
static String getTargetPackage(final Intent intent) {
final ComponentName component = intent.getComponent();
return component != null ? component.getPackageName() : intent.getPackage();
}
private void buildResolveList(Intent intent, FastImmutableArraySet<String> categories, boolean debug,
boolean defaultOnly, String resolvedType, String scheme, F[] src, List<R> dest) {
final String action = intent.getAction();
final Uri data = intent.getData();
final String packageName = intent.getPackage();
final int N = src != null ? src.length : 0;
boolean hasNonDefaults = false;
int i;
F filter;
for (i = 0; i < N && (filter = src[i]) != null; i++) {
int match;
// Is delivery being limited to filters owned by a particular
// package?
if (packageName != null && !isPackageForFilter(packageName, filter)) {
continue;
}
// Do we already have this one?
if (!allowFilterResult(filter, dest)) {
continue;
}
match = filter.match(action, resolvedType, scheme, data, categories, TAG);
if (match >= 0) {
if (!defaultOnly || filter.hasCategory(Intent.CATEGORY_DEFAULT)) {
final R oneResult = newResult(filter, match);
if (oneResult != null) {
dest.add(oneResult);
}
} else {
hasNonDefaults = true;
}
}
}
if (hasNonDefaults) {
if (dest.size() == 0) {
VLog.w(TAG, "resolveIntent failed: found match, but none with CATEGORY_DEFAULT");
} else if (dest.size() > 1) {
VLog.w(TAG, "resolveIntent: multiple matches, only some with CATEGORY_DEFAULT");
}
}
}
/**
* 从mIntent里面解析插件包名
* 1. 从Intent的package获取
* 2. 从Intent的ComponentName获取
* 3. 隐式Intent,从已安装插件列表中查找可以响应的插件
*
* @param mHostContext 主工程Context
* @param mIntent 需要启动的组件
* @return 返回需要启动插件的包名
*/
private static String tryParsePkgName(Context mHostContext, Intent mIntent) {
if (mIntent == null || mHostContext == null) {
return "";
}
String pkgName = mIntent.getPackage();
if (!TextUtils.isEmpty(pkgName) && !TextUtils.equals(pkgName, mHostContext.getPackageName())) {
// 与宿主pkgName不同
return pkgName;
}
ComponentName cpn = mIntent.getComponent();
if (cpn != null && !TextUtils.isEmpty(cpn.getPackageName())) {
// 显式启动插件
return cpn.getPackageName();
} else {
// 隐式启动插件
List<PluginLiteInfo> packageList =
PluginPackageManagerNative.getInstance(mHostContext).getInstalledApps();
if (packageList != null) {
// Here, loop all installed packages to get pkgName for this intent
String packageName = "";
ActivityInfo activityInfo = null;
ServiceInfo serviceInfo = null;
for (PluginLiteInfo info : packageList) {
if (info == null) {
continue;
}
PluginPackageInfo target = PluginPackageManagerNative.getInstance(mHostContext)
.getPluginPackageInfo(mHostContext, info);
if (target != null && (activityInfo = target.resolveActivity(mIntent)) != null) {
// 优先查找Activity, 这里转成显式Intent,后面不用二次resolve了
mIntent.setComponent(new ComponentName(info.packageName, activityInfo.name));
return info.packageName;
}
// resolve隐式Service
if (!TextUtils.isEmpty(packageName) && serviceInfo != null) {
continue;
}
if (target != null && (serviceInfo = target.resolveService(mIntent)) != null) {
packageName = info.packageName;
}
}
// Here, No Activity can handle this intent, we check service fallback
if (!TextUtils.isEmpty(packageName)) {
if (serviceInfo != null) {
// 插件框架后面的逻辑只支持显式Service处理,这里需要更新Intent的信息
mIntent.setComponent(new ComponentName(packageName, serviceInfo.name));
}
return packageName;
}
}
}
return "";
}
/**
* remapReceiverIntent
*
* @param hostCtx Context
* @param originIntent Intent
*/
public static void remapReceiverIntent(Context hostCtx, Intent originIntent) {
// 注意:pkg设置了插件包名的话,要替换成宿主包名,不然插件收不到广播
String pkg = originIntent.getPackage();
if (pkg != null && GPTPackageManager.getInstance(hostCtx).getPackageInfo(pkg) != null) {
originIntent.setPackage(hostCtx.getPackageName());
}
if (originIntent.getComponent() == null) {
return;
}
TargetMapping targetMapping = TargetManager.getInstance(hostCtx).getTargetMapping(
originIntent.getComponent().getPackageName());
if (targetMapping == null) {
return;
}
// 获取插件信息
GPTPackageInfo gptPkgInfo = GPTPackageManager.getInstance(hostCtx).getPackageInfo(
targetMapping.getPackageName());
if (gptPkgInfo == null) {
return;
}
String targetReceiver = originIntent.getComponent().getClassName();
ActivityInfo recvInfo = targetMapping.getReceiverInfo(targetReceiver);
if (recvInfo == null) {
return;
}
GPTComponentInfo info = new GPTComponentInfo();
info.packageName = targetMapping.getPackageName();
info.className = targetReceiver;
originIntent.addCategory(info.toString());
switch (gptPkgInfo.extProcess) {
case Constants.GPT_PROCESS_DEFAULT:
default:
if (!gptPkgInfo.isUnionProcess) {
originIntent.setClass(hostCtx, BroadcastReceiverProxyExt.class);
} else {
originIntent.setClass(hostCtx, BroadcastReceiverProxy.class);
}
break;
}
// 注意:pkg要替换成宿主,不然,插件收不到广播
originIntent.setPackage(hostCtx.getPackageName());
}
private void startShortcutIntentSafely(Intent intent, Bundle optsBundle, ItemInfo info) {
try {
StrictMode.VmPolicy oldPolicy = StrictMode.getVmPolicy();
try {
// Temporarily disable deathPenalty on all default checks. For eg, shortcuts
// containing file Uri's would cause a crash as penaltyDeathOnFileUriExposure
// is enabled by default on NYC.
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll()
.penaltyLog().build());
if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT) {
String id = ((ShortcutInfo) info).getDeepShortcutId();
String packageName = intent.getPackage();
DeepShortcutManager.getInstance(this).startShortcut(
packageName, id, intent.getSourceBounds(), optsBundle, info.user);
} else {
// Could be launching some bookkeeping activity
startActivity(intent, optsBundle);
}
} finally {
StrictMode.setVmPolicy(oldPolicy);
}
} catch (SecurityException e) {
// Due to legacy reasons, direct call shortcuts require Launchers to have the
// corresponding permission. Show the appropriate permission prompt if that
// is the case.
if (AndroidVersion.isAtLeastMarshmallow) {
if (intent.getComponent() == null
&& Intent.ACTION_CALL.equals(intent.getAction())
&& checkSelfPermission(Manifest.permission.CALL_PHONE) !=
PackageManager.PERMISSION_GRANTED) {
setWaitingForResult(PendingRequestArgs
.forIntent(REQUEST_PERMISSION_CALL_PHONE, intent, info));
requestPermissions(new String[]{Manifest.permission.CALL_PHONE},
REQUEST_PERMISSION_CALL_PHONE);
}
} else {
// No idea why this was thrown.
throw e;
}
}
}