Tiếp theo bài viết hướng dẫn kết nối Android với MySQL, hôm nay chúng tôi sẽ hướng dẫn cách thiết kế màn hình splash trong Android. Màn hình splash trong Android thường được sử dụng để hiển thị tiến trình trước khi ứng dụng được nạp hoàn toàn và sẵn sàng để sử dụng. Một số trường hợp sử dụng màn hình splash

  1. Hiển thị thông tin về ứng dụng hoặc thông tin về công ty.
  2. Tải dữ liệu và lưu trữ vào SQLite
  3. Tải hình ảnh
  4. Tải và phân tích json / xml

Trong android không có bất kỳ cơ chế sẵn có để hiển thị màn hình splash so với iOS. Trong hướng dẫn này chúng ta sẽ tìm hiểu làm thế nào để tạo màn hình splash trong ứng dụng Android của bạn. Và để tạo màn hình splash chúng ta sẽ tạo 2 activity riêng biệt, một cho splash và khi màn hình splash đóng lại chúng ta sẽ khởi động màn hình activity kế tiếp

Các bước thực hiện

  • Sử dụng project hiện có hoặc tạo mới project với Android Studio
  • Tạo lớp ServiceHandler.java
public class ServiceHandler {
    static InputStream is = null;
    static String response = null;
    public final static int GET = 1;
    public final static int POST = 2;

    /**
     * Making service call
     *
     * @url - url to make request
     * @method - http request method
     */
    public String makeServiceCall(String url, int method) {
        return this.makeServiceCall(url, method, null);
    }

    /**
     * Making service call
     *
     * @url - url to make request
     * @method - http request method
     * @params - http request params
     */
    public String makeServiceCall(String url, int method, List<NameValuePair> params) {
        try {
            // http client
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;

            // Checking http request method type
            if (method == POST) {
                HttpPost httpPost = new HttpPost(url);
                // adding post params
                if (params != null) {
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
                }

                httpResponse = httpClient.execute(httpPost);

            } else if (method == GET) {
                // appending params to url
                if (params != null) {
                    String paramString = URLEncodedUtils.format(params, "utf-8");
                    url += "?" + paramString;
                }
                HttpGet httpGet = new HttpGet(url);

                httpResponse = httpClient.execute(httpGet);

            }
            httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            response = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error: " + e.toString());
        }

        return response;

    }
}
    • Tạo activity tên SplashScreenActivity (Chuột phải package -> chọn New -> chọn Activity -> chọn Empty Activity -> nhập tên activity tại Activity Name -> chọn Finish)

splash trong android

    • Thiết kế giao diện

splash trong android 4

    • Viết xử lý
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class SplashScreenActivity extends AppCompatActivity {

    TextView tvName, tvState;

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

        tvName = (TextView) findViewById(R.id.tvName);
        tvState = (TextView) findViewById(R.id.tvState);

        //Get data from other activity
        Intent i = getIntent();
        String name = i.getStringExtra("name");
        String state = i.getStringExtra("state");

        // Diplaying the text
        tvName.setText(name);
        tvState.setText(state);
    }
}
    • Tạo activity tên SplashScreen (Chuột phải package -> chọn New -> chọn Activity -> chọn Empty Activity -> nhập tên activity tại Activity Name -> chọn Finish)

splash trong android 2

    • Thiết kế giao diện

splash trong android 3

    • Viết xử lý
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;
import android.os.Handler;

public class SplashScreen extends AppCompatActivity {

    // Splash screen timer
    static int SPLASH_TIME_OUT = 3000;
    String name, state;

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

        /**
         * 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.,
             */
            ServiceHandler jsonParser = new ServiceHandler();
            String json = jsonParser.makeServiceCall("http://10.0.2.2:port/json/os.json", ServiceHandler.POST);

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

            if (json != null) {
                try {
                    JSONObject jObj = new JSONObject(json).getJSONObject("os");
                    name = jObj.getString("name");
                    state = jObj.getString("state");

                    Log.e("JSON", "> " + name + state);

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            new Handler().postDelayed(new Runnable() {

         /*
             * Showing splash screen with a timer. This will be useful when you
          * want to show case your app logo / company
          */

                @Override
                public void run() {
                    // After completing http call
                    // will close this activity and lauch main activity
                    Intent i = new Intent(SplashScreen.this, SplashScreenActivity.class);
                    i.putExtra("name", name);
                    i.putExtra("state", state);
                    startActivity(i);
                    // close this activity
                    finish();
                }
            }, SPLASH_TIME_OUT);
        }
    }
}
  • Tập tin json được truy cập thông qua mạng, trong bài viết này json được truy cập ở localhost. (Các bạn có thể xem hướng dẫn cài đặt webserver XAMPP nếu máy của các bạn chưa cài đặt XAMPP). Nội dung của tập tin os.json
{"os":{"name" : "Android","state" : "USA"}}

Một số lưu ý

  • Cấp quyền truy cập internet cho ứng dụng trong AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />

kết nối android với mysql

  • Khai báo thư viện org.apache.http.legacy trong tập tin build.gradle (Module: app)
useLibrary 'org.apache.http.legacy'

kết nối android với mysql

  • Chỉ định port của Apache đang sử dụng trên máy của bạn
String json = jsonParser.makeServiceCall("http://10.0.2.2:port/json/os.json", ServiceHandler.POST);

splash trong android 5

– Theo như hình thì đoạn code sẽ được chỉnh sửa như sau

String json = jsonParser.makeServiceCall("http://10.0.2.2:7777/json/os.js
Chia sẻ