Saya melakukannya dengan mode pengamat.
Antarmuka pengamat
public interface Observer {
public void update(Subject subject);
}
Subjek Dasar
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);
}
}
}
Subjek Anak mengimplementasikan metode keluar
public class ApplicationSubject extends Subject {
public void exit(){
notifyObservers();
}
}
Aplikasi saya yang harus diperluas oleh aplikasi Anda
public class MyApplication extends Application {
private static ApplicationSubject applicationSubject;
public ApplicationSubject getApplicationSubject() {
if(applicationSubject == null) applicationSubject = new ApplicationSubject();
return applicationSubject;
}
}
Aktivitas Dasar
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();
}
}
ayo kita coba
public class ATestActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
close(); //invoke 'close'
}
}