2

我目前正在开发一个移动 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 页面上,应用程序输出会告诉我我在主线程上运行太多。

有什么方法可以将下载请求分开在后台工作?

4

3 回答 3

6
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) {

        }

    }

并运行它

new myTask().execute();
于 2013-07-17T20:19:26.183 回答
3

是的,你需要使用AsyncTask也应该有帮助。

于 2013-07-17T20:18:03.497 回答
0

如果您使用的 .Net/Mono 版本支持async/await,那么您可以简单地执行

async void DisplayNews()
{
    string url = "http://rapstation.com/webservice.php";

    HttpClient client = new HttpClient();
    string content = await client.GetStringAsync(url);
    NewsObject[] news = JsonConvert.DeserializeObject<NewsObject[]>(content);
    //!! Your code to add news to some control
}

如果不是,那么您可以使用Task

void DisplayNews2()
{
    string url = "http://rapstation.com/webservice.php";

    Task.Factory.StartNew(() =>
        {
            using (var client = new WebClient())
            {
                string content = client.DownloadString(url);
                return JsonConvert.DeserializeObject<NewsObject[]>(content);
            }
        })
    .ContinueWith((task,y) =>
        {
            NewsObject[] news = task.Result;
            //!! Your code to add news to some control
        },null,TaskScheduler.FromCurrentSynchronizationContext());
}
于 2013-07-18T09:13:22.673 回答