【发布时间】:2013-03-24 03:06:13
【问题描述】:
在我的应用程序中,我希望仅在应用程序启动时将字符串传递给服务器。
我已使用 SharedPreferences 来检查字符串是否已发送。
此代码在 MainActivity 的星号处运行
pref=getPreferences(MODE_PRIVATE);
Sent=pref.getString("ID_SENT", "");
if(Sent.equals(""))
{
SharedPreferences.Editor editor=pref.edit();
editor.putString("ID_SENT","NO");
editor.commit();
Sent=pref.getString("ID_SENT","");
}
现在在 AsyncTask 的 onPostExecute 中将字符串发送到服务器后,此代码用于将变量 ID_SENT 设置为 YES:
Sent=pref.getString("ID_SENT", "");
if(Sent.equals("NO"))
{
SharedPreferences.Editor editor=pref.edit();
editor.putString("ID_SENT","YES");
editor.commit();
}
现在的问题是,当我关闭应用程序并再次启动应用程序时,它不会将字符串发送到服务器,因为它发现 ID_SENT 设置为 YES。
那么有什么方法可以让我在 MainActivity 上按下后退按钮时将 ID_SENT 设置为 no?
编辑:
我将 MainActivity 的启动模式设置为 singleTop。所以现在只要我从另一个活动中按下主页按钮,活动就会恢复。并且不是每次都发送字符串,因为 MainActivity 只是恢复了。
【问题讨论】:
-
开始是什么意思?是否要在调用 onCreateonCreate 时发送?
标签: android android-activity sharedpreferences