Klu*_*tch 2 c# multithreading android json
我目前正致力于移动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);
}
}
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是应用程序将停留在Splash页面上,应用程序输出将告诉我我在主线程上运行太多.
有什么方法可以将下载请求分离到后台运行?
private class myTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
}
@Override
protected Void doInBackground(Void... params) {
// Runs on the background thread
return null;
}
@Override
protected void onPostExecute(Void res) {
}
}
Run Code Online (Sandbox Code Playgroud)
并运行它
new myTask().execute();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
258 次 |
| 最近记录: |