首先创建单例来计算前台的活动
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();
}
}
最好为您的应用程序中的所有活动创建 BaseActivity(带有 onStart,onStop)(然后,您不需要每次都覆盖 onStart,onStop)