我有一個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 ...我想這也應該工作... –
是的,但有些時候應用程序崩潰的靜態變量設置爲默認值。 –