Thursday, April 12, 2018

Android Splash Screen (Part-2)

Now, we will learn about the 2nd scenario of the prevoius post related to android splash screen using network calls (http). In splash screen activity in onCreate method we will call an AsyncTask method that will fetch required information by making http call. Once the http call terminates we launch main activity in onPostExecute() method.


Here, the first step is to add INTERNET permission in the manifest file as this app is going to use internet. Open your AndroidManifest.xml file and add INTERNET permission above <application> tag as follows:
<uses-permission android:name="android.permission.INTERNET"/>

Open your SplashActivity.java and add AsyncTask to make http calls. In this tutorial i am making an http call to get json and display it on the log in screen. After fetching the json, the data will be sent to MainActivity.java using Intents.
Following is the json i am going to fetch. You can access this json from 
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
Add the following code in your SplashActivity.java

SplashActivity.java

package com.android.splashscreendemo;

import com.android.splashscreendemo.R;
import com.android.splashscreendemo.network.JsonParser;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

public class SplashActivity extends Activity {

    String userId, title, body;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        /**
         * Showing splashscreen while making network calls to download necessary
         * data before launching the app Will use AsyncTask to make http call
         */
        new PrefetchData().execute();
    }

    /**
     * Async Task to make http call
     */
    private class PrefetchData extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // before making http calls         

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            /*
             * Will make http call here This call will download required data
             * before launching the app 
             * example: 
             * 1. Downloading and storing in SQLite 
             * 2. Downloading images 
             * 3. Fetching and parsing the xml / json 
             * 4. Sending device information to server 
             * 5. etc.,
             */
             JsonParser jsonParser = new JsonParser();
             String json = jsonParser.getJSONFromUrl("https://jsonplaceholder.typicode.com/posts/1");

            Log.e("Response: ", "> " + json);

            if (json != null) {
                try {
                    JSONObject jObj = new JSONObject(json);
                    userId = jObj.getJSONObject("userId");                    
                    title = jObj.getString("title");         
                    body = jObj.getString("body");
                    Log.e("JSON", "> " + userId + title + body);
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
           }
           return null;
       }

       @Override
       protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // After completing http call
            // will close this activity and lauch main activity
            Intent i = new Intent(SplashActivity.this, MainActivity.class);
            i.putExtra("userId", userId);         
            i.putExtra("title", title); 
            i.putExtra("body", body);
            startActivity(i);

            // close this activity
            finish();
        }
    }
}
In your MainActivity.java take appropriate action using parsed json data. I just displayed on log in screen.
MainActivity.java

package com.android.splashscreendemo;

import com.android.splashscreendemo.R;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends Activity {

    LinearLayout mUserDetailLayout;
    TextView mUserId, mTitle, mBody;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mUserDetailLayout = (LinearLayout) findViewById(R.id.user_detail_layout);        mUserId = (TextView) findViewById(R.id.user_id);
       mTitle = (TextView) findViewById(R.id.title);       mBody = (TextView) findViewById(R.id.body);
// layout background transparent mUserDetailLayout.getBackground().setAlpha(150); mUserDetailLayout.setVisibility(View.VISIBLE); Intent i = getIntent(); String userId = i.getStringExtra("userId"); String title = i.getStringExtra("title"); String body = i.getStringExtra("body"); // Diplaying the text mUserId.setText(userId); mTitle.setText(title); mBody.setText(body); } }


This is the second scenario using asynctask for making a network call to get http request data in json and displaying it in the example above. In actual case it is used to download this content or data and store it for offline or some other uses in your app. There is one more way you can use the splash screen using no layout at all. This will be explained in the next blog post so stay tuned.