Showing activity from onCreate - java

Problem Description
I have two activities in my application MainActivity and BannerActivity. From the main activity I start BannerActivity in onCreate method. But I first I see MainActivity screen for a second and then BannerActivity screen.
Question
How I can do so that BannerActivity will be shown first and after countdown timer will stop and BannerActivity will close after that MainActivity come to the screen.
MainActivity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Show banner activity for several seconds then close it. */
Intent bannerIntent = new Intent(MainActivity.this, BannerActivity.class);
this.startActivity(bannerIntent);
}
};
BannerActivity
public class BannerActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
/* Make banner fullscreen. */
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_banner);
/* Launch count down timer for several seconds. */
CountDownTimer countDownTimer = new CountDownTimer(3000, 1000) {
#Override
public void onTick(long millisUntilFinished) { /* Not used. */ }
#Override
public void onFinish() {
BannerActivity.this.finish();
}
}.start();
}
#Override
public void onBackPressed() {
/* Lock back button presses. */
super.onBackPressed();
}
};

You need a SplashScreen:
http://www.thiagorosa.com.br/en/tutorial/part01-splash-screen
public class GameSplash extends Activity {
// time to wait on the splash screen
private static final int SPLASH_SCREEN_DELAY = 3000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
new Thread() {
#Override
public void run() {
try {
// do any heavy initialization here
// wait a few seconds before going to the next screen
sleep(SPLASH_SCREEN_DELAY);
}
catch (InterruptedException e) {
}
catch (Exception e) {
}
finally {
// start the level selection screen
Intent intentSelect = new Intent(GameSplash.this, GameSelect.class);
startActivity(intentSelect);
}
}
}.start();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// ignore any key press on the splash screen
return true;
}
}

Run first BannerActivity and in the contdown run MainActivity rather than BannerActivity.this.finish();

You can start with BannerActivity and then when the time expires you go to MainActivity and clear the history stack by using this intent flag (so that you can't go back to the BannerActivity using the back button).
Intent.FLAG_ACTIVITY_CLEAR_TASK

Swap the activites on the Manifest to decide which activity is run first :
<activity
android:name="com.yourpackagename.MainActivity"
android:label="#string/app_name" >
</activity>
<activity
android:name="com.yourpackagename.BannerActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
The BannerActivity should have the <intent-filter> tag and set as Main and Launcher as the example. This will make Banner activity as the Initial Activity when you start your application.
After that you can just implement countdowntimer and start MainActivity when the timer ends.
Hope this helps, Good Luck ^^

try to use this way first need to load xml layout
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_banner);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
or try to put in manifest like
<activity
android:name=".BannerActivity"
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen"
>

you can do like this also in your Banner Activity
use this code in oncreate method in banner activity
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
finish();
}
}, 2000);

You need splash screen. Try this:
Start BanerActivity first. And make its onCreate like
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Thread welcomeThread = new Thread() {
int wait = 0;
#Override
public void run() {
try {
super.run();
while (wait < 5000) { //Wait of 5 seconds
sleep(500);
wait += 500;
}
} catch (Exception e) {
} finally {
Intent i = new Intent(BanerActivity.this,
MainActivity.class);
startActivity(i);
finish();
}
}
};
welcomeThread.start();
}
Hope this helps.

the easiest solution is to make the BannerActivity the launcher activity and modify the CountDownTimer to be
#Override
public void onFinish()
{
Intent mainIntent = new Intent(this, MainActivity.class);
startActivity(mainIntent);
finish();
}
then adjust the manifest file to make the BannerActivity as the launcher activity and remove it from the MainActivity

Related

Interstitial Ad not show in splash screen activity

I'm trying to integrate Interstitial Ad in splash screen activity
by using this tutorial
.. but the ad not loading.
can anyone tell me where is the problem please?
thanks in advance
here is my code :
public class SplashScreenActivity extends Activity {
private InterstitialAd mInterstitialAd;
private Timer waitTimer;
private boolean interstitialCanceled;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId(getString(R.string.interstitial_full_screen));
mInterstitialAd.setAdListener(new AdListener()
{
#Override
public void onAdLoaded() {
if (!interstitialCanceled) {
waitTimer.cancel();
mInterstitialAd.show();
}
}
#Override
public void onAdFailedToLoad(int errorCode) {
startHomeMain();
}
});
waitTimer = new Timer();
waitTimer.schedule(new TimerTask() {
#Override
public void run() {
interstitialCanceled = true;
SplashScreenActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
startHomeMain();
}
});
}
}, 5000);
} // end of onCreate implementation.
private void startHomeMain() {
Intent intent = new Intent(this, HomeMain.class);
startActivity(intent);
finish();
}
#Override
public void onPause() {
waitTimer.cancel();
interstitialCanceled = true;
super.onPause();
}
#Override
public void onResume() {
super.onResume();
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else if (interstitialCanceled) {
startHomeMain();
}
}
}
I'm trying to integrate Interstitial Ad in splash screen activity
by using this tutorial
.. but the ad not loading.
can anyone tell me where is the problem please?
thanks in advance
Google ads takes minimum 6 seconds to Load , and in your code you have set timer of 5 seconds , so thats why your Splash screen activity finished but ad not shown
try to set timer of greater than 6 seconds , and display add on destroy method of activity.
Remove timer and add progress dialogue and in onAdLoaded Dismiss dialogue and show ad as well as Dismiss dialogue in onFailedtoLoad

calling a method after starting an activity

I'm making an Android whack a mole game. I have the main activity which is basically the launcher, when you press the Play button the game activity starts. This works fine as it shows the background image and all molehills but I don't know how to call the method to start the game.
I've tried to call it from inside onCreate() but this ends up "playing the game" itself.
I've tried to call it right after the startActivity(intent) but the app crashes. And also I've tried to create an instance of the game class and call the play() method after the start activity but it doesn't work aswell. I don't know how to start the game method once the game activity is loaded.
I hope I explained well, thank you.
public class MainActivity extends AppCompatActivity {
ImageButton btnStart;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hide TitleBar
try { this.getSupportActionBar().hide();}
catch (NullPointerException e){}
setContentView(R.layout.activity_main);
btnStart = (ImageButton)findViewById(R.id.btnStart);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), GameView.class);
startActivity(intent);
}
});
}
And this is the code for the game_activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hide TitleBar
try { this.getSupportActionBar().hide();}
catch (NullPointerException e){}
setContentView(R.layout.activity_game_view);
game();
}
The game() method is a typical game loop.
public void game() {
Random random = new Random();
int index;
/*
* Casting array to store all ImageView on the game
*/
imgViewArray[0] = (ImageView)findViewById(R.id.img1);
imgViewArray[1] = (ImageView)findViewById(R.id.img2);
imgViewArray[2] = (ImageView)findViewById(R.id.img3);
imgViewArray[3] = (ImageView)findViewById(R.id.img4);
imgViewArray[4] = (ImageView)findViewById(R.id.img5);
imgViewArray[5] = (ImageView)findViewById(R.id.img6);
imgViewArray[6] = (ImageView)findViewById(R.id.img7);
imgViewArray[7] = (ImageView)findViewById(R.id.img8);
imgViewArray[8] = (ImageView)findViewById(R.id.img9);
imgViewArray[9] = (ImageView)findViewById(R.id.img10);
int j=0;
while (j < 10) {
// Get a random image to animate
index = random.nextInt(10);
switch(index) {
case 0: imgViewArray[0].setImageResource(images[6]);
new java.util.Timer().schedule(
new java.util.TimerTask() {
#Override
public void run() {
imgViewArray[0].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imgViewArray[0].setImageResource(images[0]);
}
});
}
},
300 // The code executes after 300ms
);
break;
I think you should put the game() call inside onResume().
There are many ways to solve the problem:
Using EventBus
Send the start game Event from Main Activity and register for the Event in the Game activity.
This is my favorite way to handle the problem. It's because the simplicity and prevent us from tightly coupled code. The major problem with using EventBus is we will lost in the sea of Event if there are too much Event in the the app.
How to do:
First, create the Event. This is just a simple class:
public class StartGameEvent {
}
Second, register for the event in the game activity:
public class GameActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
EventBus.getDefault().register(this);
}
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
}
Third, subscribe for the event:
public class GameActivity extends Activity {
...
#Subscribe
public void onMessageEvent(StartGameEvent event) {
game();
}
}
Last, send the event from Main activity:
EventBus.getDefault().post(new StartGameEvent());
Using LocalBroadcastManager
You need to create the message and broadcast it in from your Main activity:
Intent intent = new Intent("playEvent");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
Then, in the game activity, you need to register as receiver:
#Override
public void onCreate(Bundle savedInstanceState) {
// register for the event
LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver,
new IntentFilter("playEvent"));
}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
game();
}
};
#Override
protected void onDestroy() {
// Unregister here
LocalBroadcastManager.getInstance(this)
.unregisterReceiver(mReceiver);
super.onDestroy();
}
I slightly modifying the code from How to use LocalBroadcastManager? for your case.
Using a static method in Game activity
This is the simplest way but highly discouraged. Because we can't ensure the state of the activity. Do not use this in production code. This is for learning sake only.
You can make the game() method as a static method like this:
public class GameActivity extends Activity {
...
public static void game() {
// game logic.
}
}
Then call the method when you want with:
GameActivity.game();

background music doesn't stop if app is onStop Android

I have created a service to play music through my activities. I Have 2 activities and a splashScreen. I start the service from the first acitivity and by clicking some items I go to the second activity. The music is played properly but when I put my app in background or I lock my phone or I'm in another app I still hear the sound. I cannot put stopService in onStop because if I go to my second activity, the music will stop.
Here's my service music class :
public class BackgroundMusicService extends Service {
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.game_music);
player.setLooping(true);
player.setVolume(10, 10);
player.start();
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}
and :
public class Activity1 extends AppCompatActivity implements View.OnClickListener{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_1);
Intent backgSound = new Intent(Activity1.this, BackgroundMusicService.class);
startService(backgSound);
Button b1 = (Button) findViewById(R.id.b1);
b1.setOnClickListener(this);
}
#Override
public void onDestroy() {
super.onDestroy();
Intent backgSound = new Intent(Activity1.this, BackgroundMusicService.class);
stopService(backgSound);
}
#Override
public void onClick(View v) {
startActivity(new Intent(this,Activity2.class);
}
And the second activity is just a view (for test).
How could I keep the sound over these 2 activites and stop it when my app is in background or my phone is locked.
I've tried to stopService in onStop then startService in onResume, but it does not work between activities.
Judging by what you want you need a more fine grained control over the starting and stopping of your MediaPlayer object. An easy solution would be to add intent-filters and actions like so:
public class BackgroundMusicService extends Service {
public static final String ACTION_START_MUSIC = "package_name.action_start_music";
public static final String ACTION_STOP_MUSIC = "package_name.action_stop";
private MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.game_music);
player.setLooping(true);
player.setVolume(10, 10);
}
public int onStartCommand(Intent intent, int flags, int startId) {
if(intent.getAction() != null){
switch (intent.getAction()){
case ACTION_START_MUSIC :
if(!player.isPlaying()){
player.start();
}
break;
case ACTION_STOP_MUSIC :
if(player.isPlaying()) {
player.stop();
}
break;
default: break;
}
}
return START_STICKY;
}
#Override
public void onDestroy() {
player.release();
}
#Override
public void onLowMemory() {
}
}
Update your manifest :
<service android:name=".BackgroundMusicService"
android:exported="false">
<intent-filter>
<action android:name="package_name.action_start_music" />
<action android:name="package_name.action_stop" />
</intent-filter>
</service>
To use:
startService(new Intent(BackgroundMusicService.ACTION_START_MUSIC));
startService(new Intent(BackgroundMusicService.ACTION_STOP_MUSIC));
It is well known that onDestroy() is not always calling, moving your onDestroy actions to the onPause() method will work:
Note: do not count on this method being called as a place for saving data! For example, if an activity is editing data in a content provider, those edits should be committed in either onPause() or onSaveInstanceState(Bundle), not here. This method is usually implemented to free resources like threads that are associated with an activity, so that a destroyed activity does not leave such things around while the rest of its application is still running. There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it, so it should not be used to do things that are intended to remain around after the process goes away.
More info here.
You need to read more about the basics of Android.
Regards.

Check if app is open during a GCM onMessage event?

I am wondering how to check if my application is open and currently visible to the user when receiving an onMessage() from GCM. At first, I was just using my own boolean isVisible, but then I realized this isn't reliable, because if the app isn't open, the object I use to access that flag is null. While this in itself could be used to see if the app is open, it seems a little bit messy. Is there a way in Android from a system level to somehow check if the application is currently open, and if the user is viewing the app? Keep in mind an app could technically be running, but not be visible, because a user has recently pressed the "home" button sending it to the background.
#Override
protected void onMessage(Context arg0, Intent arg1) {
String turn = intent.getExtras().getString("turn");
if (turn.equals("yours"){
if (/*app is open*/){ <------------------ what can go here?
// dont generate a notification
// display something in the game instead
}
else{
// generate notification telling player its their turn
}
}
}
I would use order broadcasts to do that.
In your onMessage method:
Intent responseIntent = new Intent("com.yourpackage.GOT_PUSH");
sendOrderedBroadcast(responseIntent, null);
In your Activity:
public class YourActivity extends Activity {
final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Right here do what you want in your activity
abortBroadcast();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//.....
}
#Override
protected void onPause() {
unregisterReceiver(mBroadcastReceiver);
super.onPause();
}
#Override
protected void onResume() {
IntentFilter filter = new IntentFilter("com.yourpackage.GOT_PUSH");
filter.setPriority(2);
registerReceiver(mBroadcastReceiver, filter);
super.onResume();
}
}
The other BroadcastReceiver
public class SecondReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//In this receiver just send your notification
}
}
Manifest:
<activity
android:name=".YourActivity"
android:label="#string/app_name">
<intent-filter>
<action
android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".SecondReceiver">
<intent-filter
android:priority="1">
<action
android:name="com.yourpackage.GOT_PUSH" />
</intent-filter>
</receiver>
Basically in the onMessage method you send an Intent which is first received by the BroadcastReceiver registered inside YourActivity if it is running and in foreground, otherwise it is received by the SecondReceiver.
Use SharedPreferences saving the boolean isVisible, and when you get the value from the preference you can add a default value.
SharedPreferences settings = context.getSharedPreferences("NAME_XXX", Activity.MODE_PRIVATE);
settings.getBoolean("visible", false);
What I always do is have a reference to the current Activity.
I set the current Activity in every onResume to this and set it to null in every onPause.
If the current Activity is null then the app is not open. If it's not null you can see if the correct Activity is open and deliver it to that Activity.
GCMIntentService:
public static Activity currentActivity;
public static final Object CURRENTACTIVIYLOCK = new Object();
#Override
protected void onHandleIntent(Intent intent) {
synchronized(CURRENTACTIVIYLOCK) {
if (currentActivity != null) {
if (currentActivity.getClass() == CorrectActivity.class) {
CorrectActivity act = (CorrectActivity)currentActivity;
act.runOnUiThread(new Runnable() {
public void run() {
// Notifiy activity
}
});
} else {
// show notification ?
}
} else {
// show notification
}
}
}
CorrectActivity:
#Override
protected void onResume() {
synchronized (GCMIntentService.CURRENTACTIVITYLOCK) {
GCMIntentService.currentActivity = this;
}
}
super.onResume();
}
#Override
protected void onPause() {
synchronized (GCMIntentService.CURRENTACTIVITYLOCK) {
GCMIntentService.currentActivity = null;
}
super.onPause();
}
The thing that worked for me:
Create a final Class Constants, inside it, create static varaiable:
public final class Constants{
public static AppCompatActivity mCurrentActivity;
}
Now, on each on resume of your activties say:
#Override
protected void onResume() {
super.onResume();
Constants.mCurrentActivity = this;
}
When receieving notification, check if current activity is null, if its null, application is not opened, if activity isn't null, you can check things like:
if(Constants.mCurrentActivity instanceof MainActivity){
((MainActivity) Constants.mCurrentActivity).yourPublicMethodOrStaticObject;
}

Android: onTouchEvent start new activity

I have been searching for a while now but can't find a working solution for my android code. Well at least one I am able to implement.
I have an activity (StartActivity) with a few animations. Then I have an onTouchEvent. This works fine to prompt a few more animations however after this I want to open a new Activity.
Here is my code:
public class StartActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start);
RunAnimations(R.anim.translate1, R.anim.translate2);
}
public void RunAnimations(int t1, int t2) {
Animation a = AnimationUtils.loadAnimation(this, t1);
a.reset();
Animation b = AnimationUtils.loadAnimation(this, t2);
b.reset();
ImageView drop = (ImageView) findViewById(R.id.drop);
ImageView iflush = (ImageView) findViewById(R.id.iflush);
drop.clearAnimation();
iflush.clearAnimation();
drop.startAnimation(a);
iflush.startAnimation(b);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
RunAnimations(R.anim.translate3, R.anim.translate4);
}
return true;
}
}
In the onTouchEvent, after calling RunAnimations, I want to start a new activity (TipActivity). That is all.
Add another activity to you AndroidManifest file like so:
<activity
android:label="YourActivity"
android:name=".YourActivity" >
<intent-filter >
<action android:name="net.learn2develop.YourActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
And then you could do something like (after calling RunAnimations()) :
startActivity(new Intent("net.learn2develop.YourActivity"));
Hope that helps.
Use that:
Intent intent=new Intent(context, TipActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.translate3, R.anim.translate4);
^-^

Categories