Java中的CountdownTimer:每x秒做一些事情

时间:2014-08-19 09:45:51

标签: java android android-fragments countdowntimer

我已经从班级CountdownTimer.java创建了一个计数器,我想调整此计时器,以便它存储一个坐标,比如说每2秒钟。这应该是稍后的一般情况。现在,如果结果每秒存储一个坐标,我很高兴。

我遇到的问题是Timer太快了。按下Timer处的“开始”后,他会在1秒钟内打印出坐标! 我已经将结果打印出一个带有数据标记的文件,这就是为什么我知道它太快了。

所以这是我的代码:

package com.bosch.uadclient;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.osmdroid.util.GeoPoint;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.Fragment;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.SystemClock;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.uadclient.R;

public class PartyFragment extends Fragment {

    private MyCountdownTimer countDownTimer;
    private long pointsCollected;
    private boolean timerHasStarted = false;
    private TextView text;
    private TextView EdittextTime;
    private TextView EdittextIntervall;
    private TextView timeElapsedView;
    private ArrayList<String> arrayList = new ArrayList<String>();
    private long mPauseTime;
    private long startTime;
    private long interval;
    private int point = 0;
    private Button buttonTimer;
    // LocationProviderService locService;
    String s1 = "";
    String s2 = "";
    String lon = "";
    String lat = "";
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        LinearLayout rr = (LinearLayout) inflater.inflate(
                R.layout.capturefragment, container, false);
        EdittextTime = (TextView) rr.findViewById(R.id.editText1);
        EdittextIntervall = (TextView) rr.findViewById(R.id.EditText01);
        text = (TextView) rr.findViewById(R.id.timer);
        timeElapsedView = (TextView) rr.findViewById(R.id.pointsCollected);
        buttonTimer = (Button) rr.findViewById(R.id.button);
        buttonTimer.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Fragment fragment = new FindFragment();
                android.app.FragmentTransaction ft = getFragmentManager()
                        .beginTransaction();
                switch (v.getId()) {
                case R.id.button: {
                    String text0 = EdittextTime.getText().toString();
                    point = Integer.valueOf(text0);
                    long capture = point;
                    // Upload
                    String text1 = EdittextIntervall.getText().toString();
                    int sendinterval = Integer.valueOf(text1);
                    int sendintervall = sendinterval;
                    // Timer is self iniciated
                    startTime = 20000; // value in ms
                    interval = 1000;
                    countDownTimer = new MyCountdownTimer(startTime, interval);
                    text.setText(text.getText() + String.valueOf(startTime));
                    // ReadData and Parse File of coordinates
                    readfromFile();
                    String str1;
                    str1 = s1.toString();
                    readfromFile1();
                    String str2;
                    str2 = s2.toString();
                    GeoPoint geopoint = new GeoPoint(Double.parseDouble(str1),
                            Double.parseDouble(str2));

                    int AmountPoints = (int) ((startTime / 1000) / point);

                    if ((sendintervall > 0) && (capture > 0)) {
                        if (!timerHasStarted) {
                            countDownTimer.start();
                            timerHasStarted = true;
                            buttonTimer.setText("Tracing Started");
                            while (AmountPoints > 0) {
                                countDownTimer.onTick(1000, geopoint);
                                AmountPoints--;
                            }

                        } else {

                            countDownTimer.cancel();
                            timerHasStarted = false;
                            buttonTimer.setText("RESET");
                        }
                    } else {
                        System.out.println("Please type in all numbers");
                    }
                }
                    buttonTimer.setText("Tracing Stopped");
                    ft.commit();
                }
            }

        });

        return rr;
    }

    // CountDownTimer class
    public class MyCountdownTimer extends CountDownTimer {

        public MyCountdownTimer(long startTime, long interval) {
            super(startTime, interval);
        }


        public void onTick(long millisUntilFinished, GeoPoint geopoint) {


            pointsCollected = (int) ((startTime / 1000) / point);

            try {
                storeGPS(geopoint);
            } catch (IOException e) {
                System.out.println("Point can not be written");
                e.printStackTrace();
            }
        }

        /**
         * Pause the countdown.
         */
        public long pause() {
            long mStopTimeInFuture = 0;
            mPauseTime = mStopTimeInFuture - SystemClock.elapsedRealtime();
            boolean mPaused = true;
            return mPauseTime;
        }

        @Override
        public void onFinish() {
            text.setText("Points are sent!");
            timeElapsedView.setText("Points collected: "
                    + String.valueOf(pointsCollected));
        }

        @SuppressLint("SimpleDateFormat")
        public void storeGPS(GeoPoint gPt) throws IOException {

            String stringbb = gPt.toString();
            // SD card Access needed as a lot of points are saved
            File mediaDir = new File(Environment.getExternalStorageDirectory()
                    .getPath());
            if (!mediaDir.exists()) {
                mediaDir.mkdir();
            }

            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss ");
            String uhrzeit = sdf.format(new Date());

            File file = new File(mediaDir, "PointData.txt");
            // file.createNewFile();

            FileOutputStream fos = new FileOutputStream(file, true);
            fos.write(uhrzeit.getBytes());
            fos.write(stringbb.getBytes());
            fos.write(System.getProperty("line.separator").getBytes());
            fos.close();
            System.out.println("Your file has been written");
        }

        @Override
        public void onTick(long millisUntilFinished) {
            text.setText("Time in seconds remain:" + millisUntilFinished / 1000);
            pointsCollected = (int) (startTime / 1000 / point);
            timeElapsedView.setText("Points collected: "
                    + String.valueOf(pointsCollected));

        }

    }

}

以下是写入文件的输出:

19:26:11 9891183,52113450,0
19:26:11 9891183,52113450,0
19:26:11 9891183,52113450,0
19:26:11 9891183,52113450,0
19:26:11 9891183,52113450,0
19:26:11 9891183,52113450,0
19:26:11 9891183,52113450,0
19:26:11 9891183,52113450,0
19:26:11 9893183,52113450,0
19:26:11 9892283,52113450,0

祝福,玛丽塔

2 个答案:

答案 0 :(得分:0)

试试这段代码, 在此代码中,根据您的需要更改计划方法参数

计划(TimerTask任务,长延迟,长期)

import java.util.*;

public class TimerDemo {
public static void main(String[] args) {
  // creating timer task, timer
  TimerTask tasknew = new TimerSchedulePeriod();
  Timer timer = new Timer();

  // scheduling the task at interval
  timer.schedule(tasknew,100, 100);      
}
// this method performs the task
 public void run() {
  System.out.println("timer working");      
 }    
}

答案 1 :(得分:0)

我找到了解决问题的方法。虽然我不确定这是否是线程安全的?

                try {
                    storeGPS(geopoint);
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } catch (IOException e) {
                    System.out.println("Point can not be written");
                    e.printStackTrace();
                }