0

更新:原来它可以在真实设备上运行,但不能在模拟器上运行!!

我有两个按钮,我将单击一个并启动计时器,然后单击另一个按钮并停止计时器。当我看到差异时,它总是与现实大相径庭:就像秒表显示 15 秒但代码显示 3 秒。我错过了什么?!

Long starttime = System.currentTimeMillis();
Long endtime = System.currentTimeMillis();
Long differenz = ((endtime-starttime) / 1000);

我也试过 System.nanoTime(); 但没有区别。

public OnClickListener startButtonListener = new OnClickListener(){

        @Override
        public void onClick(View theView) {

            //start music
            ding.start();

            //start timer
            startTime = System.currentTimeMillis();
            startTime1= System.nanoTime();
            Log.d(TAG, "The start time isCurrent: " + startTime);
            Log.d(TAG, "The start time isNano: " + startTime1);

        }

    };

public OnClickListener stopButtonListener = new OnClickListener(){

        @Override
        public void onClick(View theView) {

            //stop timer
            endTime = System.currentTimeMillis();
            endTime1= System.nanoTime();
            Log.d(TAG, "The stop time isCurrent: " + endTime);
            Log.d(TAG, "The stop time isNano: " + endTime1);
            //stop music
            ding.stop();

            //show the time on text view
            difference = (endTime-startTime) ;

            difference1 = (endTime1-startTime1) ;
            String difference_str = Long.toString(difference1);
            textView.setText(difference_str);
            Log.d(TAG, "The difference isCurrent: " + difference);
            Log.d(TAG, "The difference isNano: " + difference1);


            try {
                ding.prepare();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


        }

    };
4

1 回答 1

0

这对我有用:

Time start = new Time();
start.setToNow();

// yada yada yada

Time end = new Time();
end.setToNow();

long diff = end.toMillis(true) - start.toMillis(true);
于 2013-11-11T19:50:11.083 回答