我目前正在开发一个移动 android 应用程序。该应用程序在加载时间方面遇到的主要问题是 Web 服务 json 字符串,在当前阶段加载时间过长,有时会导致应用程序强制关闭(停顿时间过长)。
Splash -> MainActivity -> HomeActivity 这就是我们的应用程序的启动方式。
首先我们显示一个 Splash,然后运行 MainActivity,它由以下代码组成:
public class HomeActivity : Activity
{
NewsObject[] news;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);
var request = HttpWebRequest.Create(string.Format(@"http://rapstation.com/webservice.php"));
request.ContentType = "application/json";
request.Method = "GET";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode);
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
var content = reader.ReadToEnd();
if(string.IsNullOrWhiteSpace(content)) {
Console.Out.WriteLine("Response contained empty body...");
Toast toast = Toast.MakeText (this, "No Connection to server, Application will now close", ToastLength.Short);
toast.Show ();
}
else {
news = JsonConvert.DeserializeObject<NewsObject[]>(content);
}
}
Console.Out.WriteLine ("Now: \r\n {0}", news[0].title);
}
var list = FindViewById<ListView> (Resource.Id.list);
list.Adapter = new HomeScreenAdapter (this, news);
list.ItemClick += OnListItemClick;
var Listen = FindViewById<Button> (Resource.Id.btnListen);
var Shows = FindViewById<Button> (Resource.Id.btnShows);
Listen.Click += (sender, e) => {
var second = new Intent (this, typeof(RadioActivity));
StartActivity (second);
};
Shows.Click += (sender, e) => {
var second = new Intent (this, typeof(ShowsActivity));
StartActivity (second);
};
}
protected void OnListItemClick(object sender, AdapterView.ItemClickEventArgs e)
{
var listView = sender as ListView;
var t = news[e.Position];
var second = new Intent (this, typeof(NewsActivity));
second.PutExtra ("newsTitle", t.title);
second.PutExtra ("newsBody", t.body);
second.PutExtra ("newsImage", t.image);
second.PutExtra ("newsCaption", t.caption);
StartActivity (second);
Console.WriteLine("Clicked on " + t.title);
}
}
我遇到的问题是应用程序会停留在 Splash 页面上,应用程序输出会告诉我我在主线程上运行太多。
有什么方法可以将下载请求分开在后台工作?