Android 点击关闭所有activity

有两种方式一种是用广播点击关闭所有打开activity,点击用广播关闭activity的例子网上比较多,在这里就不做介绍了。我是用一个list集合控制activity的,每当打开一个activity写的全局类,就记录一个,然后在最后把记录的activity,   finis掉就行了。
My_Aplication(要在清单文件的apllcation里面注册)

import android.app.Activity;
import android.app.Application;

import java.util.ArrayList;
import java.util.List;

public class My_Aplication extends Application{
    public List list;

    @Override
    public void onCreate() {
        super.onCreate();
        list=new ArrayList();
    }
    public void dateActivity(Activity activity){
        list.add(activity);
    }
}

MainActivity(下面打开的Activity,都会通过全局类,记录到List集合里面)

import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private List list;
    private Button mBtn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ((My_Aplication)getApplicationContext()).dateActivity(MainActivity.this);
        mBtn= (Button) findViewById(R.id.mBtn);
    }

    public void onClick(View view) {
        startActivity(new Intent(MainActivity.this,B.class));
    }
}

B

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class B extends Activity{
    private Button mBtn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.b);
        ((My_Aplication)getApplicationContext()).dateActivity(B.this);
        mBtn= (Button) findViewById(R.id.mBtn);
    }

    public void onClick(View view) {
        startActivity(new Intent(B.this,C.class));
    }
}

C(在最终的方法里面,从list里面找到每一个打开过的activity,赋值给activity,然后在把activity关掉)

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.util.List;

public class C extends Activity{
    private List list;
    private Button mBtn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.c);
        list=((My_Aplication)getApplicationContext()).list;
        mBtn=(Button) findViewById(R.id.mBtn);
    }

    public void onClick(View view) {
        for (int i=0;i

activity别忘了注册。。。。。

你可能感兴趣的:(Android)