如何创建后台线程

时间:2013-07-17 20:15:28

标签: c# android json multithreading

我目前正致力于移动Android应用程序。这个应用程序在加载时遇到问题的主要原因是Webservice json字符串,在当前阶段加载时间太长,有时会导致应用程序强制关闭(停止时间过长)。

启动 - > 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页面上,而Application输出会告诉我我在主线程上运行的太多了。

有什么方法可以将下载请求分开,以便在后台运行?

3 个答案:

答案 0 :(得分: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();

答案 1 :(得分:3)

是的,您需要使用AsyncTaskthis也应该有所帮助。

答案 2 :(得分: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());
}