生命周期
安卓应用的生命周期
在安卓的一个Activity启动,关闭的过程中,需要有经过一些重要的生命周期函数。
* onCreate: 生成安卓的一个Activity
* onStart: 将一个Activity变成一个可以显示的Activity。
* onResume: 在一个Activity被放置到当前Android页面的最上面,可以让用户进行操作的时候进行调用。
* onPause: 一个Activity退出当前Android最前的界面调用该函数。
* onStop: 一个Activity不再可见,在后台进行运行,停止UI的更新。
* onDestroy:Android系统回收系统资源,调用此函数完成最后的任务(保存数据)。
保存用户的数据
应用可以将数据保存在Bundle(一种保存在内存中的key-value结构)中,在onCreate函数中,可以在bundle中获取相应key值。
protected void onSaveInstanceState(Bundle outState) {
// COMPLETED (3) Call super.onSaveInstanceState
super.onSaveInstanceState(outState);
// COMPLETED (5) Put the text from the TextView in the outState bundle
String lifecycleDisplayTextViewContents = mLifecycleDisplay.getText().toString();
outState.putString(LIFECYCLE_CALLBACKS_TEXT_KEY, lifecycleDisplayTextViewContents);
}
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(LIFECYCLE_CALLBACKS_TEXT_KEY)) {
String allPreviousLifecycleCallbacks = savedInstanceState
.getString(LIFECYCLE_CALLBACKS_TEXT_KEY);
mLifecycleDisplay.setText(allPreviousLifecycleCallbacks);
}
}
AsyncTaskLoader
- 将结果告知当前的Activity
- 防止后台程序出现重复
- 帮助消除重复的僵尸Activity
初始化AsyncTaskLoader
getSupportLoaderManager().initLoader(GITHUB_SEARCH_LOADER, null, this);
通过bundle将数据传递给AsyncTask
Bundle queryBundle = new Bundle();
queryBundle.putString(SEARCH_QUERY_URL_EXTRA, githubSearchUrl.toString());
/*
* Now that we've created our bundle that we will pass to our Loader, we need to decide
* if we should restart the loader (if the loader already existed) or if we need to
* initialize the loader (if the loader did NOT already exist).
*
* We do this by first store the support loader manager in the variable loaderManager.
* All things related to the Loader go through through the LoaderManager. Once we have a
* hold on the support loader manager, (loaderManager) we can attempt to access our
* githubSearchLoader. To do this, we use LoaderManager's method, "getLoader", and pass in
* the ID we assigned in its creation. You can think of this process similar to finding a
* View by ID. We give the LoaderManager an ID and it returns a loader (if one exists). If
* one doesn't exist, we tell the LoaderManager to create one. If one does exist, we tell
* the LoaderManager to restart it.
*/
LoaderManager loaderManager = getSupportLoaderManager();
Loader<String> githubSearchLoader = loaderManager.getLoader(GITHUB_SEARCH_LOADER);
if (githubSearchLoader == null) {
loaderManager.initLoader(GITHUB_SEARCH_LOADER, queryBundle, this);
} else {
loaderManager.restartLoader(GITHUB_SEARCH_LOADER, queryBundle, this);
}
初始化AsyncLoader
重写onCreateLoader
方法,方法的参数为:id(int)
:当前AsyncTask的ID,args(Bundle)
:key/value对。返回一个AsyncTaskLoader作为当前Activity创建AsyncTask的入口。在这里,需要实现3个函数:
1. onStartLoading
: 主线程做准备工作。
2. loadInBackground
: 后台线程的工作(网络访问)。
3. deliverResult
(Optional): 有时我们不需要向调用任务,而是直接使用之前保存的结果。
return new AsyncTaskLoader<String>(this) {
// COMPLETED (1) Create a String member variable called mGithubJson that will store the raw JSON
/* This String will contain the raw JSON from the results of our Github search */
String mGithubJson;
@Override
protected void onStartLoading() {
/* If no arguments were passed, we don't have a query to perform. Simply return. */
if (args == null) {
return;
}
/*
* When we initially begin loading in the background, we want to display the
* loading indicator to the user
*/
mLoadingIndicator.setVisibility(View.VISIBLE);
// COMPLETED (2) If mGithubJson is not null, deliver that result. Otherwise, force a load
/*
* If we already have cached results, just deliver them now. If we don't have any
* cached results, force a load.
*/
if (mGithubJson != null) {
deliverResult(mGithubJson);
} else {
forceLoad();
}
}
@Override
public String loadInBackground() {
/* Extract the search query from the args using our constant */
String searchQueryUrlString = args.getString(SEARCH_QUERY_URL_EXTRA);
/* If the user didn't enter anything, there's nothing to search for */
if (searchQueryUrlString == null || TextUtils.isEmpty(searchQueryUrlString)) {
return null;
}
/* Parse the URL from the passed in String and perform the search */
try {
URL githubUrl = new URL(searchQueryUrlString);
String githubSearchResults = NetworkUtils.getResponseFromHttpUrl(githubUrl);
return githubSearchResults;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
// COMPLETED (3) Override deliverResult and store the data in mGithubJson
// COMPLETED (4) Call super.deliverResult after storing the data
@Override
public void deliverResult(String githubJson) {
mGithubJson = githubJson;
super.deliverResult(githubJson);
}
};
AsyncTask返回
在AsyncTask执行完成后,调用onLoadFinished
函数完成之后的工作,如修改UI。
@Override
public void onLoadFinished(Loader<String> loader, String data) {
/* When we finish loading, we want to hide the loading indicator from the user. */
mLoadingIndicator.setVisibility(View.INVISIBLE);
/*
* If the results are null, we assume an error has occurred. There are much more robust
* methods for checking errors, but we wanted to keep this particular example simple.
*/
if (null == data) {
showErrorMessage();
} else {
mSearchResultsTextView.setText(data);
showJsonDataView();
}
}