在Android应用中保持计数和保存

时间:2013-07-09 05:58:05

标签: android

我正在制作一个有不同活动的应用。每个活动都会计算屏幕被点击的次数。我想分别保存所有活动的总计数(意味着我点击活动1 10次,它应该保存10.下次我点击它5次,应用程序应该节省10 + 5 = 15活动1)

点击活动只需做一个简单的

count++;

如何轻松实现这一点? 我是Android开发新手 提前感谢你:))

2 个答案:

答案 0 :(得分:3)

您应该使用首选项将计数存储在持久状态中。如果你使用静态变量,当其他应用程序获得更高优先级时,后台活动可能会被破坏(例如,在恢复应用程序之前按下home并保留很长时间),当内存不足时,所有值都将被清除。

SharedPreferences countSettings = getSharedPreferences("count", 0);

// get current counts
int count = countSettings.getInt("counts",0);
count++;
final SharedPreferences.Editor edit = countSettings.edit();
edit.putInt("counts",count);
edit.commit();

答案 1 :(得分:0)

为根标记和

实施OnTouchListener
@Override
    public boolean onTouch(View v, MotionEvent touchevent) {
        count++;
        return true;
    }

在您的onDestroy方法中优先存储它。