本例验证的是finishiAffinity()方法,正如demo中介绍的那样No matter how deep you go,Activity.finishAffinity() will get you back,无论你走多远,它都能把你带
回来。
finishiAffinity()方法,可以关闭当前activity所属的activity栈中所有的activity。如果所有activity都保存在默认栈中,则使用该方法会直接退出程序。
本例是通过不断调用自身,向栈中添加任意的activity,尔后通过调用finishiAffinity()方法结束掉所有的activity。
布局文件activity_finish_affinity.xml,这里没有什么难理解的,也就设置了一个文字的外观样式。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="5dp" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="No matter how deep you go,Activity.finishAffinity() will get you back"/>
<TextView
android:id="@+id/tv_finish_nest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="5dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Current nesting:1"/>
<Button
android:id="@+id/bt_finish_nest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:text="nest some more" />
<Button
android:id="@+id/bt_finish_finish"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Finish!" />
</LinearLayout>
新建FinishAffinityActivity类
public class FinishAffinityActivity extends Activity {
private TextView tv_nest;
private Button bt_nest,bt_finish;
private int nesting;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_finish_affinity);
tv_nest=(TextView) findViewById(R.id.tv_finish_nest);
bt_nest=(Button) findViewById(R.id.bt_finish_nest);
bt_finish=(Button) findViewById(R.id.bt_finish_finish);
nesting=getIntent().getIntExtra("current_nesting", 1);
tv_nest.setText("Current nesting:"+nesting);
bt_nest.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 通过不断调用自身向栈中添加activity
Intent intent = new Intent(FinishAffinityActivity.this, FinishAffinityActivity.class);
intent.putExtra("current_nesting", nesting+1);
startActivity(intent);
}
});
bt_finish.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finishAffinity();
}
});
}
}
别忘记在配置文件中配置activity噢!