//WeakReference 弱引用,当WeakReference指向的对象是null时,gc就会回收这个对象
public class SMUIManager {
private static SMUIManager instance;
public static synchronized SMUIManager instance() {
if (instance == null) instance = new SMUIManager();
return instance;
}
private List> activitys = new ArrayList>();
private SMUIManager() {
}
public void pushActivity(BaseActivity activity) {
activitys.add(new WeakReference(activity));
}
public void popActivity(BaseActivity activity) {
removeActivity(activity.getIdentifier());
}
private void removeActivity(String identifier) {
for (int i = 0; i < activitys.size(); i++) {
WeakReference weakActivity = activitys.get(i);
BaseActivity activity = weakActivity.get();
if (activity != null && activity.getIdentifier().equals(identifier)) {
activitys.remove(weakActivity);
}
}
}
//出现异常处理这个
public void popAllAcitvity() {
while (activitys.size() > 0)
popActivity();
}
public void popActivity() {
WeakReference weakActivity = activitys.get(activitys.size() - 1);
BaseActivity activity = weakActivity.get();
if (activity != null) {
activity.finish();
}
activitys.remove(weakActivity);
}
/**
* 发送状态的消息
* @param msgCode 消息码
* @param param
*/
public void sendMessage(final int msgCode, final Object param) {
for (int i = 0; i < activitys.size(); i++) {
WeakReference weakActivity = activitys.get(i);
final BaseActivity activity = weakActivity.get();
if (activity != null) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
activity.onNotify(msgCode, param);
}
});}
}
}
public void sendDisMessage(final int msgCode, final Object param, final int stateCode) {
for (int i = 0; i < activitys.size(); i++) {
WeakReference weakActivity = activitys.get(i);
final BaseActivity activity = weakActivity.get();
if (activity != null) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
activity.onDisNotify(msgCode, param, stateCode);
}
});}
}
}
}
public class BaseActivity extends FragmentActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//基类中注册消息
SMUIManager.instance().pushActivity(this);
}
//每一个子类activity,子类fragment都可以收到消息
public void onNotify(final int msgCode, final Object param) {
List fragments = getSupportFragmentManager().getFragments();
if (fragments == null) return;
for (int i = 0; i < fragments.size(); i++) {
Fragment fragment = fragments.get(i);
if (fragment instanceof BaseFragment) {
((BaseFragment) fragment).onNotify(msgCode, param);
}
}
}
//每一个子类activity,子类fragment都可以收到消息
public void onDisNotify(final int msgCode, final Object param, final int statuCode) {
List fragments = getSupportFragmentManager().getFragments();
if (fragments == null) return;
for (int i = 0; i < fragments.size(); i++) {
Fragment fragment = fragments.get(i);
if (fragment instanceof BaseFragment) {
((BaseFragment) fragment).onNotify(msgCode, param);
}
}
}
@Override
protected void onDestroy() {
////基类中注销消息
SMUIManager.instance().popActivity(this);
super.onDestroy();
}
}
网友评论