倒计时器的onTick方法即使在调用取消后仍然被调用

时间:2015-12-15 07:29:12

标签: java android android-layout android-fragments android-intent

我正在尝试加载一些数据。 Id数据在20秒内加载,而不是我开始新活动,否则我将通过提供一些相关消息来完成。我已经开始倒计时以记录时间。加载数据后,我想停止计时器。我有以下课程:

public class SplashActivity extends AppCompatActivity {

    private Context mContext;
    private Boolean mDataLoadedFromServer = false;
    private String mJSONData;
    private SplashTimerForLoadingMasterDataForAllChannels mTimer;

    private void stopTimer(){
        mTimer.cancel();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_splash);
        mTimer = new SplashTimerForLoadingMasterDataForAllChannels(20000,1000);
        mTimer.start();
    }



        class SplashTimerForLoadingMasterDataForAllChannels extends CountDownTimer {

        public SplashTimerForLoadingMasterDataForAllChannels(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            Log.d("testTimer", "SplashTimerForLoadingMasterDataForAllChannels");
            //SomE AsyncTAsk
            LoadData loaddata = new LoadData();
            loaddata.execute();
            //SomE AsyncTAsk
        }
        @Override
        public void onTick(long millisUntilFinished) {
            Log.d("testTimer", "onTick millisUntilFinished = " + millisUntilFinished + " mDataLoadedFromServer = " + mDataLoadedFromServer);
            //mDataLoadedFromServer is modified once Data is loaded in AsyncTask
            if(mDataLoadedFromServer) {
                stopTimer();
            }
        }

        @Override
        public void onFinish() {
            Log.d("testTimer", "onFinish");
            if(mDataLoadedFromServer) {
                mDataSavedAndNextActivityLaunched = true;
                if (Utils.checkIfUserLoggedIn()) {
                    mContext.startActivity(new Intent(mContext, ABCACtivity.class));
                } else {
                    mContext.startActivity(new Intent(mContext, XYZActivity.class));
                }
                finish();
            }
        }

    }



}

我在本地方法调用中取消它但是onTick仍然被调用。有人可以帮忙吗?

3 个答案:

答案 0 :(得分:1)

基本上,如果我从onTick()或onFinish(),即从内部定时器中取出它,计数器就不会停止。

然而,如果我从计时器之外的任何地方进行操作,它会非常容易地停止。

所以我的数据完全加载的时间点...我调用了timer.cancle()并且它完成了这个技巧。

然而,我仍然不明白为什么如果我们从计时器内部做同样的事情它不起作用。

答案 1 :(得分:1)

我尝试了这段代码片段,因为大多数答案都说你无法取消其实现中的计时器,因此我尝试在onFinish中使用处理程序。老帖子,但如果有人遇到这个它有用。

new Handler().post(new Runnable() {
        @Override
        public void run() {
            timerTextView.setText("00:" + String.format("%02d", counter));
            cancel();
        }
    });

答案 2 :(得分:0)

您需要在import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import javax.net.ServerSocketFactory; import javax.net.SocketFactory; public class SimpleChat { protected boolean running = true; protected int port; private Thread server; public static void main(String... arg) { //create 2 clients in the localhost to test SimpleChat app1 = new SimpleChat(8989); SimpleChat app2 = new SimpleChat(8988); app1.sendMessage("localhost", 8988, "Message from app1 to app2"); app2.sendMessage("localhost", 8989, "Message from app2 to app1"); System.exit(0); // ugly way to kill the threads and exit } public SimpleChat(int port) { this.port = port; start(); } public void start() { server = new Thread(new Server()); server.start(); } public boolean sendMessage(String host, int port, String message) { try { //Connect to a server on given host and port and "send" the message InetSocketAddress destination = new InetSocketAddress(host, port); Socket s = SocketFactory.getDefault().createSocket(); s.connect(destination); OutputStream out = s.getOutputStream(); out.write(message.getBytes()); out.flush(); out.close(); s.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } } public void messageRecived(String message) { System.out.println("Message recived: " + message); } public void stop() { this.running = false; // only stop after a socked connection } class Server implements Runnable { public void run() { try { //Create a server socket to recieve the connection ServerSocket ss = ServerSocketFactory.getDefault() .createServerSocket(port); while (running) { Socket s = ss.accept(); InputStream in = s.getInputStream(); StringBuilder message = new StringBuilder(); int len; byte[] buf = new byte[2048]; while ((len = in.read(buf)) > -1) { if (len > 0) { message.append(new String(buf, 0, len)); } } messageRecived(message.toString()); } } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } } } stopTimer()之外致电CountDownTimer

类似这样的事情

onTick()