![](/img/trans.png)
[英]Android Activity::onCreate called before Application.onCreate
[英]Is Application.onCreate called before Activity.onResume if app has been idle for hours and destroyed by OS?
在我的Application onCreate中,我以如下方式實例化Retrofit:
public class MyApplication extends Application {
@Override
public void onCreate() {
RestClient.setupRestClient(getAppVersion(this));
}
}
我曾經在RestClient中有一個靜態塊來對其進行初始化,但是現在我需要為每個請求在Headers中添加應用程序版本,因此我需要在初始化時傳遞String。 (getAppVersion()需要上下文來獲取應用程序版本)
如果尚未初始化,我在RestClient.get()中添加了throw子句。
我的問題是,通常,如果一個Activity閑置數小時,操作系統會殺死它,有時在長時間閑置后恢復活動時,它在onResume中尋找的某些內容為null並崩潰,因此在onResume之前調用Application.onCreate ,活動是否事先被殺死?
這是我的RestClient類
public class RestClient {
private static API REST_CLIENT;
private RestClient() {
}
public static API get() {
if(REST_CLIENT==null){
throw new IllegalStateException("Rest Client not initialized");
}
return REST_CLIENT;
}
public static void setupRestClient(final String appVersion) {
Gson gson = new GsonBuilder()
.registerTypeAdapter(Story.class, new StorySerializer())
.create();
RequestInterceptor requestInterceptor = new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) {
request.addHeader(ServerKeys.HEADER_OS_VERSION, ServerKeys.HEADER_OS_VERSION_VALUE_ANDROID);
request.addHeader(ServerKeys.HEADER_APP_VERSION, appVersion);
}
};
RestAdapter.Builder builder = new RestAdapter.Builder();
builder.setEndpoint(APIKeys.API_ROOT);
builder.setRequestInterceptor(requestInterceptor);
builder.setExecutors(Executors.newFixedThreadPool(Preferences.MAX_NUMBER_OF_PARALLEL_NETWORK_OPERATIONS), new ScheduledThreadPoolExecutor(Preferences.MAX_NUMBER_OF_PARALLEL_NETWORK_OPERATIONS));
builder.setConverter(new GsonConverter(gson));
RestAdapter restAdapter = builder.build();
REST_CLIENT = restAdapter.create(API.class);
}
}
這就是我的用法:
RestClient.get().resetUserPassword(ge....
如果您的活動被殺死,則接下來將對該活動調用onCreate。 據我所知,該應用程序的onCreate()僅被調用一次。
這樣的例子:我啟動了我的應用程序,並且改變了方向,僅針對該Activity調用onDestroy和onCreate。 該應用程序從未重啟。
因此,現在回答您的問題,因為我已經仔細閱讀了,所以我認為不會。 除非關閉了整個應用程序,否則沒有理由再次調用該應用程序的onCreate()。
正如塞爾文在評論中說的那樣,對這個問題的直接回答是“是”。 但是,我的整個案例都是無效的,因為有一種更輕松的方法可以解決我遇到的問題,而無需將上下文傳遞給Retrofit,方法如下:
String verName = BuildConfig.VERSION_NAME;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.