0

我不知道这是否可能,但我有几个活动,目前有两个,我有 20 分钟的时间限制让玩家完成游戏。问题是,他从一项活动开始,然后进行另一项活动,依此类推。如何在另一个活动中保持计时器继续运行,并使其在 textView 中可见?

编辑 minhaz:

public void getTime(long value, String PREFERENCE_NAME){
        SharedPreferences myPrefs = mContext.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor prefsEditor = myPrefs.edit();
        prefsEditor.putLong("time", value);
        prefsEditor.commit();
    }
4

3 回答 3

1

只需创建一个全局计时器类。

class Timer {
    private static long startTime = -1;

    public static void reset() {Timer.startTime = -1;}
    public static void initialize() {Timer.startTime = System.currentTimeMillis();}
    public static long getTimeMillis() {return System.currentTimeMillis() - startTime;}

    private Timer() {}
}

然后,通过导入这个类(无论你把它放在哪里),你可以访问当前时间。

于 2013-04-24T17:13:40.570 回答
0

从一个活动启动计时器,当用户切换到下一个活动时,传递 Intent 中的值

Intent intent=new Intent(Current.class, NextActivity.class);
intent.putExtra("time", timer_value);

而在另一个活动上获得的价值为

time_value=intent.getLongExtra("time")

通过这种方式,用户将获得一些缓冲时间,当他们在活动之间延迟时,因为启动活动调用是异步的。finsh()您可以根据当时的要求打电话或做其他事情。

如果您想限制启动应用程序的时间,扩展应用程序类也是一个很好的解决方案。但这并不完全是总的游戏时间。

更新: 对于存储数据,您可以根据需要使用持久性存储。现在,共享偏好看起来是一个不错的选择。

存储数据

    SharedPreferences myPrefs = mContext.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
    SharedPreferences.Editor prefsEditor = myPrefs.edit();
    prefsEditor.putLong("time", value);
    prefsEditor.commit();

检索数据

SharedPreferences sharedPref = mContext.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
return sharedPref.getLong("time", 0);
于 2013-04-24T17:14:36.930 回答
0

正如 Lukas 所说,扩展 Application 会很好。

您还可以使用存储计时器启动时间的首选项...

但我认为,使用计时器开始时间听起来是最好的方法。

于 2013-04-24T17:09:09.373 回答