I want to show toast on every life cycle but upon running the application the OnStart and OnCreate gets skipped and OnResume only runs, same with other life cycle methods. But whenever II remove the OnResume, OnStart is firing but onCreate is not.
EDIT:
this code works, but I run the application on my smartphone which is Xiaomi.
Tried running on emulator and everything works, correct me if I'm wrong
my code:
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
//launch
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(getApplicationContext(), "Created!", Toast.LENGTH_LONG).show();
}
#Override
public void onStart() {
super.onStart();
Toast.makeText(getApplicationContext(), "Started!", Toast.LENGTH_LONG).show();
}
#Override
public void onResume() {
super.onResume();
Toast.makeText(getApplicationContext(), "Resume!", Toast.LENGTH_LONG).show();
}
//stopping
#Override
public void onPause() {
super.onPause();
Toast.makeText(getApplicationContext(), "Pause!", Toast.LENGTH_LONG).show();
}
#Override
public void onStop() {
super.onStop();
Toast.makeText(getApplicationContext(), "Stop!", Toast.LENGTH_LONG).show();
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(getApplicationContext(), "Destroy!", Toast.LENGTH_LONG).show();
}
#Override
public void onRestart() {
super.onRestart();
Toast.makeText(getApplicationContext(), "Restart!", Toast.LENGTH_LONG).show();
}
}
EDIT: this code works, but I run the application on my smartphone which is Xiaomi. Tried running on emulator and everything works, correct me if I'm wrong
Related
When I run this app I am getting "On Resume" first instead of "On start" even "On create" not showing up, please tell me why? and "On Restart" toast is not displaying but test is getting updated.
public class MainActivity extends AppCompatActivity {
public int test=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast t=Toast.makeText(getApplicationContext(),"On create",Toast.LENGTH_SHORT);
t.setGravity(Gravity.CENTER_VERTICAL,20,20);
t.show();
}
#Override
protected void onRestart() {
super.onRestart();
Toast t=Toast.makeText(getApplicationContext(),"On restart",Toast.LENGTH_LONG);
t.setGravity(Gravity.CENTER_VERTICAL,20,20);
TextView num=(TextView) findViewById(R.id.textNum);
test++;
num.setText(String.valueOf(test));
t.show();
}
#Override
protected void onStart() {
super.onStart();
Toast.makeText(getApplicationContext(),"On start",Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
super.onResume();
Toast t=Toast.makeText(getApplicationContext(),"On resume",Toast.LENGTH_SHORT);
t.setGravity(Gravity.CENTER_VERTICAL,10,20);
t.show();
}
#Override
protected void onPause() {
super.onPause();
Toast t= Toast.makeText(getApplicationContext(),"On Pause",Toast.LENGTH_SHORT);
t.setGravity(Gravity.CENTER_VERTICAL,20,20);
t.show();
}
#Override
protected void onStop() {
super.onStop();
Toast.makeText(getApplicationContext(),"On Stop",Toast.LENGTH_SHORT).show();
}
#Override
protected void onDestroy() {
super.onDestroy();
Toast.makeText(getApplicationContext(),"On destroy",Toast.LENGTH_SHORT).show();
}
}
Using Toast as a debugging method is really bad idea. Use logging and look at your logcat. You will see that the methods get called in the order that they should. Just don't do this.
I have an android studio project. When I am rotating screen, android destroys and recreates main activity. How can I check during the destruction, if android going to recreate activity?
You can determine if the activity is finishing by user choice (user chooses to exit by pressing back for example) using isFinishing() in onDestroy.
#Override
protected void onDestroy() {
super.onDestroy();
if (isFinishing()) {
// wrap stuff up
} else {
//It's an orientation change.
}
}
Another alternative (if you're only targeting API>=11) is isChangingConfigurations.
#Override
protected void onDestroy() {
super.onDestroy();
if (isChangingConfigurations()) {
//It's an orientation change.
}
}
Override the Activity lifecycle methods to see the flow.And then use the appropriate method to check activity current state like isChangingConfigurations()
Example code snippet.
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onStart() {
super.onStart();
Log.i(MainActivity.class.getSimpleName(),"OnStart Called");
}
#Override
protected void onRestart() {
super.onRestart();
Log.i(MainActivity.class.getSimpleName(),"OnRestart Called");
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.i(MainActivity.class.getSimpleName(),"OnDestroy Called");
}
#Override
protected void onPause() {
super.onPause();
Log.i(MainActivity.class.getSimpleName(),"OnPause Called");
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Log.i(MainActivity.class.getSimpleName(),"OnConfiguration Changed Called");
}
}
For more details see the official page activity-lifecycle
I was doing an application which uses some Toasts.
If a Toast appears and in the meanwhile I quit the app, it normally doesen't disappear.
Is there a way to stop the Toast if I quit the app on my phone?
In Activity onStop or ondestroy use cancel() method
public class MainActivity extends Activity {
private Toast toast = null;
#SuppressLint("ShowToast")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_LONG);
showMyToast();
}
public void showMyToast()
toast.setText(" test toast");
toast.show();
}
#Override
protected void onStop () {
super.onStop();
toast.cancel();
}
while quitting from add need to write this
toast.cancel();
Toast.makeText returns a Toast object. Call cancel() on this object to cancel it.
Toast toast = Toast.makeText(this, "Hello..", Toast.LENGTH_LONG);
toast.cancel();
use android activity life-cycle and override onstop() or onPause mthodes
onPause() called when activity is not visible to the user.
onStop() called when activity is no longer visible to the user.
#Override
protected void onPause () {
super.onPause();
toast.cancel();
}
or
#Override
protected void onStop () {
super.onStop();
toast.cancel();
}
I want to implement some sort of a monitor function, that tells me when my app is crashed or stopped or on pause. So I have 3 activities and I achieved so far that when in the mainActivity onPause is called it will send me a mail, however, I only want to know if someone stops the whole app and not just one of the activities (since the user jumps between them). Is there some kind of an overall onStop() Method or something that I can use?
Thanks !
This is my code
protected void onStop() {
super.onStop();
new Thread(new Runnable() {
public void run() {
try {
GMailSender sender = new GMailSender(
"email address",
"pw");
sender.sendMail("Pause", "The app has paused",
"email address",
"email address");
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
}
}
}).start();
}
Maybe create three Booleans... activityOneAlive, activityTwoAlive, and activityThreeAlive. When each activity hits onStart(), it writes true, and right before switching to a different activity in your app, it sets its own Boolean to false. When any activity hits onPause(), and its Boolean is true, then send your email.
Add a private field to your Activity class:
private userIsLeavingActivity = false;
public onStart(){
...
userIsLeavingActivity = false;
...
}
public onbackPressed(){
...
userIsLeavingActivity = true;
...
}
public onUserLeaveHint(){
...
userIsLeavingActivity = true;
...
}
public onPause(){
if(isFinishing()){
// activity is finishing, not just paused.
}
}
public onStop()
{
if(userIsLeavingActivity){
// do what you want going to another activity or app
}
else{
// your activity is being stopped by something else
}
You could this into a master Activity then extend your other activities from this. Of course, I've left out the super() calls and so on. Needs some adaptation but you should be able to combine all of these to determine exactly why your activity is pausing or stopping.
The problem you now need to solve is a universal exception catch. See this question.
Create an Application class and in there, create an object that implements the ActivityLifecycleCallbacks interface. In that object, increment an integer in every onStart, and decrement it in every onStop. Also in onStop, if the integer is 0, then send your email.
http://developer.android.com/reference/android/app/Application.ActivityLifecycleCallbacks.html
package com.your.package;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.os.Build;
import android.os.Bundle;
public class ExampleApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
setupLifecycleCallbacks();
}
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread paramThread, Throwable paramThrowable) {
sendEmail();
}
});
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void setupLifecycleCallbacks() {
registerActivityLifecycleCallbacks( new ActivityLifecycleCallbacks() {
int mActivityCount = 0;
#Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
#Override
public void onActivityStarted(Activity activity) {
mActivityCount++;
}
#Override
public void onActivityResumed(Activity activity) {
}
#Override
public void onActivityPaused(Activity activity) {
}
#Override
public void onActivityStopped(Activity activity) {
mActivityCount--;
if (mActivityCount == 0){
sendEmail();
}
}
#Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
#Override
public void onActivityDestroyed(Activity activity) {
}
});
}
private void sendEmail() {
new Thread(new Runnable() {
public void run() {
try {
GMailSender sender = new GMailSender(
"email address",
"pw");
sender.sendMail("Pause", "The app has paused",
"email address",
"email address");
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
}
}
}).start();
}
}
I want to set up the background music of my app so that it will keep playing while I am on the app, and pause when I press the home button. The problem is that if I pause the music when the phone goes to the home screen, it also pauses the music when I go to a different activity within my app. Is there a way to keep the music playing while I switch activities (e.g. I have a menu, from which I can open different screens in my app, and the music stops playing as soon as the phone leaves the menu screen). My code is as follows:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(Menu.this, android.R.layout.simple_list_item_1,
classes));
mp = MediaPlayer.create(Menu.this, R.raw.music);
mp.start();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onStop() {
super.onStop();
mp.pause();
}
#Override
protected void onResume() {
super.onResume();
mp.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
mp.release();
finish();
}
}
You can create a Service that will keep the music playing on the background
Sample code:
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
public class PlayAudio extends Service{
private static final String LOGCAT = null;
MediaPlayer objPlayer;
public void onCreate(){
super.onCreate();
Log.d(LOGCAT, "Service Started!");
objPlayer = MediaPlayer.create(this,R.raw.sleepaway);
}
public int onStartCommand(Intent intent, int flags, int startId){
objPlayer.start();
Log.d(LOGCAT, "Media Player started!");
if(objPlayer.isLooping() != true){
Log.d(LOGCAT, "Problem in Playing Audio");
}
return 1;
}
public void onStop(){
objPlayer.stop();
objPlayer.release();
}
public void onPause(){
objPlayer.stop();
objPlayer.release();
}
public void onDestroy(){
objPlayer.stop();
objPlayer.release();
}
#Override
public IBinder onBind(Intent objIndent) {
return null;
}
}
For more details, please refer here.
I see 2 different solutions:
Create a class that extends Application and put your music player there.
Create a Service that will read the music on the background