Here is my code:
public class SplashScreen extends Activity {
private ImageView poweredByImage;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN );
setContentView(R.layout.splash);
poweredByImage = (ImageView)findViewById(R.id.ImageView);
poweredByImage.setImageResource(R.drawable.powered_by);
this.handleAnimation(poweredByImage);
Handler handler = null;
handler = new Handler();
handler.postDelayed(new Runnable(){
public void run(){
Intent intent = new Intent(SplashScreen.this, HomeScreen.class);
startActivity(intent);
}
}, 3000);
}
public void handleAnimation(View v) {
v.startAnimation(AnimationUtils.loadAnimation(this, R.anim.fadein));
}
}
I navigate from one screen (SplashScreen) to another (HomeScreen), 3 seconds after the first one appears, but before that to happen I want to start the fade-in animation 1 second after it appears and then the transition to new screen to happen.
So how can I do it? What should I use? Any help will be useful!
Why don't you use your handler to post a Runnable responsible of starting the animation after 1000ms? You then post your second Runnable that start your HomeScreen activity after 3000ms like you are actually doing.
Related
I am trying to make app sleep using Thread. I have got 2 solutions but one of them causes a problem.
This is a shorter code which works perfectly:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
final Handler goToMenu = new Handler();
goToMenu.postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(getApplicationContext(), Menu.class);
startActivity(i);
}
},5000);
}
But this one is problematic. When I put the time in millis to make app wait it works and the second Activity starts but the R.layout.welcome does not appear. The app just waits with a gray background until the startActivity(i) gets executed.
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
final Handler goToMenu = new Handler() {
#Override
public void handleMessage(#NonNull Message msg) {
Intent i = new Intent(getApplicationContext(), Menu.class);
startActivity(i);
}
};
Runnable run = new Runnable() {
#Override
public void run() {
try {
synchronized (this) {
wait(5000);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "Waiting didnt work!!");
e.printStackTrace();
}
goToMenu.sendEmptyMessage(0);
}
};
Thread waitThread = new Thread(run);
waitThread.run();
What is wrong?
To start a new thread, use Thread#start() and not Thread#run().
run() just executes the Runnable synchronously i.e. blocking the current thread.
use
Handler.postDelayed(new Runnable(){}, DELAY_TIME) instead
for your case
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(getApplicationContext(), Menu.class);
startActivity(i);
}
}, 5000);
To Show thelayout, Activity's onCreate() method should run completely. In your second code there is a thread. That thread stops your code compilation for 5000 milliseconds. That means your second code stops and wait 5 seconds in wait(5000); line. Therefore onCreate() method not completes.
You have used Handler().postDelayed() your first code. This method don't stuck the code. It is a background task. it works synchronously.
I hope your answer is here.
Hello guys how are you today I hope you are OK
I have an application with many activity's :
Main-activity
activity1
activity2
activity3
what I need to do is make the activity3 popup every (x) minute, for example, every 2 or 3 minutes the activity3 popup how can I do that and thanks in advance.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//load the xml file for the starting loading screen
setContentView(R.layout.activity_main);
Log.d("MainActivity:", "onCreate: created activity_main.xml UI succesfully.");
new Timer().schedule(new TimerTask(){
public void run() {
startActivity(new Intent(MainActivity.this, PrimaryActivity.class));
finish();
Log.d("MainActivity:", "onCreate: waiting 5 seconds for MainActivity... loading PrimaryActivity.class");
}
}, 5000 );
}
}
I didn't know how to try this before posting so I need your help thanks in advance.
'Make the popup function static and call it with class name like'
yourclassname.popupFunction(Context);
'in on create method where you want to open the primary activity'
public static void popupFunction(Activity activity){
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(activity, PrimaryActivity.class));
finish();
Log.d("MainActivity:", "onCreate: waiting 5 seconds for MainActivity...
loading PrimaryActivity.class");
}
},5000);
}
'Hope you get the answer Thanks'
Whenever I try to exit from my app by pressing back button twice, splash screen appears and it freezes until i press back button again. So I need to press back button three times to exit from my app. Please help me to exit from app with only two back button press.
The java code in project as follows:
public void onBackPressed()
{
if (doubleBackToExitPressedOnce)
{
super.onBackPressed();
MapsActivity.this.finish();
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click Back again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable()
{
#Override
public void run()
{
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
my splash screen code as follows:
public class SplashScreen extends AppCompatActivity {
ImageView logoView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
Animation anim1 = AnimationUtils.loadAnimation(this,R.anim.anim_down);
logoView = findViewById(R.id.logoview);
logoView.setAnimation(anim1);
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
#Override
public void run()
{
Intent next_scrn = new Intent(SplashScreen.this,MapsActivity.class);
startActivity(next_scrn);
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
},2500);
}
}
you should to finish splashActivity after start new activity, so use :
handler.postDelayed(new Runnable()
{
#Override
public void run()
{
Intent next_scrn = new Intent(SplashScreen.this,MapsActivity.class);
startActivity(next_scrn);
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
SplashScreen.this.finish();
}
},2500);
Add finish(); after below code.
Intent next_scrn = new Intent(SplashScreen.this,MapsActivity.class);
startActivity(next_scrn);
You must finish() splash screen like as below than your condition on BackPress work
Intent next_scrn = new Intent(SplashScreen.this,MapsActivity.class);
startActivity(next_scrn);
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
finish();
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();
I have the following code that responds to a button click, changes the view and then after 5 seconds switches the view back:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
Button test = (Button)findViewById(R.id.browseLocation);
test.setOnClickListener(testListener);
}
private TimerTask revert = new TimerTask(){
#Override
public void run() {
setContentView(R.layout.menu);
}
};
private OnClickListener testListener = new OnClickListener() {
public void onClick(View v) {
setContentView(R.layout.test);
Timer tim = new Timer();
tim.schedule(revert, 5000);
}
};
However this code does not work. The run method of the timetask is hit but setContentView fails. I assume it has something to do with scope inside the timetask.
How can I achieve the desired result?
Try yourActivityName.this.setContentView(). Do you know if revert is being called at all (i.e. using Logging)?
Found on another post that setContentView cannot be called from a non-UI thread.
Can achieve the desired affect using runOnUiThread, but not recommended.