how to check if android going to recreate activity or destroy? - android

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

Related

Music player - activity lifecycle

I have really hard time with background music in my app. I just want to play music in all activities - when I press home button I want to stop music. I want "stop or play" music button in all activities, but couldn´t make it work.
So I decided to make embarassing choice - play it only in 1 activitiy by
onCreate
backgroundmusic = MediaPlayer.create(StoryActivity.this, R.raw.creepy_music);
backgroundmusic.start();
onPause
#Override
protected void onPause() {
super.onPause();
backgroundmusic.release();
finish();
}
Can you please help me with easy activity lifecycle? So when a user presses home button - music will stop. When he will come back to app - music will be restored and this activity too (it is not MainActivity)
Thank you, guys
Here are the different LifeCycle states. Now to your answer,
#Override
protected void onStop() {
super.onStop();
backgroundmusic.pause();
length = backgroundmusic.getCurrentPosition();
}
#Override
protected void onResume() {
super.onResume();
backgroundmusic.seekTo(length);
backgroundmusic.start();
}
In public class MainActivity extends AppCompatActivity, It's the AppCompatActivity that is the main source of an Activity's functionality, hence in the above methods like super.onResume(); and super.onStop(); super refers to the AppCompatActivity class
assume that you can get the music service in the Application ,you may be looking for this :
public class MyApp extends Application{
MusicService musicService;
#Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
#Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
#Override
public void onActivityStarted(Activity activity) {
}
#Override
public void onActivityResumed(Activity activity) {
if(musicService==null) return;
if(!musicService.isPlaying()){
musicService.play();
}
}
#Override
public void onActivityPaused(Activity activity) {
if(musicService==null) return;
if(musicService.isPlaying()){
musicService.pause();
}
}
#Override
public void onActivityStopped(Activity activity) {
}
#Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
#Override
public void onActivityDestroyed(Activity activity) {
}
});
}
}
Hope this helps

How to play music only in foreground

I have trouble to play music across all activity, I had implement service and handle onPause to stop the music when going to background (not visible to user).
The problem is when i navigate to another activity, the onPause method is called that make my music stop. How to fix this issue? I need to play my music across all my activity in foreground only and dont wan to play it when the application in the background. Appeciate anyone know how to solve this.
This is my base activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startIntent = new Intent(getApplicationContext(), MusicService.class);
if(binder==null){
bindService(startIntent,this, Context.BIND_AUTO_CREATE);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if(binder.getMyService()!=null){
stopService(startIntent);
unbindService(this);
}
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onPause() {
super.onPause();
if(binder!=null) {
binder.getMyService().pauseMusic();
}
}
#Override
protected void onResume() {
super.onResume();
if(binder!=null){
binder.getMyService().resumeMusic();
}
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
binder = (MusicService.Binder) service;
}
#Override
public void onServiceDisconnected(ComponentName name) {
}
this is my mainactivity extends base activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startIntent = new Intent(MainActivity.this, MusicService.class);
startService(startIntent);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
public void how(View view) {
Intent intent = new Intent(this, AboutActivity.class);
this.startActivity(intent);
}
You could implement code that will track current activity in your app. (Good example: How to get current activity)
And stop music only when "current activity" is null.
PS: depending on your implementation of tracking current activity you might want to check current activity not onPause() right away but with some delay .
Don't stop the audio play in onPause() as Harin Kaklotar suggested. You can use his method of onDestroy() or you can have it in an asynchronous task and turn off the sound by using surfaceDestroyed(). You can refer the android documentation of AudioManager if you need anything else of the sort.
https://developer.android.com/reference/android/media/AudioManager.html
Hope I Helped :D
UPDATE
You can create a system to check if your app is in the foreground or background. This involves counting how many activities are paused. Add this to all your activities:
#Override
protected void onPause() {
super.onPause();
MainActivity.Pause++;
}
#Override
protected void onResume() {
super.onResume();
MainActivity.Pause--;
}
And in your MainActivty,
if (Pause == NUMBER_OF_ACTIVITIES) {
//PAUSE MUSIC HERE
}
You have to use ActivityLifecycleCallbacks to tell if you app is in the foreground or background.
For example:
public class DummyActivityLifecycleCallbacks implements ActivityLifecycleCallbacks {
#Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { }
#Override public void onActivityStarted(Activity activity) { }
#Override public void onActivityResumed(Activity activity) { }
#Override public void onActivityPaused(Activity activity) { }
#Override public void onActivityStopped(Activity activity) { }
#Override public void onActivityDestroyed(Activity activity) { }
#Override public void onActivitySaveInstanceState(Activity activity, Bundle savedInstanceState) { }
}
public class OnApplicationForegroundBackgroundEnterCallbacks extends DummyActivityLifecycleCallbacks {
private Listener listener;
private int activityStartStopCounter = 0;
public interface Listener {
public void onEnterForeground();
public void onEnterBackground();
}
public OnApplicationForegroundBackgroundEnterCallbacks(Listener listener) {
this.listener = listener;
}
#Override public void onActivityStarted(Activity activity) {
if(++activityStartStopCounter == 1) listener.onEnterForeground();
}
#Override public void onActivityStopped(Activity activity) {
if(--activityStartStopCounter == 0) listener.onEnterBackground();
}
}
Then in Application.onCreate call:
registerActivityLifecycleCallbacks(new OnApplicationForegroundBackgroundEnterCallbacks(this));

Handling rotation changes and user leaving activity

So I’ve got this Activity with a doSomething() method. This method must be called when the user leaves the Activity and resumes after a while. This code works fine. The problem is: When the user rotates the phone (orientation change), the method is also called. I don’t want the method to be called on Orientation Change. Here’s my Activity code
public class MainActivity extends AppCompatActivity
{
private static boolean callMethod=true;
#Override
protected void onResume() {
super.onResume();
if(callMethod)
doSomething();
}
#Override
protected void onPause() {
super.onPause();
callMethod=true;
}
private void doSomething()
{
Log.i(“doSomething()”,”Did something.”);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(callMethod)
doSomething();
}
}
Thanks in advance!
From API 13 you can use configChanges in manifest.
Add the following to the manifest. This prevents recreation of the activity on screen rotation:
<activity android:name=".Activity_name"
android:configChanges="orientation|keyboardHidden">
One note is after this, you should handle screen orientation change yourself. you should override the following function in your activity for that:
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){
setContentView(R.layout.layout_landscape);
}
else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
setContentView(R.layout.layout);
}
}
I see in your comment that you added the isChangingConfigurations() flag, which should do the trick, but you should persist that state rather than making it a static variable. Otherwise, if your process is killed when your app goes to the background you'll lose that state.
public class MainActivity extends AppCompatActivity {
private static final String KEY_CALL_METHOD = "key_call_method";
private boolean callMethod = true;
#Override
protected void onCreate(Bundle savedState) {
super.onCreate(savedState);
setContentView(R.layout.activity_main);
if (savedState != null) {
callMethod = savedState.getBoolean(KEY_CALL_METHOD);
}
}
#Override
protected void onResume() {
super.onResume();
if (callMethod) {
doSomething();
}
}
#Override
protected void onPause() {
super.onPause();
if (!isChangingConfigurations()) {
callMethod = true;
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(KEY_CALL_METHOD, callMethod);
}
private void doSomething() {
Log.i("doSomething()", "Did something.");
}
}

Kill single activity Android app

I'm an Android newbie. I'm writing an app to trace the Activity lifecycle using Log statements. I want to kill my app in order to see the onDestroy() event being called. I've added a button that calls finish to do this, but I've not been able to terminate the app. I've also tried System.exit(0), but my app won't terminate. What am I doing wrong?
public class MainActivity extends Activity {
private static final String LOG_DISPLAY = "DEBUG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(LOG_DISPLAY, "onCreate called");
}
#Override
protected void onPause() {
super.onPause();
Log.d(LOG_DISPLAY, "onPause called");
}
#Override
protected void onResume() {
super.onResume();
Log.d(LOG_DISPLAY, "onResume called");
}
#Override
protected void onStop() {
super.onStop();
Log.d(LOG_DISPLAY, "onStop called");
}
#Override
protected void onStart() {
super.onStop();
Log.d(LOG_DISPLAY, "onStart called");
}
#Override
protected void onRestart() {
super.onStop();
Log.d(LOG_DISPLAY, "onRestart called");
}
public void addListenerOnButton() {
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
finish();
//System.exit(0);
}
});
}
}
You must override onDestroy in order to check if it is called, and call your addListenerOnButton method too:
Try with this:
public class MainActivity extends Activity {
private static final String LOG_DISPLAY = "DEBUG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(LOG_DISPLAY, "onCreate called");
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.d(LOG_DISPLAY, "onDestroy called");
}
#Override
protected void onPause() {
super.onPause();
Log.d(LOG_DISPLAY, "onPause called");
}
#Override
protected void onResume() {
super.onResume();
Log.d(LOG_DISPLAY, "onResume called");
}
#Override
protected void onStop() {
super.onStop();
Log.d(LOG_DISPLAY, "onStop called");
}
#Override
protected void onStart() {
super.onStop();
Log.d(LOG_DISPLAY, "onStart called");
}
#Override
protected void onRestart() {
super.onStop();
Log.d(LOG_DISPLAY, "onRestart called");
}
public void addListenerOnButton() {
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
MainActivity.this.finish();
//System.exit(0);
}
});
}
}
First add missing onDestroy implementation to show you logs :
#Override
protected void onDestroy() {
Log.d(LOG_DISPLAY, "onDestroy called");
super.onDestroy();
}
Then simply open activity and exit it with hardware back button. You will see onDestroy logs.
You will have same effect calling finish() programmatically as well, just dont forget to place call to your addListenerOnButton somewhere within onCreate

Killing process in onPause()

I want to kill my Activity process when I pause it by answering a call or something like that
but when i try to start my app it closes instantly. Any solutions? Sample code below
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Things to do
}
//#Override
public void onPause() {
super.onPause();
android.os.Process.killProcess(android.os.Process.myPid());
}
You should implement a logical scenario based on activity's lifecycle methods.
update your code with
#Override
public void onPause() {
super.onPause();
this.finish();
}

Categories

Resources