Friday, April 13, 2018

Android Splash Screen (Part-3)

This is the last scenario for using the spalsh screen in a different way without creating any layout for it to display when the app starts. Here we are going to set a permission dialog that will ask for some permissions in the app and it will be asked at the time of app loading means in the spalsh screen.


There are 3 steps to perform in order to create this kind of splash screen without any layout for the screen.
1.) You have to define one style in the values folder of your app. Create the following style in your
app.
<style name="splashScreenTheme" parent="Theme.AppCompat.NoActionBar">
        <item name="android:windowBackground">@drawable/splash_screen</item>
        <item name="windowActionModeOverlay">true</item>
</style>
Here you have to set a android:windowBackground with image of the splash screen that will cover the whole screen with the logo and color in the splash screen.
2.) After doing this, you have to apply this style to your screen in AndroidManifest.xml. Add the following code in the manifest file inside the application tag.
<activity
    android:name="com.android.splashscreendemo.activity.SplashActivity"
    android:label="@string/app_name"
    android:launchMode="singleTask"
    android:screenOrientation="portrait"
    android:theme="@style/splashScreenTheme">
    <intent-filter>
          <action android:name="android.intent.action.MAIN" />
          <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
Now, we will modify the SplashActivity.java to add the permission dialog to show at startup of the app and then the app will redirect the user to MainActivity.java after all the permissions are given by the user.
3.) Add the following code in your SplashActivity.java.
package com.android.splashscreendemo.activity;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.android.splashscreendemo.MyApp;
import com.android.splashscreendemo.R;
import com.android.splashscreendemo.UIElementHelper.TypeFaceHelper;
import com.android.splashscreendemo.model.Constants;
import com.android.splashscreendemo.service.PlayerService;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;

/**
 * Created by Parth Vora on 1/29/2017.
 */

@SuppressWarnings("DefaultFileTemplate")
public class SplashActivity extends AppCompatActivity {
    
    private static String[] PERMISSIONS = {Manifest.permission.READ_PHONE_STATE, 
        Manifest.permission.WRITE_EXTERNAL_STORAGE};
    final private int MY_PERMISSIONS_REQUEST = 0;
    private boolean mBound = false;

    private ServiceConnection serviceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName arg0, IBinder service) {
            mBound = true;
            Log.v(Constants.TAG, "LAUNCH MAIN ACTIVITY");
            startActivity(new Intent(ActivityPermissionSeek.this, ActivityMain.class));
            finish();
        }
        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            mBound = false;
        }
    };

    public static boolean hasPermissions(Context context, String... permissions) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //check version and make changes if any
        if (!hasPermissions(this, PERMISSIONS)) {
            try {
                permissionDetailsDialog();
            } catch (Exception e) {
                RequestPermission();
            }
        } else {
            bindService();
        }
   }

    private void permissionDetailsDialog() {
        new MaterialDialog.Builder(this)
            .typeface(TypeFaceHelper.getTypeFace(this), TypeFaceHelper.getTypeFace(this))
            .title(R.string.permission_details_title)
            .content(R.string.permission_details_content)
            .positiveText(R.string.permission_details_pos)
            .negativeText(getString(R.string.cancel))
            .cancelable(false)
            .onPositive(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    RequestPermission();
                }
            })
            .onNegative(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    finish();
                }
            })
            .show();
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
    }

    private void RequestPermission() {
        // Here, thisActivity is the current activity
        ActivityCompat.requestPermissions(this,
            PERMISSIONS,
           MY_PERMISSIONS_REQUEST);
    }

    private void bindService() {
        // Whatever the background service you want to bind to according to your app.
        startService(new Intent(this, PlayerService.class));
        try {
            Intent playerServiceIntent = new Intent(this, PlayerService.class);
            bindService(playerServiceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
        } catch (Exception ignored) {
            ignored.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            if (mBound) {
                unbindService(serviceConnection);
                mBound = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, 
            @NonNull String permissions[], @NonNull int[] grantResults) {

        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST: {
                if (grantResults.length == 0) {
                    return;
                }
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED
                        && grantResults[1] == PackageManager.PERMISSION_GRANTED
                        ) {
                    bindService();
                } else {
                    if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
                        //READ PHONE STATE DENIED
                        Intent intent = new Intent(Intent.ACTION_MAIN);
                        intent.addCategory(Intent.CATEGORY_HOME);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        Toast.makeText(this, getString(R.string.phone_stat_perm_required), Toast.LENGTH_LONG).show();
                        finish();
                    } else if (grantResults[1] == PackageManager.PERMISSION_DENIED) {
                        Intent intent = new Intent(Intent.ACTION_MAIN);
                        intent.addCategory(Intent.CATEGORY_HOME);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        Toast.makeText(this, getString(R.string.storage_perm_required), Toast.LENGTH_LONG).show();
                        finish();
                    }
                }
            }
            break;
        }
    }
}
This is the third scenario of how you can use splash screen in your app depending upon the structure and logic of your app.