下面列出了android.content.Intent#getComponent ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void startAsViewClickEdit() throws Exception
{
ActivityController activityController = setupActivity("budget", "", true, false);
Activity activity = (Activity)activityController.get();
shadowOf(activity).clickMenuItem(R.id.action_edit);
ShadowActivity shadowActivity = shadowOf(activity);
Intent startedIntent = shadowActivity.getNextStartedActivity();
ComponentName name = startedIntent.getComponent();
assertNotNull(name);
assertEquals("protect.budgetwatch/.TransactionViewActivity", name.flattenToShortString());
Bundle bundle = startedIntent.getExtras();
assertNotNull(bundle);
assertEquals(DBHelper.TransactionDbIds.EXPENSE, bundle.getInt("type", -1));
assertEquals(1, bundle.getInt("id", -1));
assertEquals(true, bundle.getBoolean("update", false));
assertEquals(false, bundle.getBoolean("view", false));
}
/**
* Given an AppTask retrieves the task class name.
* @param task The app task to use.
* @param pm The package manager to use for resolving intent.
* @return Fully qualified class name or null if we were not able to
* determine it.
*/
public static String getTaskClassName(AppTask task, PackageManager pm) {
RecentTaskInfo info = getTaskInfoFromTask(task);
if (info == null) return null;
Intent baseIntent = info.baseIntent;
if (baseIntent == null) {
return null;
} else if (baseIntent.getComponent() != null) {
return baseIntent.getComponent().getClassName();
} else {
ResolveInfo resolveInfo = pm.resolveActivity(baseIntent, 0);
if (resolveInfo == null) return null;
return resolveInfo.activityInfo.name;
}
}
@SuppressWarnings("ConstantConditions")
@Override
protected void handleInternal(@NonNull UriRequest request, @NonNull UriCallback callback) {
// 创建Intent
Intent intent = createIntent(request);
if (intent == null || intent.getComponent() == null) {
Debugger.fatal("AbsActivityHandler.createIntent()应返回的带有ClassName的显式跳转Intent");
callback.onComplete(UriResult.CODE_ERROR);
return;
}
intent.setData(request.getUri());
UriSourceTools.setIntentSource(intent, request);
// 启动Activity
request.putFieldIfAbsent(ActivityLauncher.FIELD_LIMIT_PACKAGE, limitPackage());
int resultCode = RouterComponents.startActivity(request, intent);
// 回调方法
onActivityStartComplete(request, resultCode);
// 完成
callback.onComplete(resultCode);
}
/**
* 将Notification的Intent转换成用广播传递的Intent
* <p>
* 主要用于自定义Notification时处理点击打开Activity的事件,使用此方法
* 将会在应用启动时直接打开目标Activity,应用未启动时先启动应用再打开Activity
* </p>
* */
public static PendingIntent getBroadcastIntent(Context context, Intent targetActivityIntent) {
Intent broadcastIntent = new Intent(context, NotificationReceiver.class);
Bundle bundle = new Bundle();
if (targetActivityIntent.getExtras() != null) {
bundle.putAll(targetActivityIntent.getExtras());
}
if (targetActivityIntent.getComponent() != null) {
bundle.putString(KEY_TARGET_ACTIVITY_NAME,
targetActivityIntent.getComponent().getClassName());
}
broadcastIntent.putExtra(NotificationManager.KEY_NOTIFICATION_EXTRA, bundle);
return PendingIntent.getBroadcast(context, 0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
}
@Override
public Drawable getActivityBanner(Intent intent)
throws NameNotFoundException {
if (intent.getComponent() != null) {
return getActivityBanner(intent.getComponent());
}
ResolveInfo info = resolveActivity(
intent, PackageManager.MATCH_DEFAULT_ONLY);
if (info != null) {
return info.activityInfo.loadBanner(this);
}
throw new NameNotFoundException(intent.toUri(0));
}
public int stopService(IApplicationThread caller, Intent service,
String resolvedType, int userId) {
if (service.getComponent() != null && ProxyEnvironment.hasInstance(service.getComponent().getPackageName())) {
return ServiceProxy.stopServiceExternal(service.getComponent());
} else {
return mTarget.stopService(caller, service, resolvedType, userId);
}
}
/**
* 获取目标类型,activity or service or broadcast
* @param intent
* @return
*/
public static int getTargetType(Intent intent) {
Iterator<PluginDescriptor> itr = getPlugins().iterator();
while (itr.hasNext()) {
PluginDescriptor plugin = itr.next();
// 如果是通过组件进行匹配的
if (intent.getComponent() != null) {
if (plugin.containsName(intent.getComponent().getClassName())) {
return plugin.getType(intent.getComponent().getClassName());
}
} else {
String clazzName = findClassNameByIntent(intent, plugin.getActivitys());
if (clazzName == null) {
clazzName = findClassNameByIntent(intent, plugin.getServices());
}
if (clazzName == null) {
clazzName = findClassNameByIntent(intent, plugin.getReceivers());
}
if (clazzName != null) {
return plugin.getType(clazzName);
}
}
}
return PluginDescriptor.UNKOWN;
}
private void wrapIntent(Intent intent) {
ComponentName component = intent.getComponent();
String realClazz;
if (component == null) {
// Try to resolve the implicit action which has registered in host.
component = intent.resolveActivity(Small.getContext().getPackageManager());
if (component != null) {
// A system or host action, nothing to be done.
return;
}
// Try to resolve the implicit action which has registered in bundles.
realClazz = resolveActivity(intent);
if (realClazz == null) {
// Cannot resolved, nothing to be done.
return;
}
} else {
realClazz = component.getClassName();
if (realClazz.startsWith(STUB_ACTIVITY_PREFIX)) {
// Re-wrap to ensure the launch mode works.
realClazz = unwrapIntent(intent);
}
}
if (sLoadedActivities == null) return;
ActivityInfo ai = sLoadedActivities.get(realClazz);
if (ai == null) return;
// Carry the real(plugin) class for incoming `newActivity' method.
intent.addCategory(REDIRECT_FLAG + realClazz);
String stubClazz = dequeueStubActivity(ai, realClazz);
intent.setComponent(new ComponentName(Small.getContext(), stubClazz));
}
@Override
public Drawable getActivityBanner(Intent intent)
throws NameNotFoundException {
if (intent.getComponent() != null) {
return getActivityBanner(intent.getComponent());
}
ResolveInfo info = resolveActivity(
intent, PackageManager.MATCH_DEFAULT_ONLY);
if (info != null) {
return info.activityInfo.loadBanner(this);
}
throw new NameNotFoundException(intent.toUri(0));
}
@Override public void setIntent(final Intent intent) {
final ComponentName component = intent.getComponent();
if (component != null && PACKAGE_PLACEHOLDER_SELF.equals(component.getPackageName())) {
if (component.getClassName().isEmpty()) intent.setPackage(getContext().getPackageName()).setComponent(null);
else intent.setComponent(new ComponentName(getContext().getPackageName(), component.getClassName()));
}
super.setIntent(intent);
}
@Override
public Drawable getActivityLogo(Intent intent)
throws NameNotFoundException {
if (intent.getComponent() != null) {
return getActivityLogo(intent.getComponent());
}
ResolveInfo info = resolveActivity(
intent, PackageManager.MATCH_DEFAULT_ONLY);
if (info != null) {
return info.activityInfo.loadLogo(this);
}
throw new NameNotFoundException(intent.toUri(0));
}
@Override
public Drawable getActivityBanner(Intent intent)
throws NameNotFoundException {
if (intent.getComponent() != null) {
return getActivityBanner(intent.getComponent());
}
ResolveInfo info = resolveActivity(
intent, PackageManager.MATCH_DEFAULT_ONLY);
if (info != null) {
return info.activityInfo.loadBanner(this);
}
throw new NameNotFoundException(intent.toUri(0));
}
public Bitmap getIcon(Intent intent) {
synchronized (mCache) {
final ResolveInfo resolveInfo = mPackageManager.resolveActivity(intent, 0);
ComponentName component = intent.getComponent();
if (resolveInfo == null || component == null) {
return mDefaultIcon;
}
CacheEntry entry = cacheLocked(component, resolveInfo, null);
return entry.icon;
}
}
public void testSettingComponent() {
Intent sentIntent = new Intent(instrumentation.getTargetContext(),
ReceiverTestActivity.class);
startActivity(sentIntent, null, null);
Intent receivedIntent = getActivity().getIntent();
assertTrue(receivedIntent != null);
assertTrue(receivedIntent.getPackage() == null);
ComponentName receivedComponentName = receivedIntent.getComponent();
assertTrue(receivedComponentName != null);
String packageName = receivedComponentName.getPackageName();
assertEquals(packageName, getActivity().getPackageName());
}
@Override
public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, int 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) {
List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
ActivityInfo ai = getReceiverInfo(comp, flags, userId);
if (ai != null) {
ResolveInfo ri = new ResolveInfo();
ri.activityInfo = ai;
list.add(ri);
}
return list;
}
// reader
synchronized (mPackages) {
String pkgName = intent.getPackage();
if (pkgName == null) {
return mReceivers.queryIntent(intent, resolvedType, flags);
}
final PackageParser.Package pkg = mPackages.get(pkgName);
if (pkg != null) {
return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers);
}
return null;
}
}
/**
* Restart the app.
*/
public static void restartApp() {
Context context = getContext();
PackageManager packageManager = context.getPackageManager();
Intent intent = packageManager.getLaunchIntentForPackage(context.getPackageName());
ComponentName componentName = intent.getComponent();
Intent mainIntent = Intent.makeRestartActivityTask(componentName);
context.startActivity(mainIntent);
System.exit(0);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if ("startActivity".equals(method.getName())) {
int index = -1;
for (int i = 0; i < args.length; i++) {
if (args[i] instanceof Intent) {
index = i;
break;
}
}
if (index != -1) {
Intent raw = (Intent) args[index];
ComponentName component = raw.getComponent();
//log("startActivity, rawIntent=" + raw);
if (component != null &&
component.getClassName().startsWith("nil.nadph.qnotified.")) {
Intent wrapper = new Intent();
wrapper.setClassName(component.getPackageName(), ActProxyMgr.STUB_ACTIVITY);
wrapper.putExtra(ActProxyMgr.ACTIVITY_PROXY_INTENT, raw);
args[index] = wrapper;
//log("startActivity, wrap intent with " + wrapper);
}
}
}
try {
return method.invoke(mOrigin, args);
} catch (InvocationTargetException ite) {
throw ite.getTargetException();
}
}
/**
* 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.
*/
private boolean shortcutExists(BgDataModel dataModel, Intent intent, UserHandle user) {
final String intentWithPkg, intentWithoutPkg;
if (intent == null) {
// Skip items with null intents
return true;
}
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 (dataModel) {
for (ItemInfo item : dataModel.itemsIdMap) {
if (item instanceof ShortcutInfo) {
ShortcutInfo info = (ShortcutInfo) item;
if (item.getIntent() != null && info.user.equals(user)) {
Intent copyIntent = new Intent(item.getIntent());
copyIntent.setSourceBounds(intent.getSourceBounds());
String s = copyIntent.toUri(0);
if (intentWithPkg.equals(s) || intentWithoutPkg.equals(s)) {
return true;
}
}
}
}
}
return false;
}
public ComponentName startService(Intent intent) {
String packageName;
String className;
if (intent.getComponent() != null) {
packageName = intent.getComponent().getPackageName();
className = intent.getComponent().getClassName();
} else {
ResolveInfo resolveService = getBaseContext().getPackageManager().resolveService(intent, 0);
if (resolveService == null || resolveService.serviceInfo == null) {
className = null;
packageName = null;
} else {
packageName = resolveService.serviceInfo.packageName;
className = resolveService.serviceInfo.name;
}
}
if (!StringUtils.equals(getBaseContext().getPackageName(), packageName)) {
return super.startService(intent);
}
packageName = DelegateComponent.locateComponent(className);
if (packageName != null) {
BundleImpl bundleImpl = (BundleImpl) Framework.getBundle(packageName);
if (bundleImpl != null) {
try {
bundleImpl.startBundle();
} catch (BundleException e) {
log.error(e.getMessage() + " Caused by: ", e.getNestedException());
}
}
return super.startService(intent);
}
try {
if (ClassLoadFromBundle.loadFromUninstalledBundles(className) != null) {
return super.startService(intent);
}
} catch (ClassNotFoundException e2) {
log.info("Can't find class " + className + " in all bundles.");
}
try {
if (Framework.getSystemClassLoader().loadClass(className) != null) {
return super.startService(intent);
}
return null;
} catch (ClassNotFoundException e3) {
log.error("Can't find class " + className);
return null;
}
}
/**
* Perform instantiation of the process's {@link Activity} object. The
* default implementation provides the normal system behavior.
*
* @param cl The ClassLoader with which to instantiate the object.
* @param className The name of the class implementing the Activity
* object.
* @param intent The Intent object that specified the activity class being
* instantiated.
*
* @return The newly instantiated Activity object.
*/
public Activity newActivity(ClassLoader cl, String className,
Intent intent)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException {
String pkg = intent != null && intent.getComponent() != null
? intent.getComponent().getPackageName() : null;
return getFactory(pkg).instantiateActivity(cl, className, intent);
}