मैंने इसे ऑब्जर्वर मोड के साथ किया।
प्रेक्षक का इंटरफ़ेस
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'
}
}