显示Intent

显示Intent时明确Activity的类名的启动。有3种方法:

  • Intent(Context packageContext,Class<?> cls) 最常用
1
2
Intent intent = new Intent(this,SecondActivity.class);
startActivity(intent)
  • Intent的setComponent()方法;

    1
    2
    3
    4
    5
    6
    7
    ComponentName componentName = new ComponentName(this,secondActicity.class );
    ComponentName componentName = new ComponentName(this,"com.xx.xx.SecondActivity" );
    ComponentName componentName = new ComponentName(getPackageName(),"com.xx.xx.SecondActivity" );

    Intent intent = new Intent();
    intent.setComponent(componentName);
    startActivity(intent);
  • Intent的setClass/setClassName方法;

1
2
3
4
5
6
7
Intent intent = new Intent();

intent.setClass(this,SecondActivity.class);
intent.setClassName(this,"com.xx.xx.SecondActivity");
intent.setClassName(getPackageName(),"com.xx.xx.SecondActivity")

startActivity(intent);

ComponentName构造方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public ComponentName(@NonNull String pkg, @NonNull String cls) {
if (pkg == null) throw new NullPointerException("package name is null");
if (cls == null) throw new NullPointerException("class name is null");
mPackage = pkg;
mClass = cls;
}

public ComponentName(@NonNull Context pkg, @NonNull String cls) {
if (cls == null) throw new NullPointerException("class name is null");
mPackage = pkg.getPackageName();
mClass = cls;
}

public ComponentName(@NonNull Context pkg, @NonNull Class<?> cls) {
mPackage = pkg.getPackageName();
mClass = cls.getName();
}

setClass/setClassName源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public @NonNull Intent setClass(@NonNull Context packageContext, @NonNull Class<?> cls) {
mComponent = new ComponentName(packageContext, cls);
return this;
}

public @NonNull Intent setClassName(@NonNull Context packageContext,@NonNull String className) {
mComponent = new ComponentName(packageContext, className);
return this;
}

public @NonNull Intent setClassName(@NonNull String packageName, @NonNull String className) {
mComponent = new ComponentName(packageName, className);
return this;
}

所以setClass/setClassName内部用到的还是ComponentName。

隐式Intent

隐式Intent通过设置Action、Data、Category,让系统来筛选出合适的Activity。根据来筛选。

1
2
3
4
<intent-filter>
<action android:name="com.cy.demo" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
1
2
Intent intent = new Intent("com.cy.demo");
startActivity(intent)

可以通过隐式Intent可以直接调用外部的Activity。

可能会有重复,冲突的时候会有一个弹窗供用户选择。