Android display Splash-Screen while loading - java

I have an Android App, which shows a "Splash Screen" for 3 seconds. After that, the MainActivity gets loaded.
Unfortunately the MainActivity takes additional ~4 seconds to load. On first startup even longer. However when the App is loaded, everything runs smooth.
Now how can I achieve it, that the MainActivity gets loaded, during the display of the Splash Screen? It just should display an image until the whole thing loaded completely.
I have read about Async-Task, but I'm not sure where to put it and how to use it properly. Can someone help me please?
SplashScreen.java
public class SplashScreen extends Activity {
private static int SPLASH_TIME_OUT = 3000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_startup);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(SplashScreen.this, MainActivity.class);
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
}
}
MainActivity.java
public class MainActivity extends Activity implements OnClickListener, MediaController.MediaPlayerControl {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Some heavy processing
//starting services
//starting Google Text to Speech
//and so on...
}
}

You should not be creating a new thread on startup, instead you should create a view that does not have to wait for your resources to load, as detailed in this article: Splash Screens the Right Way.
As stated in the article, you should create a layer-list drawable instead of a layout XML file:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Fill the background with a solid color -->
<item android:drawable="#color/gray"/>
<!-- Place your bitmap in the center -->
<item>
<bitmap
android:gravity="center"
android:src="#mipmap/ic_launcher"/>
</item>
</layer-list>
Then create a theme using the drawable file as a background. I use the background attribute instead of the windowBackground attribute as suggested in the article, because background takes the status and navigation bars into account, centering the drawable better. I also set windowAnimationStyle to null so that the splash screen does not animate the transition to the MainActivity:
<resources>
<!-- Base application theme -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
</style>
<!-- Splash Screen theme -->
<style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
<item name="android:background">#drawable/background_splash</item>
<item name="android:windowAnimationStyle">#null</item>
</style>
</resources>
Then declare your theme in the manifest for your SplashActivity:
<activity android:name=".SplashActivity"
android:theme="#style/SplashTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
And finally all you have to do in your SplashActivity is start your MainActivity, and the splash screen will only show for as long as it takes for your app to configure:
public class SplashActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
}

If there are no specific constraints about the time the splash screen should be shown, you could use the AsyncTask in the following way:
public class SplashScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_startup);
startHeavyProcessing();
}
private void startHeavyProcessing(){
new LongOperation().execute("");
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
//some heavy processing resulting in a Data String
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.interrupted();
}
}
return "whatever result you have";
}
#Override
protected void onPostExecute(String result) {
Intent i = new Intent(SplashScreen.this, MainActivity.class);
i.putExtra("data", result);
startActivity(i);
finish();
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
}
If the resulting data if of another nature than a String you could put a Parcelable Object as an extra to your activity. In onCreate you can retrieve the data with:
getIntent().getExtras.getString('data');

How about, in the interest of simplicity, you combine your splash activity with your main activity? That way you get the best of both worlds, namely a splash screen while your data is preparing the first time, and a quick startup when it's been prepared previously. Making the user wait for nothing is not really good form...
Something like:
public class MainActivity extends Activity implements OnClickListener, MediaController.MediaPlayerControl {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initially shows splash screen, the main UI is not visible
setContentView(R.layout.activity_main);
// Start an async task to prepare the data. When it finishes, in
// onPostExecute() get it to call back dataReady()
new PrepareDataAsyncTask(this).execute();
}
public void dataReady() {
// Hide splash screen
// Show real UI
}
}

your splash screen code works fine but when you call next activity then in onCreate() use Asynctask for your heavy tasks...

I have had similar problem. There was a blank loading screen (not even toolbar). Mu culprit was in the manifest in the MainActivity:
android:launchMode="singleInstance"

Just do like in this article:
1 - create a XML layout like this for the splash screen. I called it "background_splash.xml"
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:drawable="#color/cardview_light_background"/>
<item>
<bitmap
android:gravity="center"
android:src="#drawable/kiss_com_sub_logo"/>
</item>
</layer-list>
2 - Then, go to the styles.xml and write a style like this:
<style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
<item name="android:windowBackground">#drawable/background_splash</item>
</style>
3 - Write an activity to your splash. I called it SplashActivity.kt
class SplashActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
finish()
}
}
4 - Finally, go to you AndroidManifest.xml and add your activity splash: (Note: don't remove anything in the AndroidManifest, just add this before the Main activity).
<activity
android:name=".SplashActivity"
android:label="Kiss"
android:theme="#style/SplashTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
This is done. You don't need to worry about the time that your application will demand to start, the splash will be there just for enough time. When your MainActivity is ready, it will be showed.

Related

Why previous Activity get destroyed pressing up button on Setting Activity Toolbar?

GOAL: when the user press back on SettingsActivity toolbar the previous Activity should be resumed from where the user left.
PROBLEM: From Activity lifecycle reported on android developer website I understand that the previous Activity should be resumed calling OnResume method, instead in my case the MainActivity start again calling OnCreate method.
In particular the flow is as follows:
1) User click on icon to start SettingsActivity
2)MapsActivity invokes onPause, then onSaveInstanceState, then onStop
3) User click back button on SettingsActivity
4)MapsActivity invokes onDestroy then onCreate (and everything I tried to save during point 2 with saveInstanceState is lost because Bundle is always null)
CODE
MapsActivity (main activity)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// .... other initialization code ... //
// If location permission is granted initialize Map
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mapSync();
} else {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSION_FINE_LOCATION);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("prova", true);
}
// Where I start the second activity
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.connection_type:
// .... handle this case ... //
case R.id.settings:
Intent intent = new Intent(MapsActivity.this, SettingsActivity.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
SettingsActivity (called activity)
public class SettingsActivity extends AppCompatActivity
{
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
// Set the toolbar
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
myToolbar.setTitle("Settings");
myToolbar.setNavigationIcon(R.drawable.ic_baseline_arrow_back_24px);
myToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
setSupportActionBar(myToolbar);
}
public static class MainSettingsFragment extends PreferenceFragmentCompat {
public final static String KEY_ENABLE_BACKGROUND_UPDATE = "enable_background_update";
public final static String KEY_ENABLE_LAST_KNOWN_LOCATION = "enable_last_known_location";
public final static String KEY_DELETE_DB_DATA = "delete_db_data";
public final static String KEY_CHANGE_MAP_COLOR ="change_map_color";
private SharedPreferences.OnSharedPreferenceChangeListener preferenceChangeListener;
#Override
public void onCreatePreferences(Bundle bundle, String s) {
// Load the Preferences from the XML file
addPreferencesFromResource(R.xml.preferences);
preferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(key.equals(KEY_DELETE_DB_DATA))
{
String connectivityType = sharedPreferences.getString(key, null);
new DeleteAreaAsync(SignalAreaDatabase.getDatabase(getContext()), connectivityType).execute();
} else if(key.equals(KEY_CHANGE_MAP_COLOR)){
String gradientColor = sharedPreferences.getString(key, null);
SignalAreaDrawer signalAreaDrawer = SignalAreaDrawer.getSignalAreaDrawer();
signalAreaDrawer.setGradientColor( gradientColor);
}
}
};
}
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(preferenceChangeListener);
}
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(preferenceChangeListener);
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- Less accurate location: telephony manager and location requests -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- Access to wifi network information -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!-- Change wifi connectivity state -->
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat.Light.NoActionBar">
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SettingsActivity"
android:parentActivityName=".MapsActivity"
android:theme="#style/PreferenceScreen" />
</application>
QUESTION: how can I restore the previous Activity state and show to the user exactly what he was visualizing when he opened the second Activity?
EDIT #1:
I tried to override oonDestroy() , onSaveInstance(), onRestoreInstance() and this is what happens:
when I start the setting activity, the main activity go onPause() as I would expect.
when I press the back button on the settings activity , the main activity go before onDestroy() and immediately after onCreate(), not calling onSaveInstance() or onRestoreInstance() at all.
EDIT #2: the app didn't go through onSaveInstanceState(Bundle outState) probably because I declared it public. Now the app calls it. So I tried to save some info like outState.putBoolean("prova", true); but when the mainActivity is destroyed , at new onCreate(Bundle savedInstanceState) invokation the Bundle savedInstanceState is always null.
EDIT #3: as #SherifelKhatib suggested I tried to delete all finish() statement from MapsActivity, and I tried to substitute MapsActivity with a minimal EmptyActivity to see if the problem was in MapsActivity. Unfortunately the app has the same behaviour.
When the user press the back button the previous app is always destroyed. No way to restore its state.
EDIT #4: what I tried and still doesn't work. Modifying SettingsActivity :
First approach
#Override
public void onBackPressed(){
moveTaskToBack(true);
}
Second approach
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
Third approach
#Override
public void onBackPressed() {
Intent backIntent = new Intent(this, MapsActivity.class);
backIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(backIntent);
}
And add this in MainActivity:
Intent intent = new Intent(MapsActivity.this, SettingsActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
SOLUTION:
Add this attribute to MainActivity in the manifest .
android:launchMode="singleTop"
Explanation
The "standard" and "singleTop" modes differ from each other in just
one respect: Every time there's a new intent for a "standard"
activity, a new instance of the class is created to respond to that
intent. Each instance handles a single intent. Similarly, a new
instance of a "singleTop" activity may also be created to handle a new
intent. However, if the target task already has an existing instance
of the activity at the top of its stack, that instance will receive
the new intent (in an onNewIntent() call); a new instance is not
created.

how to programatically theme an activity to be like a dialog?

Question
How does one programatically (without touching the AndroidManifext.xml) set the theme of an Activity so that it looks like a dialog?
Note: I am ok with modifying the AndroidManifext.xml as long as it does not need to be modified in order to switch between making it look like a normal activity or a dialog.
What I've tried so far
I tried the following as per this stackoverflow answer:
public class DialogActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
setTheme(android.R.style.Theme_DeviceDefault_Dialog);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialog);
Log.d(TAG,"Build.VERSION.SDK_INT: "+Build.VERSION.SDK_INT); // 23
}
}
But it ends up blacking out everything in the background.
I also saw this stackoverflow answer, and tried:
public class DialogActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
setTheme(android.R.style.Theme_DeviceDefault_Dialog);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialog);
getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
}
}
but it ends up making everything black.
What do? Thank you.
Background
The Activity behind an Acivity is drawn if the foreground activity's theme according to its AndroidManifest.xml is a dialog; otherwise the android os will not draw the Activity behind it (probably to save memory since it usually won't be seen anyway).
To exploit this, we set the theme of our Acitvity to a dialog in the manifest, making the android os draw the Activity behind it, but later, programatically set our Activity's theme to whatever we like at runtime.
Example on github
I made an example and put it on github.
Tutorial
Step 1: create two custom themes for your application in styles.xml. One for normal activities, and another for dialog activities. It is important for the custom dialog theme to inherit from a base theme that is also a dialog. In my case, the parent theme is Base.Theme.AppCompat.Light.Dialog.FixedSize). Here is my styles.xml:
<resources>
<!-- custom normal activity theme -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
</style>
<!-- custom dialog activity theme -->
<style name="AppTheme.Dialog" parent="Base.Theme.AppCompat.Light.Dialog.FixedSize">
<!-- removing the dialog's action bar -->
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
</resources>
Step 2: in the AndroidManifest.xml, set the theme of the Activity in question to any dialog theme. This makes the android os think that the Activity is a dialog, so it will draw the Activity behind it, and not black it out. In my case, I used Theme.AppCompat.Dialog. Below is my AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.eric.questiondialog_artifact">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name">
<activity
android:name=".DialogActivity"
android:label="#string/app_name"
android:theme="#style/Theme.AppCompat.Dialog"> <-- IMPORTANT!!! -->
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
Step 3: in the actual activity, set the theme programatically to either the theme for normal activities, or the theme for dialogs. My DialogActivity.java is below:
package com.example.eric.questiondialog_artifact;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
public class DialogActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
setTheme(R.style.AppTheme_Dialog); // can either use R.style.AppTheme_Dialog or R.style.AppTheme as deined in styles.xml
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialog);
}
}
if what you're looking for is just a theme with transparent background for you activity, just use this:
<style name="Theme.Transparent" parent="android:Theme">
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowBackground">#android:color/transparent</item>
<item name="android:windowContentOverlay">#null</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowIsFloating">true</item>
<item name="android:backgroundDimEnabled">false</item>
</style>
apply this style to your activity in your AndroidManifest file and this is it
I am late but still for future users
you need to call the below code after setTheme() Calling this allows the Activity behind this one to be seen again. Once all such Activities have been redrawn
// setTheme()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
try {
Method getActivityOptions = Activity.class.getDeclaredMethod("getActivityOptions");
getActivityOptions.setAccessible(true);
Object options = getActivityOptions.invoke(activity);
Class<?>[] classes = Activity.class.getDeclaredClasses();
Class<?> translucentConversionListenerClazz = null;
for (Class clazz : classes) {
if (clazz.getSimpleName().contains("TranslucentConversionListener")) {
translucentConversionListenerClazz = clazz;
}
}
Method convertToTranslucent = Activity.class.getDeclaredMethod("convertToTranslucent",
translucentConversionListenerClazz, ActivityOptions.class);
convertToTranslucent.setAccessible(true);
convertToTranslucent.invoke(activity, null, options);
} catch (Throwable t) {
}
} else {
try {
Class<?>[] classes = Activity.class.getDeclaredClasses();
Class<?> translucentConversionListenerClazz = null;
for (Class clazz : classes) {
if (clazz.getSimpleName().contains("TranslucentConversionListener")) {
translucentConversionListenerClazz = clazz;
}
}
Method method = Activity.class.getDeclaredMethod("convertToTranslucent",
translucentConversionListenerClazz);
method.setAccessible(true);
method.invoke(activity, new Object[] {
null
});
} catch (Throwable t) {
}
}
Try these code before dailog.setMessage(...);
Dialog id = new AlertDialog.Builder(this,AlertDialog.THEME_DEVICE_DEFAULT_DARK);
Dialog ID = new AlertDialog.Builder(this,AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
//Default theme
Try this for Old theme
Dialog ID = new AlertDialog.Builder(this,AlertDialog.THEME_TRADITIONAL);
Try these for KITKAT theme
Dialog ID = new AlertDialog.Builder(this,AlertDialog.THEME_DEVICE_DEFAULT_DARK); //Dark
Dialog ID = new AlertDialog.Builder(this,AlertDialog.THEME_HOLO_LIGHT);
Try these codes for Pragmatically
Exmaple
dialog = new AlertDialog.Builder(this);
dialog = new AlertDialog.Builder(this,AlertDialog.THEME_DEVICE_DEFAULT_DARK);
dialog.setTitle("HAI");
dialog.setMessage("look");
dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
Toast toast= Toast.makeText(getApplicationContext(), "This is exmaple theme", Toast.LENGTH_LONG);

requestFeature() before adding content error when trying to make AndEngine work with Google Play Game Service

I have a game I'm working on, that uses AndEngine.
AndEngine has a "BaseGameActivity" and so does Google Play Game Service. I had to rename BaseGameActivity from AndEngine to AEBaseGameActivity and have it as a parent class BaseGameActivity instead of Activity.
But it is giving me this error:
Caused by: android.util.AndroidRuntimeException: requestFeature() must be called before adding content
at com.android.internal.policy.impl.PhoneWindow.requestFeature(PhoneWindow.java:226)
at org.andengine.util.ActivityUtils.requestFullscreen(ActivityUtils.java:56)
at org.andengine.ui.activity.AEBaseGameActivity.applyEngineOptions(AEBaseGameActivity.java:427)
at org.andengine.ui.activity.AEBaseGameActivity.onCreate(AEBaseGameActivity.java:83)
Now AndEngine has this piece of code:
public static void requestFullscreen(final Activity pActivity) {
final Window window = pActivity.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
window.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
window.requestFeature(Window.FEATURE_NO_TITLE);
}
if I comment the requestFeature line, my projects runs! But it has an ugly title bar.
Does anyone please know a fix for this ?
EDIT, HERE IS SOME MORE CODE:
PS: AEBaseGameActivity.php extends BaseActivity which extends BaseGameActivity (previously just activity)
AEBaseGameActivity.php
public abstract class AEBaseGameActivity extends BaseActivity implements IGameInterface, IRendererListener {
#Override
protected void onCreate(final Bundle pSavedInstanceState) {
if(BuildConfig.DEBUG) {
Debug.d(this.getClass().getSimpleName() + ".onCreate" + " #(Thread: '" + Thread.currentThread().getName() + "')");
}
super.onCreate(pSavedInstanceState);
this.mGamePaused = true;
this.mEngine = this.onCreateEngine(this.onCreateEngineOptions());
this.mEngine.startUpdateThread();
this.applyEngineOptions(); //REQUEST FULLSCREEN
this.onSetContentView(); //SET CONTENT VIEW
}
...
private void applyEngineOptions() {
final EngineOptions engineOptions = this.mEngine.getEngineOptions();
if(engineOptions.isFullscreen()) {
ActivityUtils.requestFullscreen(this); //ACTIVITY UTIL SHOWN LATER
}
...
}
...
protected void onSetContentView() {
this.mRenderSurfaceView = new RenderSurfaceView(this);
this.mRenderSurfaceView.setRenderer(this.mEngine, this);
this.setContentView(this.mRenderSurfaceView, AEBaseGameActivity.createSurfaceViewLayoutParams());
}
}
ActivityUtils.java
public class ActivityUtils {
public static void requestFullscreen(final Activity pActivity) {
final Window window = pActivity.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
window.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
window.requestFeature(Window.FEATURE_NO_TITLE); //IF COMMENTING THIS, THE GAME IS RUNNING
}
...
}
EDIT2:
The code is basically only AndEngine, here is the original code:
https://github.com/nicolasgramlich/AndEngine/tree/GLES2/src/org/andengine/ui/activity
My changes:
renamed BaseGameActivity to AEBaseGameActivity
BaseActivity extends BaseGameActivity (taken from Google Play Game Service) instead of Activity
BaseGameActivity and GameHelper.java taken from BaseGameUtils from Google Play Game Service.
Ok so this is what I did:
I commented out the line that is causing the problem (ActivityUtils.java line 56 of AndEngine)
I added this in my activity to the Android Manifest:
android:theme="#android:style/Theme.NoTitleBar"
It ends up looking something like:
<activity
android:name=".GameActivity"
android:theme="#android:style/Theme.NoTitleBar"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Exception requestFeature() must be called before adding content telling everything
call requestFullscreen() before setContenview()
Edit
try REQUEST FULLSCREEN after super.onCreate()
#Override
protected void onCreate(final Bundle pSavedInstanceState) {
super.onCreate(pSavedInstanceState);
this.applyEngineOptions(); //REQUEST FULLSCREEN

Android transparent black layer?

I have a ProgressBar and a login button.
When i click on the login button i show this progressBar and everything worke fine.
But it would be nice if i have a black transparent layer, like the AlertDialog class it do, and only the progressBar has the full bright.
Try to create another class with transculent theme.
For example new class:
public class BlahActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_blah);
ProgressDialog pg = new ProgressDialog(this);
pg.setTitle("Title of progress dialog");
pg.setMessage("Message of progress dialog");
pg.show();
}
}
And change in AndroidManifest.xml file (check second line):
<activity
android:name="com.example.dialog.BlahActivity"
android:theme="#android:style/Theme.Translucent.NoTitleBar"
android:label="#string/title_activity_blah" >
</activity>
Now, when you click on button in your class, you will have to only create new intent to open transculent class. OnCreate it will run ProgressDialog which will blur the rest and you will be able see text from the last activity.
You can also try with opening new intents with options onResult, this will allow you open intent - do something - and back to the last activity.
If you want total black, you don't have to set theme as transculent, just set background to black.
You can set in xml of the layout android:background:#60000000 where two first numbers are alpha and 6 next are the color in hex.

List Preference, How to Do something when the preference is clicked

Ok so every post i find i cannot get this to work, i am trying to inside my list preference
Settingsbasic.xml
<ListPreference
android:title="themes"
android:summary="Select the option of the list"
android:key="listPref"
android:entries="#array/Themes"
android:entryValues="#array/list"
android:defaultValue="default" />
Now about as you can see above this is my listpreference inside my settingsbasic.xml file. Now what i need to know how to do is i have 2 java files, my main activity. and my preferences java file. I need to know how i can when the user clicks one of the the entries it does something, likes opens something or changes the ui, just something i think i can take it from there. I just need to know how and where the code would go. inside the main acitivty or preference activity.
here is my preference java file
public class Prefs extends PreferenceActivity {
ListPreference listPref;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settingsbasic);
}
protected void onResume() {
super.onResume();
// Registers a callback to be invoked whenever a user changes a preference.
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
protected void onPause() {
super.onPause();
// Unregisters the listener set in onResume().
// It's best practice to unregister listeners when your app isn't using them to cut down on
// unnecessary system overhead. You do this in onPause().
getPreferenceScreen()
.getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// Sets refreshDisplay to true so that when the user returns to the main
// activity, the display refreshes to reflect the new settings.
WebViewClientDemoActivity.????? = true;
}
}
Any example code would help, or adding on to my code above. I just need someone whom can shed some light on this code. i've tried so many different things and none of it works.
Ok so using the method of the sample app that was recommended below here is some more code i have .
Main Activity
public class WebViewClientDemoActivity extends Activity {
public static String sPref = null;
public void onStart() {
super.onStart();
// Gets the user's network preference settings
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
// Retrieves a string value for the preferences. The second parameter
// is the default value to use if a preference value is not found.
sPref = sharedPrefs.getString("listPref", "Default");
}
This is the way I used PreferenceActivity:
public class EditPrefs extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.screen_prefs);
}
}
Then in /res/xml folder I have the XML file:
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<ListPreference
android:key="txtColor"
android:title="textView Color"
android:summary="select color for textViews"
android:entries="#array/txtColor"
android:entryValues="#array/txtColorValues" />
</PreferenceScreen>
And in /res/values I have this XML file includes items and their values:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="txtColor">
<item>blue</item>
<item>brown</item>
<item>gray</item>
<item>violet</item>
</string-array>
<string-array name="txtColorValues">
<item>#ff000099</item>
<item>#5F1E02</item>
<item>#333333</item>
<item>#421C52</item>
</string-array>
</resources>
Then I easily call this class from another android class for instance when user clicks on a menu item:
startActivity(new Intent(this, EditPrefs.class));
You can call the preferences in onCreate and onResume like:
#Override
protected void onResume() {
super.onResume();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String txtColor = prefs.getString("txtColor", DEFAULT COLOR); // for instanse : #ff000099
textView.setBackgroundColor(Color.parseColor(txtColor));
}
I have resolved my question by this.
Prefs
public static String theme = "Theme1";
#Override
public void onBackPressed() {
ListPreference listPreference = (ListPreference) findPreference("listPref");
String currValue = listPreference.getValue();
theme = currValue;
super.onBackPressed();
}
Main Activity
if (Prefs.theme.equals("Theme1"))
setContentView(R.layout.main);
else
setContentView(R.layout.main2);
Preference XML
<ListPreference
android:title="themes"
android:summary="Select the option of the list"
android:key="listPref"
android:entries="#array/listReturnValue"
android:entryValues="#array/listDisplayWord" />

Categories