I currently confused on how I can display my dialog only if the application is first time to load only with orientation change. I have only one activity composed of tabs.
Problem:
I tried using boolean variables and preferences but I can't figure out on where to place them in cases where the activity's view is being destroyed. Destroyed is either by exiting the app or orientation change. Secondly, during orientation changes the dialog should be showed again on first time, but the even if I dismiss dialog and do orientation change - the dialog is displayed again which should not happen. I prefer not using the onConfigurationChanged(Configuration).
boolean FirstTimeActivityOpened = true;
boolean dialogDismissed = false;
boolean orientationChanged = false;
++++++++++
if(FirstTimeActivityOpened && dialogDismissed && orientationChanged ){
loadDialog(this);
}
new OrientationEventListener(MainActivity.this,
SensorManager.SENSOR_DELAY_NORMAL){
#Override
public void onOrientationChanged(int orientation) {
// TODO Auto-generated method stub
orientationChanged = true;
//Toast.makeText(MainActivity.this, "onOrientationChanged"+ orientation, Toast.LENGTH_SHORT).show();
}};
loadDialog
dialog.setOnDismissListener(new OnDismissListener(){
#Override
public void onDismiss(DialogInterface arg0) {
// TODO Auto-generated method stub
dialogDismissed = true;
Toast.makeText(MainActivity.this, "Dialog Dismissed", Toast.LENGTH_SHORT).show();
}});
+++++++++++++
#Override
public void onDestroy() {
super.onDestroy();
if(dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
//or
if(dialog != null) {
dialog.dismiss();
}
}
I found out during my study:
FirstLoad:
onCreate()
onStart()
onResume()
Change or Orientation:
onPause()
onStop()
onDestroy()
onCreate()
onStart()
onRestoreInstantState()
onResume()
Activity not visible but not destroyed
onPause()
onStop()
Activity opened from Pause State:
onRestart()
onStart()
onResume()
Activity not visible and destroyed:
onPause()
onStop()
onDestroy()
Activity Destroyed and Re-opened
onCreate()
onStart()
I think you should store them in shared preferences so that you don't lose them when you restart your application or when the activity reloads.
Edit :
First of all, add this line to your manifest if it is not already done :
android:configChanges="orientation"
Adding this won't let your activity restart when the orientation changes.
In that case, you can set your FirstTimeActivityOpened to true at the beggining of the onCreate() method of your activity and you can set it to false in onDestroy().
Now, you already know when the orientation changes. So when it changes, you just have to prompt your dialog IF it is the first time your app is opened.
Hope this helps
Related
I've implemented something similar to Android notification of screen off/on, but it's not working the way it should. All I want to do is stop music when the screen is turned off. I created a screen action class like this
public class ScreenAction extends BroadcastReceiver {
public static boolean wasScreenOn = true;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// DO WHATEVER YOU NEED TO DO HERE
wasScreenOn = false;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// AND DO WHATEVER YOU NEED TO DO HERE
wasScreenOn = true;
}
}
}
Then, in my main activities on create I have this
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenAction();
registerReceiver(mReceiver, filter);
In my main activities onPause, I have something like this:
public void onPause() {
super.onPause();
if (ScreenAction.wasScreenOn) {
final MediaPlayer mp = MediaPlayer.create(this, R.raw.pcmouseclick1);
mp.setVolume(.1f, .1f);
mp.start();
if (buttonState) {
mServ.reduceVolume();
}
}
}
I found this from an online source, but I am having issues. It seems that the screen state is always set as true, and I'm not sure how to change this.
How do I utilize this ScreenAction class to turn off music in on Pause ONLY when the user has locked the screen? I feel like I am missing something in the onPause because in onCreate I link to the class.
#Override
protected void onPause() {
// when the screen is about to turn off
// or when user is switching to another application
super.onPause();
}
#Override
protected void onResume() {
// only when screen turns on
// or when user returns to application
super.onResume();
}
Here you can see the entire lifecycle of an Activity in android:
Activity Lifecycle
Maybe you could also start and stop your music directly from the receiver:
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// Pause music player
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// Resume music player
}
}
You're checking ScreenAction.wasScreenOn in onPause, but that's happening before the BroadcastReceiver is called to notify you that the screen is being turned off. So at that point, ScreenAction.wasScreenOn is still true, and then it's set to false, but onPause has already run, so your music never gets paused.
To solve this, you should take the action directly in response to the screen turning off in the BroadcastReceiver. If you need to interact with your UI, consider a solution like LiveData as an abstraction so that you're not reliant on your Activity being paused at the exact moment the screen is turned off (consider also that the onPause solution wouldn't work if your Activity weren't currently visible).
I'm building an app that plays music on the background with service. The music is muted when the user is not in the app and unmuted when he is back. I used the onPause() and onResume() methods to do this.
The problem is - every time the user enters a new activity, the music pauses for a second and then resumes, because for a second the current activity is paused.
another problem - for the first run of the activity, the onResume() and onCreate() both works, which makes my service stops from the onResume() without it even being created from the onCreate() (which makes the app shut down).
is there a way to use onPause() without the intent part (or another similar way?)
is there a way to use onCreate() without to onResume() on the first run?
protected void onCreate(Bundle savedInstanceState) {
counter++;
if (counter==1) {
alliesSPEditor.putBoolean("isAllies", true);
alliesSPEditor.commit();
startService(new Intent(this,MusicService.class));
}
#Override
protected void onPause() {
super.onPause();
MusicService.getMP().mute();
}
#Override
protected void onResume() {
super.onResume();
if (counter!=1) //because the counter is still 1, the app won't shut down this way but it will not unmute the music.
MusicService.getMP().unMute();
}
onResume() is always called after onCreate() before the activity starts running
See https://developer.android.com/guide/components/activities/activity-lifecycle
I see some ways to solve this:
the problem is - every time the user enters a new activity, the music pauses for a second and then resumes, because for a second the current activity is paused
The first is you set a flag in the handler that start your new activity and
check in your onPause() method the value of de flag, if false, do nothing othewise mute de music.
public static boolean openOtherActivity = false;
#Override
protected void onPause() {
super.onPause();
if (!openOtherActivity) {
MusicService.getMP().mute();
}
}
You can use Preferences too if you preferrer
To resolve de onCreate() and onResume() problem, you can use the same logic
creates a flag for the services started and control when you needs unmute the music in anothers methods
public static boolean isServiceCreated = false; // In your activity that start the service
protected void onCreate(Bundle savedInstanceState) {
counter++;
if (counter==1) {
alliesSPEditor.putBoolean("isAllies", true);
alliesSPEditor.commit();
startService(new Intent(this,MusicService.class));
isServiceCreated = true; // set the flag to true
}
}
OnResume() method you can check if the service is started an create your logic
I have kind of a game with 2 activities: Start Activity (with high score, start button and tutorial button) and main game activity which is is based on countdown timer, when time is up, game returns to start activity.
Problem is when user starts game and then hits home button and goes back to home screen (just leaving game by home button) Everything is ok until time is up, then Start activity appears on screen with lost message.
I've tried various combined methods like onPause witch finish(); inside and so on but it doesn't work or causes app force close.
I can't handle home button click like in onBackPressed() which I did in that case.
Is there any way to suspend app and pause all threads while it isn't in foreground?
I suggest two way
1
Create global variable like
private isInForgrand = false;
And in onStop() or onPause() and onResume() change it
#Override
public void onStop() {
isInForgrand = false;
super.onStop();
}
#Override
public void onResume() {
super.onResume();
isInForgrand = true;
}
And in onFinish() check it
#Override
public void onFinish() {
if(isInForgrand){
//do what you want
}else{
//your app NOT in Forgrannd
}
2
You can cancel CountDownTimer in onStop()
#Override
public void onStop() {
super.onStop();
mCountDownTimer.cancel();
}
i want to restart an activity when i make changes to wifi settings menu if connection is disabled.
this is my code (onCreate method):
boolean status = ConnectionManager.getConnectivityStatusString(this);
if(status){
networkStatus.setText("SEI CONNESSO AD INTERNET !");
}else{
networkStatus.setText("connection not present");
FragmentManager fragmentManager = getSupportFragmentManager();
MsgAlertConnection newAlertConnection = new MsgAlertConnection();
newAlertConnection.show(fragmentManager, "Fragment");
}
and this is the code that show a dialog :
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
// 1. Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// 2. Chain together various setter methods to set the dialog characteristics
builder.setTitle("Connection Error !")
.setMessage("Please check your Internet Connection for start the application.")
.setPositiveButton("Back to Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent=new Intent();
intent.setComponent(new ComponentName("com.android.settings", "com.android.settings.WirelessSettings"));
startActivity(intent);
}
});
// Create the AlertDialog object and return it
return builder.create();
}
when a user change the wifi network on "ON", how i restart or resume the application for check network connection ?
Thanks
I think that if you need to restart the activity - then something is wrong with your design - anyway
startActivity(getIntent());
finish();
this will do the trick
With onRestart method
protected void onRestart() {
super.onRestart();
}
Call recreate() from the activity
public void recreate ()
Cause this Activity to be recreated with a new instance. This results in essentially the same flow as when the Activity is created due to a configuration change -- the current instance will go through its lifecycle to onDestroy() and a new instance then created after it.
Try to put the first block of code in onResume() method.
When back from WirelessSettings to the activity, the onResume method was called and assign a new value to status var.
Try this one.
#Override
protected void onResume() {
super.onResume();
notify("onResume");
}
or
#Override
protected void onStart() {
super.onStart(); // Always call the superclass method first
// The activity is either being restarted or started for the first time
// so this is where we should make sure that GPS is enabled
LocationManager locationManager =
(LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!gpsEnabled) {
// Create a dialog here that requests the user to enable GPS, and use an intent
// with the android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS action
// to take the user to the Settings screen to enable GPS when they click "OK"
}
}
#Override
protected void onRestart() {
super.onRestart(); // Always call the superclass method first
// Activity being restarted from stopped state
}
Please Visit this link.
http://developer.android.com/training/basics/activity-lifecycle/stopping.html
I read that after a screen rotation, an android activity is created again. I understood how to recover a view, but i don't understand if i can start from where a method was stopped after a screen rotation.
Recover after screen rotation.
In it's simplest form you save what you need to recreate where you left off in the onSaveInstanceState method. So for your basic flashlight you save the state of the light. For you more complex apps your saving all of the global fields. Flashlight has a global variable isFlashOn.
private boolean isFlashOn = false;
save the state of the flashlight in the onSaveInstanceState
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(ISON, isFlashOn);
}
Then in the oncreate method you recreate the global variable.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
isFlashOn = savedInstanceState.getBoolean(ISON);
}
later in the onstart method process the isFlashOn. This flashlight is turned on by a click so I change the state of isFlashOn and call the click handler.
#Override
protected void onStart() {
super.onStart(); // Always call the superclass method first
if (camera == null) {
camera = Camera.open();
}
//flip the isflashon and then click the button
isFlashOn = !isFlashOn;
onClick(null);
}
process the click.
public void onClick(View arg0) {
ImageButton i = (ImageButton) findViewById(R.id.imageButton1);
final Parameters p = camera.getParameters();
if (isFlashOn) {
i.setImageResource(R.drawable.ic_launcher);
isFlashOn = false;
p.setFlashMode(Parameters.FLASH_MODE_OFF);
} else {
i.setImageResource(R.drawable.ic_launcher2);
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
// Set flag to true
camera.startPreview();
isFlashOn = true;
}
Good Luck
If there was a method that was executing at the moment you turned your screen, the method will finish its work.
It wont be paused or anything else since its "impossible" to do that.
If that particular method was important to your app/activity you should then call it again upon Activity recreation.