user1195614
user1195614

Reputation: 385

How to run the code in the background of SplashScreen in Android

I'm working with one application which requires a background processing as follows.

Whenever i send the request to the URL i will get the output in JSON Format. In the JSON I have a boolean variable. If the boolean variable is true, again i need to send the request to the URL till i get the value of the boolean variable as false.

But in the foreground the SplashScreen should run along with the Progress Bar. How can i achieve this.

Any Suggestions?

Upvotes: 1

Views: 357

Answers (3)

Simon Dorociak
Simon Dorociak

Reputation: 33505

Use AsyncTask, this is very strong tool but maybe more complicated like others techniques... AsynchTask use generic types. Has one method that you have to implement.

protected T doInBackground(T... params) {
   // body of your method
}

and others methods. Usually

protected T doInBackground {}
protected void onProgressUpdate(T... params)
protected void onPostExecute(T param)

First T serve for some input data. in your case, it can be your URL for example. This method (doInBackground) is running on background thread how colleagues above me wrote and they wrote probably everything. So little similar example how it can look:

private class DownloadAsyncTask extends AsyncTask<String, DataTransmitted, InputStream> {
      protected InputStream doInBackground(String... params) {

            int contentLength = 0;
            int buffLength = 0;
            int progress = 0;
            InputStream inputStream = null;
            try {

                URL url = new URL(params[0]);
                HttpURLConnection urlConntection = (HttpURLConnection) url.openConnection();
                urlConntection.setRequestMethod("GET");
                urlConntection.setAllowUserInteraction(false);
                urlConntection.setInstanceFollowRedirects(true);
                urlConntection.connect();
                if (urlConntection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    contentLength = urlConntection.getContentLength();
                    progressDialog.setMax(contentLength);
                    inputStream = urlConntection.getInputStream();

                    while ((buffLength = inputStream.read(MAX_BUFFER)) != -1) {
                        try {
                            Thread.sleep(1);
                            progress += buffLength;
                            DataTransmitted data = new DataTransmitted(progress, contentLength);
                            publishProgress(data);
                        }
                        catch (InterruptedException ex) {
                            Log.e(this.getClass().getName(), ex.getMessage());
                        }
                    }

                }
                else {
                    throw new IOException("No response.");
                }

            }
            catch (MalformedURLException ex) {
                Log.e(this.getClass().getName(), ex.getMessage());
            }
            catch (IOException ex) {
                Log.e(this.getClass().getName(), ex.getMessage());
            }
            return inputStream;
        }

      @Override
        protected void onProgressUpdate(DataTransmitted... data) {

            progressDialog.setProgress(data[0].getProgress());
            progressDialog.setMessage(data[0].getProgress() + " bytes downloaded.");
            data[0] = null;
        }


        @Override
        protected void onPostExecute(InputStream inStream) {
            progressDialog.dismiss();
            progressDialog.setProgress(0);
            DownloadedStream.inputStream = inStream;
            DownloadedStream.test = "Toto je len test...";
            Thread.currentThread().interrupt();
            downloadTask = null;
            new AlertDialog.Builder(DownloadPictureActivity.this)
                .setTitle("Download finished")
                .setMessage("Picture was downloaded correctly.")
                .setPositiveButton("Zobraziť", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dlg, int whichButton) {
                        // body of method

                    }
                })
                .setNegativeButton("Zavrieť", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dlg, int whichButton) {
                     //body of method   
                    } 
                })
                .show();
        }
}

hope it helps!

Upvotes: 1

Vishnu Haridas
Vishnu Haridas

Reputation: 7517

You can use AsyncTask<> to achieve this. You can learn more at : http://www.vogella.com/articles/AndroidPerformance/article.html

The flow of your idea can be like this:

  1. start splash activity with a progress bar.
  2. Inside onCreate() start your AsyncTask to fetch JSON, and update the progressbar in onProgressUpdate() function of your AsyncTask.
    • When AsyncTask completed [ onPostExecute(..) ], call a function to parse the JSON, and check true / false values
    • if true then repeat the task again.
    • if false then stop the AsyncTask.
  3. Now your URL fetching task is completed, and you can move to your next activity.

You can make use of a customized ProgressDialog also.

Upvotes: 1

blessanm86
blessanm86

Reputation: 31779

Use an aynctask or a separate thread to fetch data on the server while the progress bar runs on the ui thread.

Upvotes: 1

Related Questions