當我的應用程序安裝並首次打開時(有互聯網連接時),我希望手機從我的服務器下載一些信息並將其插入到數據庫。如何在第一次啓動時執行Android應用程序時的操作
如果信息沒有完全下載或下載,這個活動應該發生,直到它完全下載?
我該如何去做這件事?
當我的應用程序安裝並首次打開時(有互聯網連接時),我希望手機從我的服務器下載一些信息並將其插入到數據庫。如何在第一次啓動時執行Android應用程序時的操作
如果信息沒有完全下載或下載,這個活動應該發生,直到它完全下載?
我該如何去做這件事?
爲此使用SharedPreference。創建一個布爾變量並在操作完成後進行更改。在主/啓動器活動的onCreate中檢查此變量並相應地執行操作。一些僞代碼。
if (!sharedpreferences.getBoolean("isOpComplete", false)) {
// perform my operation
performOperation();
}
performOperation() {
// Operation complete
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean("isOpComplete", true);
editor.commit();
}
使用偏好
在活動:
private boolean isFirstLaunch() {
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean isFirstLaunch = settings.getBoolean("isFirstLaunch", true);
Log.i(TAG + ".isFirstLaunch", "sharedPreferences ");
return isFirstLaunch;
}
,並從onCreate
通話
if (isFirstLaunch()) {
Intent firstLaunchIntent = new Intent(this,
GetStartedActivity.class);
firstLaunchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(firstLaunchIntent);
// set the bool to false in next activity !
finish();
}
添加標記在你的數據庫,共享偏好或文件表示你已經下載了數據。在onResume中,檢查該標誌以及設備是否具有連接性。如果標誌爲假並且您有連接性,請嘗試下載數據。
如果這樣做成功,更新標誌。
我想在第二種方法的末尾需要'commit()'。 – 2011-06-16 15:27:46