可以根据应用程序的要求使用启动画面,例如:
1.下载数据并存储。2.解析json等
当您想为此在后台运行主要活动时,您应该使用 AsyncTask 或 Service:
例如
public class SplashScreen extends Activity {
String now_playing, earned;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
/**
* Showing splashscreen while making network calls to download necessary
* data before launching the app Will use AsyncTask to make http call
*/
new PrefetchData().execute();
}
/**
* Async Task to make http call
*/
private class PrefetchData extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// before making http calls
}
@Override
protected Void doInBackground(Void... arg0) {
/*
* Will make http call here This call will download required data
* before launching the app
* example:
* 1. Downloading and storing in SQLite
* 2. Downloading images
* 3. Fetching and parsing the xml / json
* 4. Sending device information to server
* 5. etc.,
*/
JsonParser jsonParser = new JsonParser();
String json = jsonParser
.getJSONFromUrl("http://api.androidhive.info/game/game_stats.json");
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jObj = new JSONObject(json)
.getJSONObject("game_stat");
now_playing = jObj.getString("now_playing");
earned = jObj.getString("earned");
Log.e("JSON", "> " + now_playing + earned);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// After completing http call
// will close this activity and lauch main activity
Intent i = new Intent(SplashScreen.this, MainActivity.class);//Here Main activity is the splash screen.
i.putExtra("now_playing", now_playing);
i.putExtra("earned", earned);
startActivity(i);
// close this activity
finish();
}
}
}
有关更多信息,您可以查看在启动画面、服务和AsyncTask中使用 asynctask 的示例。
如果我理解您的要求,那么您应该查看在启动画面中使用 asynctask 的示例,一次。
上述编码过程:
- onCreate setContentView(R.layout.activity_splash); 调用启动画面并调用PrefetchData()。
- 在prefetch()中,异步任务在这里执行后台操作,从给定的 url 解析一个 json。
- 在onPostExecute() MainActivity 被调用。提醒 onPostExecute() 在 AsyncTask 中用于表示后台处理已完成,因此在上面的示例中,finish() 函数结束时显示启动画面。
希望它可以帮助你。