Я це робив у режимі спостерігачів.
Інтерфейс спостерігача
public interface Observer {
public void update(Subject subject);
}
Основний предмет
public class Subject {
private List<Observer> observers = new ArrayList<Observer>();
public void attach(Observer observer){
observers.add(observer);
}
public void detach(Observer observer){
observers.remove(observer);
}
protected void notifyObservers(){
for(Observer observer : observers){
observer.update(this);
}
}
}
Subject Subject реалізує метод виходу
public class ApplicationSubject extends Subject {
public void exit(){
notifyObservers();
}
}
MyApplication, який ваша програма повинна розширити
public class MyApplication extends Application {
private static ApplicationSubject applicationSubject;
public ApplicationSubject getApplicationSubject() {
if(applicationSubject == null) applicationSubject = new ApplicationSubject();
return applicationSubject;
}
}
Базова активність
public abstract class BaseActivity extends Activity implements Observer {
public MyApplication app;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
app = (MyApplication) this.getApplication();
app.getApplicationSubject().attach(this);
}
@Override
public void finish() {
// TODO Auto-generated method stub
app.getApplicationSubject().detach(this);
super.finish();
}
/**
* exit the app
*/
public void close() {
app.getApplicationSubject().exit();
};
@Override
public void update(Subject subject) {
// TODO Auto-generated method stub
this.finish();
}
}
давайте перевіримо це
public class ATestActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
close(); //invoke 'close'
}
}