Deactivate SplashScreen after start - java

When i start my application comes a SplashScreen for 3 seconds after that i am on my MainActivity when i press now the back button from my mobile im back on the SplashScreen. How can i adjust when i press the back button that, that close the app?
I have programmed this
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == event.KEYCODE_BACK){
if (!pressedOnce){
pressedOnce = true;
Toast.makeText(getApplicationContext(), "Erneut drücken,um zu beenden.", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
pressedOnce = false;
}
}, 3000);
}else if (pressedOnce){
pressedOnce = false;
onBackPressed();
}
return true;
}
return super.onKeyDown(keyCode, event);
}

Start your MainActivity from the Splash screen with a flag and finish the splash Activity:
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();

When you launch Intent to start your MainActivity write this.finish() to terminate SplashScreen activity and to remove it from your heap

Put finish(); after the startActivity code where you start MainActivity in SplashScreen.class.

Related

Android Studio on click button after a splash screen and a main screen [duplicate]

I have an application in which I'm receiving a sms containing his location.On receiving sms it calls another activity to start and passes that location to that activity to plot it on the map.Before calling the second activity it shows a toast like notification on the screen but somehoe due to calling second activity that toast doesn't come up.My question is how can we delay the calling of second activity from this activity ?
You can use something like this:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i=new Intent(SearxhJobs.this,JobsTypes.class);
startActivity(i);
}
}, 5000);
Here it waits upto 5 seconds to launch activity.
Hope it helps
You can do it with a Handler like this
Handler h = new Handler(){
#Override
public void handleMessage(Message msg) {
Intent i = new Intent().setClass(ctx, MainActivity.class);
startActivity(i);
}
};
h.sendEmptyMessageDelayed(0, 1500); // 1500 is time in miliseconds
Make an AsyncClass that does Thread.sleep() in the doInBackground() method, then navigate to your new activity in the your onPostExecute() method.
Call your toast message and then execute the AsyncClass.
For Kotlin
Handler().postDelayed({
val i = Intent(this, MainActivity::class.java)
startActivity(i)
}, 5000)
Try:
Runnable r = new Runnable() {
#Override
public void run() {
// if you are redirecting from a fragment then use getActivity() as the context.
startActivity(new Intent(SplashActivity.this, MainActivity.class));
// To close the CurrentActitity, r.g. SpalshActivity
finish();
}
};
Handler h = new Handler();
// The Runnable will be executed after the given delay time
h.postDelayed(r, 1500); // will be delayed for 1.5 seconds
Simply set the layout!
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
setContentView(R.layout.next); //where <next> is you target activity :)
}
}, 5000);
An example would be the following:
Handler TimeDelay=new Handler();
if(previous=="geofence"){
tts.speak(previous,TextToSpeech.QUEUE_ADD,null, null);
Runnable r = new Runnable() {
#Override
public void run() {
/*
Intent intent = new Intent(
MyBroadcastMessageReceiver.class.getName());
intent.putExtra("some additional data", choice);
someActivity.sendBroadcast(intent);*/
tts.speak(previous,TextToSpeech.QUEUE_ADD,null, null);
}
};
TimeDelay.postDelayed(r, 150000);

Problem with startService. How to fix it?

I have a start activity which is using services to play a background sound and after 5 seconds another activity is loaded.
The problem is in the second activity the sound doesn't load or service doesn't work... i'm not sure what is happening.
Sound works in the first activity when the app start.
here is the first activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//remove window title and make it fullscreen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//bind activity
setContentView(R.layout.start_activity);
ButterKnife.bind(this);
Intent intent = new Intent(StartActivity.this, SoundService.class);
intent.putExtra("filename", "audiostart");
//start service and start music
startService(intent);
int TIME_OUT = 5000;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(StartActivity.this, AvatarsActivity.class);
startActivity(i);
finish();
}
}, TIME_OUT);
Log.d(TAG, "APP Started!");
}
#Override
protected void onDestroy() {
//stop service and stop music
stopService(new Intent(StartActivity.this, SoundService.class));
super.onDestroy();
}
and the second activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.avatars_activity);
ButterKnife.bind(this);
Intent intent = new Intent(AvatarsActivity.this, SoundService.class);
intent.putExtra("filename", "audioavatars");
//start service and start music
startService(intent);
}
#Override
protected void onDestroy() {
//stop service and stop music
stopService(new Intent(AvatarsActivity.this, SoundService.class));
super.onDestroy();
}
here is the service:
#Override
public IBinder onBind(Intent intent) {
return null;
}
public void onCreate() {
player = MediaPlayer.create(this, R.raw.audio);
player.setLooping(false);
}
public int onStartCommand(Intent intent, int flags, int startId) {
if(intent != null){
String mFilename = intent.getStringExtra("filename");
Toast toast = Toast.makeText(getApplicationContext(), "Filename: " + mFilename, Toast.LENGTH_SHORT);
toast.show();
}
player.start();
return Service.START_NOT_STICKY;
}
public void onDestroy() {
player.stop();
player.release();
stopSelf();
super.onDestroy();
}
I want a background sound when the second activity loads after 5 seconds passed in first activity.
And a second problem is that i want to pass a variable in onCreate method in service with what sound to play depending on the activity. (This task i think i can do it but doesn't hurt to ask opinions how to do it)
Your code seems fine. But have you registered your service in your manifest file? Please check your manifest. Your service is not registered can be possible cause.
You are starting second activity after 5sec delay and immediately, after you queue start intent, you call finish() on first activity which will trigger onDestroy callback of the same activity. In onDestroy() of that 1st activity you implemented stop service, which causes service to stop.
Remove that implementation of onDestroy() in both activities and provide to user a way to stop service explicitly (clicking on a button or whatever) instead of doing it in a activity lifecycle callback.

"New Game" button deleting Android game progress

It's been a month since I started learning Java/Android Studio so I apologise beforehand for any silly questions.
I am currently making a simple riddle game with Android Studio - a question is asked, and the right answer gets you to the next activity/question. So, my main menu consists of a Start Interrogation button and a Continue button. Using SharedPreferences I managed to make the game "save progress" so it can get you to the last question you couldn't answer; but my problem comes with the Start Interrogation button. Whenever it is pressed and starts a new game, the continue button will still get you to the last question asked before.
So in simple terms, I want to make the New Game button delete the progress made until then. The only thing that comes to mind is to try and delete the SharedPreferences whenever the button is pressed, but I fail to write such code.
Any tips on what should I do? Help is greatly appreciated. Here's the Java code of my MainMenu.
MainMenuWithLogo.Java
public class MainMenuWithLogo extends AppCompatActivity {
private Button mStartInterrogationButton;
private VideoView mLogoprwto;
private Button mContinueButton;
MediaPlayer song;
#Override
protected void onPause() {
super.onPause();
song.release();
}
#Override
public void onResume() {
super.onResume();
setContentView(R.layout.activity_main_menu_with_logo);
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
song = MediaPlayer.create(this, R.raw.chopin);
song.start();
song.setLooping(true);
mLogoprwto = (VideoView) findViewById(R.id.logoprwto);
mLogoprwto.setVideoPath("android.resource://its_destination/"+R.raw.teloslogo);
mLogoprwto.start();
mLogoprwto.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mLogoprwto.start();
}
});
mStartInterrogationButton = (Button)findViewById(R.id.StartInterrogationButton);
mStartInterrogationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
startGame();
}
});
mContinueButton = (Button)findViewById(R.id.ContinueButton);
mContinueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences prefs = getSharedPreferences("Stage", MODE_PRIVATE);
boolean question00Answered = prefs.getBoolean("QuestionZero", false);
boolean question01Answered = prefs.getBoolean("QuestionOne", false);
boolean question02Answered = prefs.getBoolean("QuestionTwo", false);
if (!(question00Answered)) {
Intent intent = new Intent(MainMenuWithLogo.this, QuestionZero.class);
startActivity(intent);
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
finish();
} else if (!(question01Answered)) {
Intent intent = new Intent(MainMenuWithLogo.this, QuestionOne.class);
startActivity(intent);
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
finish();
} else if (!(question02Answered)) {
Intent intent = new Intent(MainMenuWithLogo.this, QuestionTwo.class);
startActivity(intent);
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
finish();
}else {
Intent intent = new Intent(MainMenuWithLogo.this, End.class);
startActivity(intent);
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
finish();
}
}
});
}
private void startGame () {
Intent intent = new Intent(this, Intro.class);
startActivity(intent);
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
finish();
}
#Override
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
You can use SharedPreferences.Editor.remove() to delete items saved to SharedPreferences using the item's key. So, when you start a new game, call this to delete the user's progress. Or, if you want to remove ALL the stuff in SharedPreferences, call SharedPreferences.Editor.clear().

Stop/Pause/Sleep Service if connection unavailable and resume if available

I have an application in which I have created a service MyService.class
Now MyService.class is tied to my activity using bindService() but I want my service to run in the background even if activity destroys itself.
So I started the service and then bind it like below:
private void doBindService() {
if (!isServiceBound){
Log.d(LOG_TAG, "Binding Service...");
if (mBtAdapter != null && mBtAdapter.isEnabled()){
Intent intent = new Intent(MyActivity.this, MyService.class);
startService(intent);
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
}
}
}
In MyActivity's onDestroy method I am unbinding the service
Now my service is running smoothly until the connection with the remote device breaks. I want to pause/sleep/stop this service if connection breaks, then after every 60 seconds it tries to start the service/connection.
I have tried this but doesn't work.
private void stopService() {
doUnbindService();
stopService(new Intent(MyActivity.this, MyService.class));
startService(new Intent(MyActivity.this, MyService.class));
}
Please any help will be much appreciated. Thanks in advance!!!
Try this
create a method that perform the Operation you want
create a Thread or Runnable class
Call the Helper method you created in the run() of the Thread or Runnable
Inside the Service onStartCommand start the Thread if connection is available
thread.wait/sleep if no connection
I'm not sure I have understanding your request.
With this solution you can play, pause and stop service.
And the service do some work every 60seconds
public class MyService extends Service {
public static boolean testConnexion;
private Timer timer;
#Override
public void onCreate() {
super.onCreate();
timer = null;
testConnexion = true;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (timer != null) {
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
if (testConnexion) {
//StartConnexion
}
}
}, 1000, 60000);
}
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
timer.cancel();
}
}
In Any activity
To start or stop service.
(Your can call startService many times as you want, there will be just one who will run.)
if (v.getId() == R.id.startService) {
Intent intent = new Intent(this, MyService.class);
startService(intent);
} else if (v.getId() == R.id.stopService) {
Intent intent = new Intent(this, MyService.class);
stopService(intent);
}
To pause action (but not kill the service)
MyService.testConnexion = false;
And for restarting
MyService.testConnexion = true;
Your service is not related to your activity.
If your killing your activity, your service continues to run.
I hope this can help you

After SplashScreen finish() app gets minimized

I'm using finish() to end a thread in my SplashScreen activity and when I do the app gets minimized before going to Activity2. How can I end the SplashScreen activity and go to Activity2 without calling finish() so the app won't minimize?
public class SplashScreen extends Activity {
/**
* The thread to process splash screen events
*/
private Thread mSplashThread;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Splash screen view
setContentView(R.layout.splash);
final SplashScreen sPlashScreen = this;
// The thread to wait for splash screen events
mSplashThread = new Thread(){
#Override
public void run(){
try {
synchronized(this){
// Wait given period of time or exit on touch
wait(5000);
}
}
catch(InterruptedException ex){
}
finish();
// Run next activity
Intent intent = new Intent();
intent.setClass(sPlashScreen, MainActivity.class);
startActivity(intent);
//stop();
}
};
mSplashThread.start();
}
/**
* Processes splash screen touch events
*/
#Override
public boolean onTouchEvent(MotionEvent evt)
{
if(evt.getAction() == MotionEvent.ACTION_DOWN)
{
synchronized(mSplashThread){
mSplashThread.notifyAll();
}
}
return true;
}
}
call finish after startActivity
mSplashThread = new Thread(){
#Override
public void run(){
try {
synchronized(this){
// Wait given period of time or exit on touch
wait(5000);
}
}
catch(InterruptedException ex){
}
// Run next activity
Intent intent = new Intent();
intent.setClass(sPlashScreen, MainActivity.class);
startActivity(intent);
//call finish after startActivity
finish();
//stop();
}
};
mSplashThread.start();
I do it like this:
private class IntentLauncher extends Thread {
#Override
/**
* Sleep for some time and than start new activity.
*/
public void run() {
try {
// Sleeping
Thread.sleep(SLEEP_TIME*1000);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
// Start main activity
Intent intent = new Intent(SplashActivity.this, MainActivity.class);
SplashActivity.this.startActivity(intent);
SplashActivity.this.finish();
}
}

Categories