我想每天进行一次活动。我找到了这样做的方法:
Calendar calendar = Calendar.getInstance();
int currentday = calendar.get(Calendar.DAY_OF_MONTH);
Log.d("Today",""+currentday);
SharedPreferences settings = getSharedPreferences("DAY", 0);
int lastday = settings.getInt("day", 0);
Log.d("Last day",""+lastday);
if(lastday==currentday){Toast.makeText(MainActivity.this,"Activity will run just once a day",Toast.LENGTH_SHORT).show();}
}
说今天的值是20, 最后一天如何从settings.getInt()获取它的值?
答案 0 :(得分:0)
以这种方式尝试先将日期存储到共享的偏好中。
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("day", 12);
editor.apply();
并获取如下数据..
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int day = prefs.getInt("day", 0); //0 is the default value.
答案 1 :(得分:0)
这是我在应用程序中用于存储和存储在名为AppPreferences的单独类中的内容。可能您可以修改和使用它,还可以记录值,以防您要检查并存储值。让我知道,如果我回答了您
public static final String PREFS_KEY = "example_key";
public static final String APP_PREFS = "example_prefs";
/**
* Returns the value stored
*
* @return String containing the value
*/
public static String getValueStored() {
SharedPreferences prefs = AppAplication.getContext().getSharedPreferences(APP_PREFS, Context.MODE_PRIVATE);
return prefs.getString(PREFS_KEY , "");
}
/**
* Sets the value
*
* @return true if the value was saved, false on failure
*/
public static boolean setValueToStore(final String url) {
SharedPreferences prefs = AppAplication.getContext().getSharedPreferences(APP_PREFS, Context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = prefs.edit();
prefsEditor.putString(PREFS_KEY , url);
return prefsEditor.commit();
}
答案 2 :(得分:-1)
以下是Java中的示例:
public class MainActivity extends AppCompatActivity {
public static final String TAG = "MainActivity";
public static final String PREF = "PREF";
public static final String KEY_DAY = "KEY_DAY";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences pref = getSharedPreferences(PREF, Context.MODE_PRIVATE);
// Set
pref.edit().putInt(KEY_DAY, 20).apply();
// Get
int lastDay = pref.getInt(KEY_DAY, 0);
Log.d(TAG, "lastDay: " + lastDay);
}
}