如何在后台运行计时器?

时间:2016-04-29 07:18:12

标签: android android-studio

我有一个计时器的代码,但是如果我改变了片段,计时器被重置为00:00我想在我点击停止或暂停之后计时器仍然计数或者这意味着这个计时器仍然在后台计算 怎么做 ? 这是我的代码,

public class TimerFragment extends BaseFragment {
    private Button startButton;
    private Button pauseButton;
    private TextView timerValue;
    private long startTime = 0L;
    private Handler customHandler = new Handler();
    long timeInMilliseconds = 0L;
    long timeSwapBuff = 0L;
    long updatedTime = 0L;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_timer, container, false);

        initialize();
        //when start

        startTime = SystemClock.uptimeMillis();
        customHandler.postDelayed(updateTimerThread, 0);

        //pause
        pauseButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {

                timeSwapBuff += timeInMilliseconds;
                customHandler.removeCallbacks(updateTimerThread);

            }
        });

        return rootView;
    }

    private Runnable updateTimerThread = new Runnable() {

        public void run() {

            timeInMilliseconds = SystemClock.uptimeMillis() - startTime;

            updatedTime = timeSwapBuff + timeInMilliseconds;

            int secs = (int) (updatedTime / 1000);
            int mins = secs / 60;
            secs = secs % 60;

            timerValue.setText("" + mins + ":"
                    + String.format("%02d", secs));
            customHandler.postDelayed(this, 0);
        }

    };

谢谢你

1 个答案:

答案 0 :(得分:1)

问题: - 当您切换片段并返回到Timer Fragment时,将调用onCreate生命周期回调并且不会重置您的计时器

  

customHandler.postDelayed(updateTimerThread,0);

解决方案: - 将计时器逻辑移动到Activity类,但是会在方向更改时重新创建活动,因此将计时器逻辑移动到Application类中: -

将此课程放在项目包中

import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Application;
import android.os.Handler;
import android.widget.Toast;

public class App extends Application {

    public static App appInstance;
    private SimpleDateFormat dateFormat;

    @Override
    public void onCreate() {
        super.onCreate();

        appInstance = this;

        dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    }

    public void afficher() {
        Toast.makeText(getBaseContext(), dateFormat.format(new Date()), 300).show();
        handler.postDelayed(runnable,1000);
    }

    public void startTimer() {
        runnable.run();
    }

    public void stopTimer() {
        handler.removeCallbacks(runnable);
    }

    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        public void run() {
            afficher();
        }
    };

}

应用程序名称设置为应用程序类,如下所示(应用程序的android名称属性): -

   <application
        android:name="com.masterdetail_webview.App"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.masterdetail_webview.TimertestActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

现在你可以从任何地方开始和停止计时器

findViewById(R.id.button1).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            App.appInstance.startTimer();

        }
    });

    findViewById(R.id.button2).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            App.appInstance.stopTimer();

        }
    });

添加AppController

enter image description here