首先在前臺計數活動
public class ActivitiesCounter {
public interface ApplicationLaunchListener{
public void onLaunch();
}
private int mCounter = 0;
private ApplicationLaunchListener mListener;
private static ActivitiesCounter mInstance = new ActivitiesCounter();
public static ActivitiesCounter getInstance(){
return mInstance;
}
public void increase(){
if(mCounter == 0){
if(mListener != null){
mListener.onLaunch();
}
}
mCounter++;
}
public void decrease(){
mCounter--;
}
public void setApplicationLaunchListener(ApplicationLaunchListener listener){
mListener = listener;
}
}
然後活動創造單:
public class MyActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ActivitiesCounter.getInstance().setApplicationLaunchListener(new ActivitiesCounter.ApplicationLaunchListener() {
@Override
public void onLaunch() {
Toast.makeText(MyActivity.this, "launched", Toast.LENGTH_LONG).show();
}
});
findViewById(R.id.btn_activity_b).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MyActivity.this, ActivityB.class);
startActivity(intent);
}
});
}
@Override
protected void onStart() {
super.onStart();
ActivitiesCounter.getInstance().increase();
}
@Override
protected void onStop() {
ActivitiesCounter.getInstance().decrease();
super.onStop();
}
}
活動B也應該增加和減少計數器
public class ActivityB extends Activity {
@Override
protected void onStart() {
super.onStart();
ActivitiesCounter.getInstance().increase();
}
@Override
protected void onStop() {
ActivitiesCounter.getInstance().decrease();
super.onStop();
}
}
它更好地爲應用中的所有活動(然後,你不需要覆蓋在onStart,的onStop每次)
那麼你不應該已經接受了部分答案創建BaseActivity(藉助onStart,的onStop) 。或者你需要問兩個不同的問題,每個問題都是針對ios和android。 –