Я сделал это в режиме наблюдателя.
Интерфейс наблюдателя
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);
}
}
}
Дочерний субъект реализует метод выхода
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'
}
}