您可以通过设置标志来更改通知中的 PendingIntent 以重用 Activity 的先前实例。
就像是:
Intent intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_CLEAR_TOP);
PendingIntent pending = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT
您还可以更改活动,以便在 onResume() 中加载 SharedPreferences,此方法在活动创建和恢复期间运行。
编辑:根据您关于丢失数据的评论,我为您提供以下附加代码。我在 AsyncTask 中使用此代码,并且在持久性方面没有任何问题。
public final class PreferenceUtils
{
private static final String TAG = PreferenceUtils.class.getSimpleName();
public static final String SESSION_ID = "sessionId"; //$NON-NLS-1$
public static final String NAME = "name"; //$NON-NLS-1$
private PreferenceUtils()
{
// enforcing singleton
super();
}
/**
* Set sessionId in app preferences to the supplied value.
*
* @param context
* @param sessionId
*/
public static void setSessionId(final Context context, final String sessionId)
{
final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
final Editor editor = settings.edit();
editor.putString(PreferenceUtils.SESSION_ID, sessionId);
editor.commit();
if (BuildConfig.DEBUG)
{
Log.d(PreferenceUtils.TAG, "Setting sessionId: " + sessionId); //$NON-NLS-1$
}
}
/**
* Get the current session id
*
* @param context
* @return session id or null on not activated
*/
public static String getSessionId(final Context context)
{
final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
return settings.getString(PreferenceUtils.SESSION_ID, null);
}
/**
* Get current name stored in the app preferences
*
* @param context
* @return
*/
public static String getName(final Context context)
{
final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
return settings.getString(PreferenceUtils.NAME, null);
}
/**
* Set name in app preferences to the supplied value.
*
* @param context
* @param name
*/
public static void setName(final Context context, final String name)
{
final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
final Editor editor = settings.edit();
editor.putString(PreferenceUtils.NAME, name);
editor.commit();
if (BuildConfig.DEBUG)
{
Log.d(PreferenceUtils.TAG, "Setting name: " + name); //$NON-NLS-1$
}
}
}