我有一个Android应用程序,它依赖于很多后台服务。我在服务中通过JNI从C++获取一些值,并将这些值设置为一些静态变量。静态变量设置为删除Android应用程序的默认值
据我的理解,即使应用程序被删除,因为服务始终保持在后台,所以值应该保留在这些变量中。但不知何故,当应用程序被删除或杀死,静态变量重置为默认值,而不是有新的分配值。
任何机构都可以解释Android中后台服务中静态变量的行为。谢谢。这里是代码
public class ServiceData extends Service{
public static void setUser_id(int id) {
user_id = id;
}
public static void setUserData_id(int id) {
user_data_id = id;
}
protected static int user_id = -1;
protected static int user_data_id = -1;
@Override public void onCreate() {
super.onCreate();
context = getApplicationContext();
running = true;
Log.d(TAG, "in onCreate");
Toast.makeText(context,"in onCreate", Toast.LENGTH_SHORT).show();
}
@Override public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "in onStartCommand");
Toast.makeText(context,"in onStartCommand", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
@Override public IBinder onBind(Intent intent) {
Log.d(TAG, "in onBind");
Toast.makeText(context,"in onBind", Toast.LENGTH_SHORT).show();
return messenger.getBinder();
}
@Override public boolean onUnbind(Intent intent) {
Log.d(TAG, "in onUnbind");
Toast.makeText(context,"in onUnBind", Toast.LENGTH_SHORT).show();
return super.onUnbind(intent);
//return true;
}
@Override public void onRebind(Intent intent) {
Log.d(TAG, "in onRebind");
Toast.makeText(context,"in onRebind", Toast.LENGTH_SHORT).show();
super.onRebind(intent);
}
@Override public void onDestroy() {
super.onDestroy();
Log.d(TAG, "in onDestrory");
Toast.makeText(context,"in onDestroy", Toast.LENGTH_SHORT).show();
this.manager.cancel(R.string.service_started);
running = false;
}
您应该使用SharedPreferences而不是静态变量。 –
是的,但我不想使用sharedPreference ...我想这也应该工作... –
是的,但有些时候应用程序崩溃的静态变量设置为默认值。 –