这里我简单介绍下跳转的三个方式,直接上方法了
这里你可以看到我没做非空判断 下面是网上流传的非常普遍的用法:
String package_name = "xx.xx.xx"; String activity_path = "xx.xx.xx.ab.xxActivity"; Intent intent = new Intent(); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//可选 ComponentName cn = new ComponentName(package_name,activity_path); intent.setComponent(cn); if (intent.resolveActivity(getPackageManager()) != null) { startActivity(intent); } else { //找不到指定的 Activity }但是经验证,Intent.resolveActivity() 方法并不能判定此方式所要启动的 Activity 是否存在,如果此 Activity 不存在,会报 Java.lang.IllegalArgumentException: Unknown component 异常,并导致程序崩溃。 所以我选择用resolveActivityInfo,这两种方法非常相似,咱们对比下源码
public ComponentName resolveActivity(PackageManager pm) { if (mComponent != null) { return mComponent; } ResolveInfo info = pm.resolveActivity(this, PackageManager.MATCH_DEFAULT_ONLY); if (info != null) { return new ComponentName( info.activityInfo.applicationInfo.packageName, info.activityInfo.name); } return null; } public ActivityInfo resolveActivityInfo(PackageManager pm, int flags) { ActivityInfo ai = null; if (mComponent != null) { try { ai = pm.getActivityInfo(mComponent, flags); } catch (PackageManager.NameNotFoundException e) { // ignore } } else { ResolveInfo info = pm.resolveActivity(this, PackageManager.MATCH_DEFAULT_ONLY | flags); if (info != null) { ai = info.activityInfo; } } return ai; }显而易见,resolveActivityInfo最后还是调用了resolveActivity,但是其内部做了处理和判断不会报IllegalArgumentException
所以最后的使用方式
Intent intent = new Intent(); ComponentName componentName=new ComponentName("com.example.admin.tiaoapp2","com.example.admin.tiaoapp2.MainActivity"); intent.setComponent(componentName); if (intent.resolveActivityInfo(getPackageManager(), PackageManager.MATCH_DEFAULT_ONLY) != null) { startActivity(intent); }如果按包名跳转会有两个进程,但是如果按activity跳转则 只有一个进程。(我就是掉坑了—。——)
这里在说下隐式启动第三方应用 此方式多用于启动系统中的功能性应用,比如打电话、发邮件、预览图片、使用默认浏览器打开一个网页等。
Intent intent = new Intent(); intent.setAction(action); intent.addCategory(category); intent.setDataAndType("abc://www.dfg.com","image/gif"); startActivity(intent); 条件1:IntentFilter 至少有一个action 至少有一个Category 可以没有Data和Type 条件2:如果有Data,参数中Data必须符合Data规则 条件3:Action和Category必须同时匹配Activity中的一个Action和一个Category(Category 默认:android.intent.category.DEFAULT)