繁体   English   中英

在Android中处理静态变量

[英]Handing static variables in android

我的应用程序中有很多活动(例如A-> B-> C-> D)...我有一个用于会话超时的倒数计时器。我所做的是创建一个静态计数器...我在活动A处启动计数器....如果用户进行了交互,则重置了计数器...这也适用于活动B,C,D ....在完成活动D时也开始活动A.已经使用过addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)以便清除堆栈...

但是发生的事情是当活动A重新开始时..一个新实例与前一个计数器一起创建并保持在后台运行....并且在用户交互时未重置...我在onDestroy中完成counter = null 。 ...是对的还是我需要做其他事情???

  public class CountTime extends Activity {

    TextView tv;
    static MyCount counter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tv = new TextView(this);
        this.setContentView(tv);
        // 5000 is the starting number (in milliseconds)
        // 1000 is the number to count down each time (in milliseconds)
        counter = new MyCount(5000, 1000);
        counter.start();
    }

    @Override
    public void onUserInteraction() {
        // TODO Auto-generated method stub
        super.onUserInteraction();
        counter.start();
    }

    // countdowntimer is an abstract class, so extend it and fill in methods
    public class MyCount extends CountDownTimer {
        public MyCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            tv.setText("done!");
        }

        @Override
        public void onTick(long millisUntilFinished) {
            tv.setText("Left: " + millisUntilFinished / 1000);
        }
    }
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        counter = null;
    }
}

这是正常的Android行为。

在任何时候,活动都不是前台活动,它可能会根据某些不确定性条件(例如空闲内存,正在运行多少后台应用程序等)而被销毁。

在您的情况下,活动A被销毁,当您返回活动A时,将创建一个新实例并调用它的onCreate()。

通常,您永远不要尝试从另一个活动访问活动中的某些内容。

您可以扩展应用程序类并在其中实例化计时器。

public class MyApplication extends Application{

    static MyCount counter;

    @Override public void onCreate () 
    {     
        super.onCreate();   
        counter = new MyCount();
    } 

}

在你的清单上

<application android:name="com.myname.MyApplication" 

您仅应在真正需要时使用此技术。 请不要将所有内容放在扩展应用程序类中,以使事情变得容易。 这确实是不好的做法。

最后,如果您的活动被销毁,则与Android没有达成协议将调用onDestroy()。 只有您自己完成活动才能保证。 您应该使用onPause()来执行活动进入后台(可能已被破坏)时需要发生的事情。

您可以通过替换此行来尝试

 counter = null;

到线

 counter.cancel();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM