我在服务文件(backgroundService.java)中声明了一个静态Arraylist 变量。我收到推送消息(使用GCM)后,我正在更新静态变量。我正在使用4.0.4设备(三星S3)..静态变量变空,一旦我的应用程序进入后台,然后如果我长按memu按钮并刷我的应用程序(一旦我们刷了应用程序已完成但没有强制停止),服务暂停一段时间再次启动,即不调用服务onDestroy方法而是OnCreate方法在该暂停之后.. 在该暂停之后,静态ArrayList变为空。怎么解决?我不希望我的静态Arraylist失去价值..
仅在Android版本4.0+设备中出现此问题。
public class BackgroundService extends Service
{ private Timer timer = new Timer();
Context mContext;
String LOG_TAG=BackgroundService.class.getSimpleName();
ApplicationInfo ai;
private static boolean isRunning = false;
public static ArrayList<String> mDMPush=new ArrayList<String>();
@Override
public void onCreate()
{
super.onCreate();
Log.e(LOG_TAG,"on create ");
isRunning = true;
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.e(LOG_TAG,"mDMPush"+mDMPush);
Log.e(LOG_TAG,"mDMPush outside if else "+mDMPush.size()+" "+mDMPush.isEmpty());
startService();
}
public static boolean isRunning()
{
return isRunning;
}
private void startService()
{
int delay = 100;
int period =500;
final PackageManager pm = getPackageManager();
timer.scheduleAtFixedRate(new TimerTask() {
public void run()
{
ActivityManager am = (ActivityManager) mContext.getSystemService(Activity.ACTIVITY_SERVICE);
String packageName = am.getRunningTasks(1).get(0).topActivity.getPackageName();
try {
ai = pm.getApplicationInfo(packageName, 0);
if ((ai.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
**Iam doing an action inside this timer using that arraylist mDMPush.. I ll add value to the arraylist once i received a push***
}
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, delay, period);
}
答案 0 :(得分:0)
看起来您的应用程序进程被杀死并重新创建,这在Android上是正常的事情。您不应该依赖静态,将其保存到更多持久性存储,如首选项或db。
答案 1 :(得分:0)
您应该查看此页面以找到更好的方法来实现数组列表的存储Android Persistent Storage
答案 2 :(得分:0)
这是如何在持久存储中保存数组列表的
Set<String> localStore = new HashSet<String>();
List<String> list = new ArrayList<String>();
localStore.addAll(list);
SharedPreferences ssidPref = getSharedPreferences("ssidPref", Context.MODE_PRIVATE);
SharedPreferences.Editor EDITIOR = ssidPref.edit();
EDITIOR.putStringSet("ssidStored", localStore);
EDITIOR.commit();
阅读
localStore = ssidPref.getStringSet("ssidStored", null);