Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a background thread

I'm currently working toward a mobile android application. The main thing that this app will have trouble with for load times is a Webservice json string that at this current stage is taking too long to load and sometimes causing the app to force close (stalling for too long).

Splash -> MainActivity -> HomeActivity This is how our application starts.

First we display a Splash, and behind that we run the MainActivity, which consists of the following code:

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);

    }

}

The problem I am running into is the app will stick on the Splash page and the Application output will tell me that I am running too much on the Main thread.

What is a way to separate the download request to work in the background?

like image 475
Klutch Avatar asked Jun 14 '26 10:06

Klutch


2 Answers

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

        }

    }

and to run it

new myTask().execute();
like image 115
Broak Avatar answered Jun 16 '26 02:06

Broak


Yes there is, you need to use AsyncTask, this should help too.

like image 21
aehs29 Avatar answered Jun 16 '26 02:06

aehs29



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!