方法一.
看看Google工程師是怎么判斷的(來源于Android源碼中的Call應(yīng)用嗓蘑,AsyncTask中的onPostExecute片段):
@Override
protected void onPostExecute(Void result) {
final Activity activity = progressDialog.getOwnerActivity();
if (activity == null || activity.isDestroyed() || activity.isFinishing()) {
return;
}
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
多了一個(gè)isDestroyed()的判斷
方法二.定義ActivityCollector
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.Set;
/**
* Author: jack
* Description:管理所有的棧中的Activity
*/
public class ActivityCollector {
/**
* 存放activity的列表
*/
public static HashMap<Class<?>, Activity> activities = new LinkedHashMap<>();
/**
* 添加Activity
*
* @param activity
*/
public static void addActivity(Activity activity, Class<?> clz) {
activities.put(clz, activity);
}
/**
* 判斷一個(gè)Activity 是否存在
*
* @param clz
* @return
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public static <T extends Activity> boolean isActivityExist(Class<T> clz) {
boolean res;
Activity activity = getActivity(clz);
if (activity == null) {
res = false;
} else {
if (activity.isFinishing() || activity.isDestroyed()) {
res = false;
} else {
res = true;
}
}
return res;
}
/**
* 獲得指定activity實(shí)例
*
* @param clazz Activity 的類對(duì)象
* @return
*/
public static <T extends Activity> T getActivity(Class<T> clazz) {
return (T) activities.get(clazz);
}
/**
* 移除activity,代替finish
*
* @param activity
*/
public static void removeActivity(Activity activity) {
if (activities.containsValue(activity)) {
activities.remove(activity.getClass());
}
}
/**
* 移除所有的Activity
*/
public static void removeAllActivity() {
if (activities != null && activities.size() > 0) {
Set<Entry<Class<?>, Activity>> sets = activities.entrySet();
for (Entry<Class<?>, Activity> s : sets) {
if (!s.getValue().isFinishing()) {
s.getValue().finish();
}
}
}
activities.clear();
}
}
在 App中的BaseActivity中
public class BaseActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityCollector.addActivity(this, getClass());
}
@Override
protected void onDestroy() {
super.onDestroy();
ActivityCollector.removeActivity(this);
}
}
然后所有的Activity都去繼承 BaseActvity 就可以使 ActivityCollector起作用了贤姆。
好處
- 在應(yīng)用的任何地方都可以去獲取到 Activity實(shí)例,從而操作指定的 View對(duì)象
MainActivity mainActivity = ActivityCollector.getActivity(MainActivity.class);
if (mainActivity!=null) mainActivity.main_radio.check(R.id.radio_button1);
- 判斷一個(gè) Activity是否存在
ActivityCollector.isActivityExist(MainActivity.class);
參考資料
- 如何判斷Activity是否在運(yùn)行煎源?
- ActivityManager 來實(shí)現(xiàn),請(qǐng)戳我的博客:ActivityManager.