Black screen before Splash screen appear in android - android

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>

Related

Dynamically change android's accent color

I set Android's accent color to grey, so it would look normal in any theme (light or dark). And gray works great for edit control for example, but it turns out that is also used in alert cancel button's text. So now it looks fine in light theme, but very bad in the dark one.
How can I change colorAccent for Android dynamically from Xamarin.Forms app?
Edit: Here is my theme changing code as of now. (I'm not using AppThemeBinding since this approach allows to more than two themes)
In Xamarin Forms, we could use DependencyService to call native method. Fortunately, Android document provide the method setLocalNightMode to modify the local DarkMode. We should note that this mehtod can not modify the configure of Settings for the Mobile.
Now we can create a IDarkModeService interface:
public interface IDarkModeService
{
void SetDarkMode(bool value);
}
Then implement its method in Android solution:
public class DarkModeService : IDarkModeService
{
public void SetDarkMode(bool value)
{
if (value)
{
MainActivity.instance.Delegate.SetLocalNightMode(AppCompatDelegate.ModeNightYes);
MainActivity.instance.Recreate();
}
else
{
MainActivity.instance.Delegate.SetLocalNightMode(AppCompatDelegate.ModeNightNo);
MainActivity.instance.Recreate();
}
}
}
Here we need to create a static instance from MainActivity
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
public static MainActivity instance { set; get; }
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
instance = this;
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
}
}
And not forgetting to add configure inside styles.xml to make the app support DarkMode:
<style name="MainTheme" parent="Theme.AppCompat.DayNight.NoActionBar"></style>
Last, we could call the dependency method in Xamarin Forms as follows:
private async void ShowDialog_Clicked(object sender, EventArgs e)
{
await DisplayAlert("Alert", "You have been alerted", "OK");
}
private void SetDarkMode_Clicked(object sender, EventArgs e)
{
DependencyService.Get<IDarkModeService>().SetDarkMode(true);
}
private void CancelDarkMode_Clicked(object sender, EventArgs e)
{
DependencyService.Get<IDarkModeService>().SetDarkMode(false);
}
The effect:
==================================Update==================================
If need to custom style of each Theme, you could exchange Theme on runtime.
First, you could store a Theme flag(DarkMode) in Xamrin Forms:
private void SetDarkMode_Clicked(object sender, EventArgs e)
{
Preferences.Set("DarkMode", true);
DependencyService.Get<IDarkModeService>().SetDarkMode(true);
}
private void CancelDarkMode_Clicked(object sender, EventArgs e)
{
Preferences.Set("DarkMode", false);
DependencyService.Get<IDarkModeService>().SetDarkMode(false);
}
Then add each Theme style inside styles.xml:
<?xml version="1.0" encoding="utf-8" ?>
<resources>
<style name="MainTheme" parent="Theme.AppCompat.DayNight.NoActionBar">
</style>
<style name="DayTheme" parent="MainTheme">
</style>
<style name="NightTheme" parent="MainTheme" >
<item name="buttonBarPositiveButtonStyle">#style/positiveBtnStyle</item>
<item name="buttonBarNegativeButtonStyle">#style/negativeBtnstyle</item>
</style>
<!--style of sure button-->
<style name="positiveBtnStyle" parent="Widget.AppCompat.Button.ButtonBar.AlertDialog">
<item name="android:textColor">#0000ff</item>
</style>
<!--style of cancel button-->
<style name="negativeBtnstyle" parent="Widget.AppCompat.Button.ButtonBar.AlertDialog">
<item name="android:textColor">#999999</item>
</style>
</resources>
Last, change the Theme before create view in MainActivity.cs:
public static MainActivity instance { set; get; }
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
instance = this;
var darkMode = Preferences.Get("DarkMode", false);
if (darkMode)
{
this.SetTheme(Resource.Style.NightTheme);
}
else
{
this.SetTheme(Resource.Style.DayTheme);
}
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
Now we could see the color style of button will change:
you can't, because the accent color is defined in the theme and themes are read-only. I assume that dynamically means programmatically.
I found the solution!
All you have to put accent (or any other) color for light theme in MyApp.Android\Resources\values\colors.xml and for dark theme in MyApp.Android\Resources\values-night\colors.xml. Then reference that color by name in your theme in styles.xml <item name="colorAccent">#color/colorAccent</item>.
Now, when device would switch to dark theme accent color also would change.
Now. What if you have manual theme control in your app? You can force Android to display color for light or dark theme. Add similar interface to the shared project:
namespace MyApp.Core.Models.InterplatformCommunication
{
public interface INightModeManager
{
NightModeStyle DefaultNightMode { get; set; }
}
public enum NightModeStyle
{
/// <summary>
/// An unspecified mode for night mode.
/// </summary>
Unspecified = -100,
/// <summary>
/// Mode which uses the system's night mode setting to determine if it is night or not.
/// </summary>
FollowSystem = -1,
/// <summary>
/// Night mode which uses always uses a light mode, enabling non-night qualified resources regardless of the time.
/// </summary>
No = 1,
/// <summary>
/// Night mode which uses always uses a dark mode, enabling night qualified resources regardless of the time.
/// </summary>
Yes = 2,
/// <summary>
/// Night mode which uses a dark mode when the system's 'Battery Saver' feature is enabled, otherwise it uses a 'light mode'.
/// </summary>
AutoBattery = 3
}
}
Add this implementation in Android project. Setting AppCompatDelegate.DefaultNightMode forces the app to load resources for light or dark theme without restarting the app.
[assembly: Xamarin.Forms.Dependency(typeof(NightModeManager))]
namespace MyApp.Droid.Dependences
{
public class NightModeManager : INightModeManager
{
public NightModeStyle DefaultNightMode
{
get => (NightModeStyle)AppCompatDelegate.DefaultNightMode;
set => AppCompatDelegate.DefaultNightMode = (int)value;
}
}
}
Add this logic when changing theme of your app (AppTheme is a custom enum):
private static void UpdateNativeStyle(AppTheme selectedTheme)
{
NightModeStyle style = selectedTheme switch
{
AppTheme.Dark => NightModeStyle.Yes,
AppTheme.Light => NightModeStyle.No,
AppTheme.FollowSystem => NightModeStyle.FollowSystem,
_ => throw new InvalidOperationException("Unsupported theme"),
};
var nightModeManager = DependencyService.Get<INightModeManager>();
nightModeManager.DefaultNightMode = style;
}
More info about this:
https://medium.com/androiddevelopers/appcompat-v23-2-daynight-d10f90c83e94
https://www.journaldev.com/19352/android-daynight-theme-night-mode
As as side note, after setting:
AppCompatDelegate.DefaultNightMode = ...
you need to recreate the activity to apply changes to current Page:
activity.Recreate();
For example, if you are using CrossCurrentActivity plugin for Xamarin, you can do:
CrossCurrentActivity.Current.Activity.Recreate();

How to add real Loading Screen

I have an android application of a pdf file inside. When I open my application on lower configuration devices (galaxy 2 etc.), it takes a while to load the PDF file. I tried to adding a splash screen in my application but when opening MainActivity.class after SplashScreen still taking same time. How can I develop a real loading screen? It should work on top of Main Activity layer.
Here my codes:
AndroidManifest.xml
<activity
android:name=".SplashScreen"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity"></activity>
</application>
</manifest>
SplashScreen.class
public class SplashScreen extends AppCompatActivity {
private GifImageView gifImageView;
private ProgressBar progressBar;
Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
gifImageView=(GifImageView)findViewById(R.id.gifview);
progressBar=(ProgressBar)findViewById(R.id.progressbar);
progressBar.setVisibility(progressBar.VISIBLE);
try {
InputStream inputStream = getAssets().open("loading.gif");
byte[] bytes = IOUtils.toByteArray(inputStream);
gifImageView.setBytes(bytes);
gifImageView.startAnimation();
}
catch (IOException ex)
{
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = newIntent(SplashScreen.this,MainActivity.class);
SplashScreen.this.startActivity(intent);
SplashScreen.this.finish();
}
},12000);
}
}
Here my codes how I can solve this problem?
Have you considered using Async Task for this?
You can use the async task in your MainActivity.
For Example you can do something like the following:
class PDFLoader extends AsyncTask<Void, Void, Void>
{
protected void onPreExecute (){
super.onPreExecute();
// Here you can instantiate the Progressdialog to show the progress.
}
protected String doInBackground(Void...arg0) {
// here you can go ahead write the reading logic for the PDF
// if it is taking time.
}
protected void onProgressUpdate(Integer...a){
super.onProgressUpdate(a);
// you may or may not use this. This can act as a progress updated based on
// the integer.
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Here you can dismiss the progress bar since the read as been done.
}
}
Call it like this in your MainActivity:
new PDFLoader().execute();
I hope this helps you.
This is just the basic structure to get you started. More information here.
Using a Splash screen is not a solution to this.You are adding a screen with 12second gap and after 12 second the MainActivity class is getting execute.
So, you can directly add a progress bar in MainActivity class and you can use AsyncTask to solve this problem.
AsyncTask has 3 methods-
OnPreExecute, doInBackground, OnPostExecute. Here, you can add a progress bar in OnPreExecute method and the code for opening PDF file in doInBackground method, and finally stop the progress bar in OnPostExecute method.
For more help you should provide your MainActivity class code here.
You should give a shot to this article: https://antonioleiva.com/branded-launch-screen/
It's far better than Splash Screen, 'cause It loads async to your MainActivity
Add this code to styles:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar" />
<style name="AppTheme.BrandedLaunch" parent="AppTheme">
<item name="android:windowBackground">#drawable/branded_logo</item>
</style>
Now create branded_logo.xml into your drawable directory
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<color android:color="#color/background_material_light"/>
</item>
<item>
<bitmap
android:src="#drawable/launch_logo_image"
android:tileMode="disabled"
android:gravity="center"/>
</item>
</layer-list>
And assign that style into your MainActivity
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.BrandedLaunch">
And finally add setStyle to your default theme in your onCreate in MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.AppTheme);
super.onCreate(savedInstanceState);
...
You can create a LoadingScreen instead of splash screen(looking at your 12 secs. delay). Here is something that might help:
public class LoadingScreen {private ImageView loading;
LoadingScreen(ImageView loading) {
this.loading = loading;
}
public void setLoadScreen(){
final Integer[] loadingImages = {R.mipmap.loading_1, R.mipmap.loading_2,
R.mipmap.loading_3, R.mipmap.loading_4};
final Handler loadingHandler = new Handler();
Runnable runnable = new Runnable() {
int loadingImgIndex = 0;
public void run() {
loading.setImageResource(loadingImages[loadingImgIndex]);
loadingImgIndex++;
if (loadingImgIndex >= loadingImages.length)
loadingImgIndex = 0;
loadingHandler.postDelayed(this, 500);//change to accordingly(i.e. 12000)
}
};
loadingHandler.postDelayed(runnable, 500); // change it accordingly
}}
In your MainActivity, you can pass a to the LoadingScreen class like this :-
private ImageView loadingImage;
Don't forget to add an ImageView in activity_main. After that call the LoadingScreen class like this;
LoadingScreen loadingscreen = new LoadingScreen(loadingImage);
loadingscreen.setLoadScreen();
It is always helpful in creating a custom loading screen instead of Splash screen.Also don't forget to add some different images to make that feel like a gif and after that add the images in the res folder . I have checked it for lower versions too Therefore, believe that it might serve your purpose...
Nowadays lots of applications are avoiding loading screen due to bad UI/UX. You can use alternative for content loading. This article may help more about. You can look this kind of implementation on lot of popular apps like Facebook, LinkedIn, Upwork etc.

How to display Splash Screen in android

I want to display splash screen in android app. But I want to execute onCreate() method of MainActivity behind the splash screen. because i am doing huge work in this method. Anyone can tel me how to do that.
Basically you want to do some work in background while user is shown some splash screen, right ? What you need is an Async Task or a Loader kind of thing.
Step 1: Display the splash screen.
Step 2: Start an Async task and do all your heavy processing in the doInBackground method of Async Task
Step 3: Update the UI using the onPostExecute method of Async Task. In this method, first close the timer to splash screen. Then send the intent to start another screen with the data of the heavy processed result of Async task. Display it on UI thread.
Only Showing Splash screen is very simple. This code creates a splash screen of 3 seconds and then sends an Intent to another activity.
public class SplashScreenActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
CountDownTimer cdt1 = new CountDownTimer(3000, 1000) {
Boolean checkInternetConnection = false;
#Override
public void onTick(long l) {
}
#Override
public void onFinish() {
//Send Intent here
Intent i = new Intent(getApplicationContext(),
anotherActivity.class);
startActivity(i);
}
}.start();
}
PS- Dont forget to make the activity with this code as launcher activity from manifest file.
You can try this for Splash Screen...
public class SplashScreen extends Activity {
//Further Needed Declarations
#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();
}
}
This is exactly the same way you wanted it.
create file in drawable
<item
android:drawable="#color/gray"/>
<item>
<bitmap
android:gravity="center"
android:src="#mipmap/ic_launcher"/>
</item>
</layer-list>
Styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
</style>
<style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
<item name="android:windowBackground">#drawable/background_splash</item>
</style>
</resources>
Activity:
public class SplashActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
}
You can add this in your onCreate Method
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// going to next activity
Intent i=new Intent(SplashScreenActivity.this,MainActivity.class);
startActivity(i);
finish();
}
},time);
And initialize your time value in milliseconds as yo want...
private static int time=5000;
for more detail download full code from this link...
https://github.com/Mr-Perfectt/Splash-Screen

How do I avoid a black screen before startup?

I created a loadpage with a background and a progress bar and when it finishes loading, it starts the main class but the loading screen is not showing up. It is just a black screen while it loads and then the main screen. I put all the work in the onResume and I also tried onStart with no luck
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loadpage);
//get rid of title bar
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(1);
}
#Override
public void onResume() {
super.onResume();
words = WordList.sharedWordList(this);
if(generatedLevels==null)
{
generatedLevels = new ArrayList<PuzzleMZLen>();
}
if(!p.isAlive())
{
p.start();
}
Intent i = new Intent(getApplicationContext(), Main.class);
startActivity(i);
}
thanks in advance
You have to use AsyncTask for this kind of work.Your layout is populated after the completion of the loading.So you are watching black screen.
Use onPreExecute of AsyncTask class to show the progress bar. And write loading code in the doInBackground method.
Definitely use AsyncTask for this. I had the same thing going for my app, and here's my code:
private class getAllData extends AsyncTask<Context, Void, Cursor> {
protected void onPreExecute () {
dialog = ProgressDialog.show(Directory.this, "",
"Loading. Please wait...", true);
}
#Override
protected Cursor doInBackground(Context... params) {
DirectoryTransaction.doDepts();
return null;
}
protected void onPostExecute(Cursor c) {
for(int i = 0 ; i < DeptResults.length ; i++){
deptsAdapter.add(DeptResults[i][0]);
}
dialog.dismiss();
}
}
onPreExecute method loads a ProgressDialog that just shows "Loading. Please wait...". doInBackground does what was making my app load (in my case grabbing and parsing text from a server) and then onPostExecute is filling a spinner then dismissing the ProgressDialog. You'll want some thing different for a progress BAR, but the AsyncTask will be very similar. Call it in onCreate with new getAllData.execute(this);
There is a good way how to create a good splash activity.
To prevent ANR you should move all data loading outside of UI thread as it was mentioned at other answers. Please use AsyncTask or any other kind of multi-threading for that.
However to remove annoying black screen which shows for few moments on some slow devices you need to do next steps:
Create bg_splash drawable. It will be shown instead of black background just in time activity shows to user. For example it can be brand logo on brand color background.
Create a splash screen theme and put it into /res/values/themes.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="MyApp.Splash" parent="#style/Theme.Sherlock.Light.NoActionBar">
<item name="android:windowBackground">#drawable/bg_splash</item>
</style>
</resources>
Don't forget assign created theme to splash activity by updating AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp"
android:versionCode="1"
android:versionName="1" >
...
<application>
<activity
android:name=".SplashActivity"
android:theme="#style/MyApp.Splash" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<activity>
...
</application>
</manifest>

Clean dialog collector class for use in all other activities [Android]

Im trying and searching for a good method to handle dialogs in a single class so i can use them in any activity i want. The most clean and good performance method would be best.
Currently im handly dialogs in each activity where the main work is done. If i need to change a dialog or dialogevent its a hassle to search through all my classes.
[SOLVED] ~ Update with code below.
Looks great. Hope im doing good with it. Any optimization?
--- Code from Dialog Class
public class Dialogs extends Activity {
public static final int DIALOG_START = 0;
public static final int DIALOG_END = 1;
private Context mContext;
private int mDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = getApplicationContext();
mDialog = getIntent().getExtras().getInt("dialog");
showDialog(mDialog);
}
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
switch (id) {
case DIALOG_START:
Toast.makeText(mContext, "Test...", Toast.LENGTH_SHORT).show();
finish(); //works because toasts are somehow delayed
break;
case DIALOG_END:
// do something else but always finish(), e.g. after dialogbutton- click.
break;
}
return dialog;
}
}
--- Code in target Activity (for example button click):
Intent dialogIntent = new Intent();
dialogIntent.setClass(Main.this, Dialogs.class);
dialogIntent.putExtra("dialog" , Dialogs.DIALOG_START);
startActivityForResult(dialogIntent, 0x0);
--- Code in Manifest:
<activity android:name=".Dialogs" android:label="#string/app_name"
android:configChanges="orientation|keyboardHidden"
android:theme="#style/dialog" />
--- Code in Stylefile (values/style.xml):
<style name="dialog" parent="#android:style/Theme.Dialog">
<item name="android:windowBackground">#android:color/transparent</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowContentOverlay">#null</item>
</style>
You have to create one Activity whose theme set as #android:style/Theme.Dialog in Android-manifest.xml. Then you can use this one as dialog(or popup) anywhere simply as we use activities that is by startActivityForResult(Intent intent, int requestCode).

Categories

Resources