Android - 销毁指定Activity

转载请注明出处:https://blog.csdn.net/mythmayor/article/details/72842520

1.在自定义的Application中添加下面代码,在其它类中直接使用即可。

private static Map destroyMap = new HashMap<>();

/**
 * 添加到销毁队列
 *
 * @param activity 要销毁的activity
 */
public static void addDestroyActivity(Activity activity, String activityName) {
    destroyMap.put(activityName, activity);
}

/**
 * 销毁指定Activity
 */
public static void destroyActivity(String activityName) {
    Set keySet = destroyMap.keySet();
    if (keySet.size() > 0) {
        for (String key : keySet) {
            if (activityName.equals(key)) {
                destroyMap.get(key).finish();
            }
        }
    }
}

2.使用

AActivity.class

/**
 * Created by mythmayor on 2017/3/31.
 */

public class AActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_a);
        MainApplication.addDestroyActivity(this, "AActivity");      
    }
}

BActivity.class

/**
 * Created by mythmayor on 2017/3/31.
 */

public class BActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_b);
        MainApplication.destroyActivity("AActivity");
    }
}

你可能感兴趣的:(Android)