android中经常会遇到自己的app会调用系统的Activity或是别人写的app中的Activity,那本文就来讲讲这个话题。
假如有app B,包名为com.abc.xxx,该app中有一个activity,名为com.abc.xxx.MainActivity,那我们在自己的程序中如何调用该activity呢。
<pre name="code" class="java">private View.OnClickListener onImageClickEvent = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.app_settings:
startSettings();
break;
case R.id.app_otherActivity:
startOtherActivity();
break;
default:
break;
}
}
};
在xml资源中定义
<ImageView
android:id="@+id/app_otherActivity"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_gravity="center"
android:src="@drawable/app_otherActivity" />
在点击该ImageView时,调用startOtherActivity()。那么接下来看看startOtherActivity()的写法,这才是本文的关键
<pre name="code" class="java">private void startOtherActivity() {
String packageName = "com.abc.xxx";
String activity = "com.abc.xxx.MainActivity";
ComponentName component = new ComponentName(packageName, activity);
Intent intent = new Intent();
intent.setComponent(component);
startActivity(intent);
}
调用android中的系统设置时,代码为
private void startSettings() {
String packageName = "com.android.settings";
String activity = "com.android.settings.Settings";
ComponentName component = new ComponentName(packageName, activity);
Intent intent = new Intent();
intent.setComponent(component);
startActivity(intent);
}