如何构建一个出现在所有应用程序屏幕中的全局计时器

How to build a global timer that appears in all app screens

我想构建一个具有增量值的全局计时器,并使用 Chronometer 显示在所有应用程序活动中,如何使 Chronometer 值对所有应用程序都是全局的?

使用静态方法初始化 getInstance 并检索值 getFormatedTime()。

public class CounterClass  extends CountDownTimer{

private static String hms;
private static CounterClass instance;

private CounterClass(long millisInFuture, long countDownInterval){
    super(millisInFuture,countDownInterval);
}

public static CounterClass  initInstance(long millisInFuture, long countDownInterval){
    if(instance==null){
        instance =  new CounterClass(millisInFuture,countDownInterval);
    }
    return instance;
}

public static CounterClass  getInstance() throws Exception{
    if(instance==null){
        throw new Exception("Parameters not initialized. Initiate with initInstance");
    }else{
        return instance;
    }
}

public static String getFormatedTime(){
    return hms;
}
@Override
public void onTick(long l) {

    long millis= l;
    hms= String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
            TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
            TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
    );
}
@Override
public void onFinish() {

}
}

我修改了代码

为了启动 CounterClass,请执行以下操作。

CounterClass counterClass = CounterClass.initInstance(180000, 1000);
counterClass.start();

用于访问之前的值

try {
      CounterClass counterClass = CounterClass.getInstance();
      Log.i("TAG 222", counterClass.getFormatedTime());
     } catch (Exception e) {
       e.printStackTrace();
       // counter class is not initiated , access initInstance
     }

由于android.os.CountDownTimer没有默认构造函数,我们可以通过这种方式实现您的要求

完整的代码解决方案,但我可以给你基本的想法,这就是我实现的方式。

在 BaseActivity 或应用程序中 class 你可以在我的例子中使用静态计时器,我已经使用了 BasActivity。

public static CountDownTimer timerBase;
private long startTimer;

现在,在执行特定操作时,这就是启动计时器的方法。

    public void sessionStart() {

        if (timerBase != null)
            timerBase.cancel();
          start = SystemClock.elapsedRealtime();
        timerBase = new CountDownTimer("Pass Total time the task should be excute", 1000) {
            @Override
            public void onTick(long millisUntilFinished) {

                long time = ("Pass Total time the task should be excute"/ 1000 - Math.round((float) millisUntilFinished / 1000.0f));
                String timeTakenForeachQue = String.valueOf(time);
                Log.e("counterValue", timeTakenForeachQue + " start = " + (SystemClock.elapsedRealtime() - start) / 1000 + " time " + millisUntilFinished / 1000);

            }

            @Override
            public void onFinish() {
               // Do stuff when time finish

                Toast.makeText(BaseActivity.this,"time finished" Toast.LENGTH_LONG).show();

            }
        }.start();
    }

}

现在您可以在任何 class 中访问此方法,因为它是 BaseActivity 或在应用程序中 class.Also 这只是如何实现整个任务无法发布的基本想法。

你可以很容易地尝试这个

将此添加到 xml

   <android.support.design.widget.CoordinatorLayout

                        xmlns:android="http://schemas.android.com/apk/res/android"
                        xmlns:app="http://schemas.android.com/apk/res-auto"
                        android:id="@+id/coordinatorLayout"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent">

                        <Chronometer
                            android:id="@+id/simpleChronometer"
                            android:layout_width="125dp"
                            android:layout_height="40dp"
                            android:layout_gravity="end"
                            android:layout_marginStart="8dp"
                            android:layout_marginTop="20dp"
                            android:layout_marginEnd="20dp"
                            android:gravity="center"
                            android:textColor="@color/white" />

                                    <Button
                                        android:id="@+id/next"
                                        android:layout_width="0dp"
                                        android:layout_height="match_parent"
                                        android:layout_weight="1"
                                        android:background="@color/green"
                                        android:gravity="center"
                                        android:text="@string/next"
                                        android:textColor="@color/white" />
                    </android.support.design.widget.CoordinatorLayout>

将此添加到您的 firstActivity

public class firstActivity extends AppCompatActivity  {

    private Button Next;
    private Chronometer simpleChronometer;
    Long base, timeDeviceImages;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(R.style.full_screen);
        setContentView(R.layout.activity_first);

        Next = (Button) findViewById(R.id.next);

        simpleChronometer = (Chronometer) findViewById(R.id.simpleChronometer);
        simpleChronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
            @Override
            public void onChronometerTick(Chronometer cArg) {
                long time = SystemClock.elapsedRealtime() - cArg.getBase();
                int h = (int) (time / 3600000);
                int m = (int) (time - h * 3600000) / 60000;
                int s = (int) (time - h * 3600000 - m * 60000) / 1000;
                String hh = h < 10 ? "0" + h : h + "";
                String mm = m < 10 ? "0" + m : m + "";
                String ss = s < 10 ? "0" + s : s + "";
                cArg.setText(hh + ":" + mm + ":" + ss);
            }
        });
        simpleChronometer.start();
        timeDeviceImages = simpleChronometer.getBase();

 Next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(firstActivity.this, UnitCondition.class);
                Bundle bundle = new Bundle();
                bundle.putString("timerJob", String.valueOf(timeDeviceImages));
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

  }
}

并在另一个 activity 中添加这个

public class secondActivity  extends AppCompatActivity  {
    private Chronometer simpleChronometer;
    Long base, timeDeviceImages;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(R.style.full_screen);
        setContentView(R.layout.activity_second);


        base = Long.valueOf(getIntent().getExtras().getString("timeUnit"));
        simpleChronometer = (Chronometer) findViewById(R.id.simpleChronometer);
        simpleChronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
            @Override
            public void onChronometerTick(Chronometer cArg) {
                long time = SystemClock.elapsedRealtime() - cArg.getBase();
                int h = (int) (time / 3600000);
                int m = (int) (time - h * 3600000) / 60000;
                int s = (int) (time - h * 3600000 - m * 60000) / 1000;
                String hh = h < 10 ? "0" + h : h + "";
                String mm = m < 10 ? "0" + m : m + "";
                String ss = s < 10 ? "0" + s : s + "";
                cArg.setText(hh + ":" + mm + ":" + ss);
            }
        });
        simpleChronometer.setBase((base));
        simpleChronometer.start();
        timeDeviceImages = simpleChronometer.getBase();
 }
}