In my app I want to use a theme which is defined in the framework-res.apk. I decompiled an other which uses this theme and I found this in the styles.xml
<style name="DefaultSettingsTheme" parent="#com.sonyericsson.uxp:style/SEMCTheme">
<item name="android:directionality">leftToRight</item>
</style>
If I try to use this in my app it comes to an error because eclipse does not know that this theme is aviable in an other apk. How can I use this theme without rebuilding it?
I haven't tested this, but hope it works:
public class MyActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String packageName = ""; // package name of the app of which you want to access the resources;
String resourceName = ""; // name of the resource you want to access
int theme = 0;
theme = getResources().getIdentifier(resourceName, "style", packageName);
if (theme != 0) {
setTheme(theme);
}
setContentView(R.layout.main);
}
}
Related
let's suppose that customer A wants his app to be blue, while user B wants his app to be red, both app, are the same in execution, except for the colors and image logos. So, to change the app's colors based on customer login would be a violation of googles terms ?
Make in values folder a themes.xml file (like styles.xml)
There you can define 2 or more themes with colors that can you set later in your app for some type of user:
<resources>
<style name="AppTheme.White" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">#color/white</item>
...
</style>
<style name="AppTheme.Black" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">#color/black</item>
...
</style>
</resources>
Set in your AndroidManifest.xml your theme in each activity that should be affected:
...
<activity android:name="com.example.YourApp.MainActivity"
...
android:theme="#style/AppTheme.White"/>
...
Make a class for saving the states, called Utility.class:
public class Utility {
public static void setTheme(Context context, int theme) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
prefs.edit().putInt(context.getString(R.string.prefs_theme_key), theme).apply();
}
public static int getTheme(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
return prefs.getInt(context.getString(R.string.prefs_theme_key), 1);
}
}
And in your TargetActivity.class you will set the method to apply the states with your specific user type:
public void updateTheme() {
if (Utility.getTheme(getApplicationContext()) <= 1) {
setTheme(R.style.AppTheme_White);
} else if (Utility.getTheme(getApplicationContext()) == 2) {
setTheme(R.style.AppTheme_Black);
}
}
To set the saved theme at start of the app just type that into your MainActivity.class:
private final static int THEME_WHITE = 1;
private final static int THEME_BLACK = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
updateTheme();
}
public void updateTheme() {
if (Utility.getTheme(getApplicationContext()) <= THEME_WHITE) {
setTheme(R.style.AppTheme_White);
} else if (Utility.getTheme(getApplicationContext()) == THEME_BLACK) {
setTheme(R.style.AppTheme_Black);
}
}
That's how you work with different Themes. I think your question is answered by now :)
PS: Setting different colors for users isn't a violation against the terms of google. Google itself gave each letter a different color. ;)
I know this question was asked few times. but I cant find the problem in my case.
I want to change the theme of the app but my colorPrimary ,colorAccent and etc.. aren't changing.
my MainActivity extends BasicActivity. it looks like this:
public class MainActivity extends BasicActivity {
public static String MY_PREFS = "MY_PREFS";
private SharedPreferences mySharedPreferences;
int prefMode = Activity.MODE_PRIVATE;
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private ViewPagerAdapter adapter;
private TextView tabOne, tabTwo, tabThree;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
this is my BasicActivity(in this case I made it even simpler to show that the theme is taken from R.style):
public class BasicActivity extends AppCompatActivity {
public static String MY_PREFS = "MY_PREFS";
int prefMode = Activity.MODE_PRIVATE;
protected void onCreate(Bundle savedInstanceState) {
JsonParser parser = new JsonParser(getApplicationContext());
int resourceId = this.getResources().getIdentifier(parser.getThemeID(), "style", this.getPackageName());
setTheme(R.style.c_2ecc71_BC6C2B);
if (android.os.Build.VERSION.SDK_INT >= 19) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
super.onCreate(savedInstanceState);
}
}
and my XML:
<style name="c_2ecc71_BC6C2B" parent="#style/Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#2ecc71</item>
<item name="colorPrimaryDark">#1ebc61</item>
<item name="colorAccent">#BC6C2B</item>
</style>
According to the previous questions this code should work but in my case the views that have colorPrimary in their XML still loading the old theme's colors insted of the new one even though i set the theme before calling setContentView(R.layout.activity_main);
Thanks!
If you use Fragments, they will ignore the value you have set in the onCreate(), if you override the getTheme() method, it will be used within fragments as well:
Answered on different question: Change Activity's theme programmatically
#Override
public Resources.Theme getTheme() {
Resources.Theme theme = super.getTheme();
theme.applyStyle(R.style.c_2ecc71_BC6C2B, true);
return theme;
}
Use it in your MainActivity or your BasicActivity depending on where you want it to apply. You will NOT need to change it in the onCreate anymore.
You are trying to extend one of the newer themes of Android (above API 21). In addition to all the answers above , you can put your theme in styles.xml(v21).
More info here https://developer.android.com/training/material/compatibility.html
Not sure if you really want to set it programmatically, but you might try this: How to setTheme to an activity at runtime? It doesn't work call setTheme before onCreate and setContentView
If you're looking to set it for the whole application, it might be easier/cleaner to set it in the AndroidManifest.xml file instead.
<application android:theme="#style/CustomTheme">
Also, I'd highly avoid using a style name that has the values in it. The point of using a style is to avoid hard coding the values and allowing them to be configurable and reusable. What if you want to change the colorPrimary, are you also going to change your style name?
To set theme at runtime you can use following line of code :
setTheme(android.R.style.Theme_Name);
and write it before calling setContentView() and super.onCreate() method inside onCreate() method.
If you want to change that kind of stuff during runtime, you must insert all those "setTheme(android.R.style.Theme_Name);" methods inside runonUiThread, like this:
public class BasicActivity extends AppCompatActivity {
public static String MY_PREFS = "MY_PREFS";
int prefMode = Activity.MODE_PRIVATE;
protected void onCreate(Bundle savedInstanceState) {
JsonParser parser = new JsonParser(getApplicationContext());
int resourceId = this.getResources().getIdentifier(parser.getThemeID(), "style", this.getPackageName());
runOnUiThread(new Runnable() {
#Override
public void run() {
setTheme(R.style.c_2ecc71_BC6C2B);
}
});
recreate();
if (android.os.Build.VERSION.SDK_INT >= 19) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
super.onCreate(savedInstanceState);
}
}
and call recreate() after!
According to Android -
void recreate ()
Cause this Activity to be recreated with a new instance. This results in essentially the same flow as when the Activity is created due to a configuration change -- the current instance will go through its lifecycle to onDestroy() and a new instance then created after it.
Just modify your BasicActivity and MainActivity as shown in below and create appropriate theme. You can use shared preference for checking theme state during app up.
BasicActivity .java
public abstract class BasicActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
if (getLayoutID() != 0) {
setContentView(getLayoutID());
}
} catch (Exception ex) { /* ... */ }
final boolean THEME_DARK = true;// read appropriate value from SP or any other storage
Toolbar toolbar;
if ((toolbar = getToolbar()) != null) {
if (THEME_DARK/* check theme type here*/) {
toolbar.setPopupTheme(R.style.c_2ecc71_BC6C2B);
}
try {
setSupportActionBar(toolbar);
} catch (NoClassDefFoundError e) {
// Toast
finish();
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(getResources().getColor(R.color.colorPrimary));
}
}
public abstract Toolbar getToolbar();
public abstract int getLayoutID();
}
MainActivity.java
public class MainActivity extends BasicActivity {
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public Toolbar getToolbar() {
return toolbar == null ? toolbar = (Toolbar) findViewById(R.id.toolbar) : toolbar;
}
#Override
public int getLayoutID() {
return R.layout.activity_main;
}
}
You have hard-coded the theme in BaseActivity , rather than getting targetted resource id.
You need to put setTheme(value_from_resourceId);
Currently the BaseActivity always calls irrespective of value that you parsed
setTheme(R.style.c_2ecc71_BC6C2B);
than referring the runtime value
I have a apps named: preference, and i want to make themes for this apps. My AndroidManifest.xml of preference is:
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.preference.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
And in the MainActivity.java: I received theme change button click by:
themeChange = (Button) findViewById(R.id.themeChange);
themeChange.setOnClickListener(this);
I have a theme application which has PinkTheme (styles.xml) and the package name is com.example.theme.
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="AppBaseTheme" parent="android:Theme.Light">
<!--
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
-->
</style>
<style name="PinkTheme" parent="AppBaseTheme" >
<item name="android:textColor">#FF69B4</item>
<item name="android:typeface">monospace</item>
<item name="android:textSize">40sp</item>
<item name="android:windowBackground">#008000</item>
</style>
</resources>
And the onClick() of my preference is:
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.themeChange:
Resources res = null;
try {
res = getPackageManager().getResourcesForApplication("com.example.theme");
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(null != res) {
int sId = res.getIdentifier("com.example.theme:style/PinkTheme", null, null);
Theme themeObject = res.newTheme(); // theme object
themeObject.applyStyle(sId, true); // Place new attribute values into the theme
getTheme().setTo(themeObject);
}
break;
default:
break;
}
}
I have received theme Object of the theme package and try to setTheme of the preference application. But its not working. Please help me that: how to set theme from others application to my current application programmatically.
If you want to change settings in one application from another, then probably the easiest way to do it is to put a theme ID into an intent and send that intent to your MainActivity (or to an IntentService) where the receiving app can process the data. For example when the intent arrives, you can process it like you do a click event in your "onClick" logic.
For example, an app can create an intent like this:
Intent intent = new Intent("android.intent.action.MAIN");
intent.setComponent(new ComponentName("your.package", "your.package.component"));
intent.putExtra("theme_id", "theme_1");
startActivity(intent);
Then in your activity, use getIntent().getStringExtra("theme_id") to get the data passed to your app.
You would need to use the application's resources to load the theme. I have answered this in another thread here: https://stackoverflow.com/a/41948943/1048340
Here is an example where the package "com.example.theme" is installed and we use the app's resources and theme style in another app:
public class MainActivity extends AppCompatActivity {
Resources resources;
#Override protected void onCreate(Bundle savedInstanceState) {
int themeResId = getResources().getIdentifier("AppTheme", "style", "com.example.theme");
if (themeResId != 0) {
setTheme(themeResId);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override public Resources getResources() {
if (resources == null) {
try {
resources = getPackageManager().getResourcesForApplication("com.example.theme");
} catch (PackageManager.NameNotFoundException e) {
resources = super.getResources();
}
}
return resources;
}
}
See here for a working project on GitHub.
This can lead to problems because all layouts, drawables, strings, etc. will be loaded from the other application's resources. Therefore, you should avoid using a theme from another package and instead copy the resources and theme to your own project.
I have been trying to get my app to read data from the preferences, and change the theme according to the option selected. I have found many different suggestions on the internet, including here, but have been unable to get it to work.
I have created preferences.xml and arrays.xml, and the user is able to select the theme they want. However, the change is not reflected in the app.
Here are the contents of ActivityMain.java:
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String userTheme = preferences.getString("prefTheme", "darkab");
if (userTheme.equals("darkab"))
setTheme(R.style.darkab);
else if (userTheme.equals("light"))
setTheme(R.style.light);
else if (userTheme.equals("dark"))
setTheme(R.style.dark);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#SuppressLint("NewApi")
protected void onResume(Bundle savedInstanceState) {
recreate();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String userTheme = preferences.getString("prefTheme", "darkab");
if (userTheme.equals("darkab"))
setTheme(R.style.darkab);
else if (userTheme.equals("light"))
setTheme(R.style.light);
else {setTheme(R.style.dark);}
super.onResume();
setContentView(R.layout.activity_main);
}
These are the styles I wish to use, as set in styles.xml:
<style name="darkab" parent="android:Theme.Holo.Light.DarkActionBar"></style>
<style name="light" parent="android:Theme.Holo.Light"></style>
<style name="dark" parent="android:Theme.Holo">
And here is my preferences.java file:
public class Preferences extends PreferenceActivity {
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
Any help would be appreciated.
setTheme() is effective only before the layout has been constructed i.e. you should call it before setContentView(). The LayoutInflater resolves theme attributes and accordingly set properties on the View's it creates. To apply a theme on an already running Activity, you would have to re-start the Activity.
I know that I am late but I would like to post a solution here:
Check the full source code here.
This is the code I used when changing theme using preferences..
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(this);
String themeName = pref.getString("prefSyncFrequency3", "Theme1");
if (themeName.equals("Africa")) {
setTheme(R.style.AppTheme);
} else if (themeName.equals("Colorful Beach")) {
//Toast.makeText(this, "set theme", Toast.LENGTH_SHORT).show();
setTheme(R.style.beach);
} else if (themeName.equals("Abstract")) {
//Toast.makeText(this, "set theme", Toast.LENGTH_SHORT).show();
setTheme(R.style.abstract2);
} else if (themeName.equals("Default")) {
setTheme(R.style.defaulttheme);
}
Please note that you have to put the code before setcontentview..
We know that when the app do some long process like downloading some information from internet it could show a splash screen before loading the application and when the app is loaded completely it will display the main page.
In splash screen activity we must load long processes in threads to avoid showing black screen before loading app.
I had done all of them. but also the black screen appears before showing app.
This is my onCreate method of the splash screen activity:
protected override void OnCreate (Bundle bundle)
{
try {
base.OnCreate (bundle);
//_dt = DateTime.Now.AddSeconds (_splashTime);
SetContentView (Resource.Layout.Splash );
FirstLoadPB= FindViewById <ProgressBar >(Resource .Id.FirstLoadPB );
FirstLoadingInfo= FindViewById <TextView >(Resource .Id.FirstLoadInfo );
LoadApplication ();
} catch (System.Exception ex) {
Common.HandleException (ex);
}
}
and this is the code of LoadApplication method:
public void LoadApplication()
{
new System.Threading.Thread (new ThreadStart (() =>
{
//Some Codes to load applications- Downloading from web and accessing the storage(Because was many codes - about 100 line- i was clear them.
}
)
).Start ();
}
I don't understand why the black screen appears and how should to avoid from this now.
I have some code that access to storage in oncreate of my application class. Maybe the issue's root cause be from there.There fore i shared its code:
public override void OnCreate ()
{
try {
base.OnCreate ();
_typeOfShow = new MapViewType ();
ListingTypes = new Dictionary<int,ListingTypeItem> ();
OfflineMode =false;
PropertyShowWasShown = false;
MeasutingUnitsChanged =false;
if(RplXmlSettings .Instance .getVal (AppConstants .XmlSettingShowOnCurrentLocationKey )== "True")
typeOfShow .ShowOnCurrentLocation =true ;
else
typeOfShow .ShowOnCurrentLocation =false;
//StorageClass .ctx = ApplicationContext ;
FillDashboardOnResume =false;
//initlize image loader
ImageLoader = Com.Nostra13.Universalimageloader.Core.ImageLoader.Instance;
Options = new DisplayImageOptions.Builder ()
.ShowImageForEmptyUri (Resource.Drawable.ic_tab_map)
.CacheOnDisc ()
.CacheInMemory ()
.ImageScaleType (ImageScaleType.InSampleInt)
.BitmapConfig (Bitmap.Config.Rgb565)
.Displayer (new FadeInBitmapDisplayer (300))
.Build ();
ImageLoaderConfiguration config;
ImageLoaderConfiguration .Builder builder =new ImageLoaderConfiguration
.Builder (ApplicationContext).ThreadPoolSize (3);
if(RplXmlSettings .Instance .getVal (AppConstants .XmlSettingMemoryCacheKey )== "True")
builder .ThreadPriority (4).MemoryCacheSize (1500000) ;// 1.5 Mb
builder .
DenyCacheImageMultipleSizesInMemory ().
DiscCacheFileNameGenerator (new Md5FileNameGenerator ()).
MemoryCache (new WeakMemoryCache()).
DiscCacheSize (15000000);
config = builder .Build ();
ImageLoader.Init (config);
} catch (Exception ex) {
Common .HandleException (ex);
}
}
OK.Long story short.Now the question is this-- Really what is the root cause of this black screen. Is this from splash activity or from application class. And How we can solve it and avoid form showing this?
Add a theme with the background you are using to your application tag in the manifest file to prevent the black screen to be drawn.
theme.xml
<resources>
<!-- Base application theme is the default theme. -->
<style name="Theme" parent="android:style/Theme" />
<style name="Theme.MyAppTheme" parent="Theme">
<item name="android:windowNoTitle">true</item>
<item name="android:windowContentOverlay">#null</item>
<item name="android:windowBackground">#drawable/my_app_background</item>
</style>
</resources>
AndroidManifest.xml
....
<application
android:name="#string/app_name"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/Theme.MyAppTheme"
>
....
Read why there is a black screen here
This initial screen that you see is called the "Preview" screen. You can disable this completely by declaring this in your theme:
android:windowDisablePreview
<style name="Theme.MyTheme" parent="android:style/Theme.Holo">
<!-- This disables the black preview screen -->
<item name="android:windowDisablePreview">true</item>
</style>
An explanation of how to handle this screen is posted here: http://cyrilmottier.com/2013/01/23/android-app-launching-made-gorgeous/
Add this line in your AndroidManifest.xml to the Launcher Activity:
android:theme="#android:style/Theme.Translucent.NoTitleBar.Fullscreen
You can solve this bug by converting image as a brush(color).
Add new file xml(splash_bg.xml) file in the drawable folder, like this.
<?xml version="1.0" encoding="utf-8" ?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<color android:color="#color/splash_bg_color"/>
</item>
<item>
<bitmap
android:src="#drawable/splash_screen"
android:tileMode="disabled"
android:gravity="center"/>
</item>
</layer-list>
Now add a new style, and apply splash_bg.xml as a background color.
<style name="Theme.SplashBg" parent="android:Theme">
<item name="android:windowBackground">#drawable/splash_bg</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowContentOverlay">#null</item>
</style>
Apply this new style to your main launcher activity or splash screen.
[Activity(Label = "label", MainLauncher = true, Theme = "#style/Theme.SplashBg")]
public class SplashScreenActivity : Activity
If you call some "heavy code" in onCreate the screen will appear black until it is done loading. You might consider using AsyncTask and make the onCreate handle setContentView etc, and make the AsyncTask handle "the heavy code".
the better solution to avoid this problem is using AsyncTask, here is a sample code that i use in one of my ListActivity:
private class YoutubeTask extends AsyncTask<URL, Integer, String> {
protected void onPreExecute() {
super.onPreExecute();
mLoadingProgress.startAnimation(mDisappear);
mLoadingProgress.setVisibility(View.GONE);
showDialogProgress();
}
protected String doInBackground(URL... url) {
youtubeData = VersionParser.readFromUrl(url[0]);;
try {
JSONObject jsono = new JSONObject(youtubeData);
JSONObject feed = jsono.getJSONObject("feed");
JSONArray entry = feed.getJSONArray("entry");
for(int i = 0 ; i < entry.length() ; i++ ){
JSONObject item = entry.getJSONObject(i);
JSONArray AUTHOR = item.getJSONArray(TAG_AUTHOR);
JSONObject Author = AUTHOR.getJSONObject(0);
JSONObject author = Author.getJSONObject("name");
String author_name = author.getString(TAG_TITRE);
JSONObject Statistics = item.getJSONObject("yt$statistics");
String Views = Statistics.getString(TAG_VIEWS);
JSONObject Media = item.getJSONObject("media$group");
JSONObject MediaTitle = Media.getJSONObject("media$title");
String title = MediaTitle.getString(TAG_TITRE);
JSONObject DURATION = Media.getJSONObject("yt$duration");
String duration = DURATION.getString(TAG_DURATION);
JSONArray Thumbinail = Media.getJSONArray("media$thumbnail");
JSONObject IMAGE = Thumbinail.getJSONObject(0);
String image = IMAGE.getString(TAG_CONTENT);
String id = image.substring(22,33);
map = new HashMap<String, String>();
map.put(TAG_TITRE , title );
map.put(TAG_ID , id );
map.put(TAG_DURATION , duration );
map.put(TAG_IMAGE , image);
map.put(TAG_VIEWS , Views );
map.put(TAG_AUTHOR , author_name);
CURRENCY.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
dismisDialogProgress();
mListView.setVisibility(View.VISIBLE);
mListView.startAnimation(mAppear);
mAdapter = new MAdapter(youtubeSearch.this , CURRENCY);
mListView.setSelector(R.drawable.home_bg);
mListView.setAdapter(mAdapter);
}
}
and inside the onCreate Methode implement this:
#Override
public void onCreate(Bundle savedInstanceState) {
if (Build.VERSION.SDK_INT < 11)
setTheme(android.R.style.Theme_Black_NoTitleBar);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new YoutubeTask().execute(new URL("https://gdata.youtube.com/feeds/api/videos?q=Adele&max-results=15&v=2&alt=json"));
}
Here's some food for thought; maybe you don't have a sizeable initialization delay in your application at all; you might in fact, be waiting for the instant run service.
From what I've experienced, the symptoms of this are that your application shows a lengthy black screen whilst initializing, but upon debugging you find that none of your Application/Activity's onCreate methods have yet to even be called whilst it's visible.
This happens only when you use an activity as a Splash screen, if your app does not do any background operation like calling a api and stuff like that then use #maulikparmar method for standard splash screen(google recommended Way). But for activity method I only wrote a annotation in My splash screen activity , this worked for me very well
#SuppressLint("CustomSplashScreen")
public class SplashScreen extends AppCompatActivity {}
and also do android:windowDisablePreview = true in your theme (style.xml) of splash screen activity.
<item name="android:windowDisablePreview">true</item>