4.活动的4种启动模式(launchMode)

AndroidManifest.xml给指定的<Activity>标签选择android:launchMode属性,可选4种属性:standard(默认)、singleTop、 singleTask、singleInstance。

(1)standard(标准模式)

新建FirstActivity,FirstActivity.java中onCreate方法中按钮事件

Button btn_to_this = findViewById(R.id.btn_to_this);
btn_to_this.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent = new Intent(FirstActivity.this, FirstActivity.class);
        startActivity(intent);

    }
});

在activity_first.xml中文本和按钮

<TextView
    android:id="@+id/tv_"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="20dp"
    android:gravity="center"
    android:text="This is FirstActivity"
    android:textSize="24sp" />
<Button
    android:id="@+id/btn_to_this"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Click to this"
    android:textAllCaps="false"
    android:textSize="24sp" />



(2)singleTop

AndroidManifest.xml中指定FirstActivity的android:launchMode属性值singleTop

<activity android:name=".FirstActivity" android:launchMode="singleTop">

新建SecondActivity,SecondActivity.java中onCreate方法中按钮事件

Button btn_second = findViewById(R.id.btn_second);
btn_second.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent = new Intent(SecondActivity.this, FirstActivity.class);
        startActivity(intent);
    }
});

activity_second.xml中文本和按钮

<TextView
    android:id="@+id/tv_"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="20dp"
    android:gravity="center"
    android:text="This is SecondActivity"
    android:textSize="24sp" />

<Button
    android:id="@+id/btn_second"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Click to FirstActivity"
    android:textAllCaps="false"
    android:textSize="24sp" />

FirstActivity.java中增加btn_to_second按钮事件

 
 
Button btn_to_second = findViewById(R.id.btn_to_second);
btn_to_second.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
        startActivity(intent);
    }
});

activity_first.xml中增加btn_to_second按钮

<Button
    android:id="@+id/btn_to_second"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Click to SecondActivity"
    android:textAllCaps="false"
    android:textSize="24sp" />




(3)singleTask

<activity android:name=".FirstActivity" android:launchMode="singleTask">



(4)singleInstance


发布了30 篇原创文章 · 获赞 2 · 访问量 6426

猜你喜欢

转载自blog.csdn.net/yaochaohx/article/details/80307226
今日推荐