#override onResume used but screen resets - java

The java and/or XML file seems to reload on wake from pause but I thought #Override would stop that. How do I stop this from happening?
#Override
public void onPause() {
super.onPause();
Playsound2.stop();
}
#Override
public void onResume() {
super.onResume();
SoundManager.getInstance();
SoundManager.initSounds(this);
SoundManager.loadSounds();
}
Perhaps I was unclear. How do I stop the activity restarting on wakeup?

onResume Method will be called every time your activity gets Resumed. if you do not want that, use your code in some method of your own apart from activity because activity methods have a life cycle and they follow the same hierarchy.

#Override means you override the method from the parent class.
onResume is part of the Activity's lifecycle and will be called automatically.

Related

Android onCreate dont call

Need help!
I don’t understand why the onCreate method is not always called (it not activity).
If the program is stopped or forcibly stopped from the task manager, then run again in logcat I see that the OnCrete method is called normally.
But if you press the back button (or stop) and then run again, the creative method is no longer called. But at the same time, the creative method of the fragment is called normally, but not in the main class!
How can one be forced, or is there some way, to make oncrete always called up?
public class MyApplication extends MultiDexApplication
{
...
...
#Override
public void onCreate()
{
super.onCreate();
Log.v("CWF","----------------- BEGIN -------------------");
...
...
}
#Override
public void onTerminate()
{
}
#Override
public void onLowMemory()
{
super.onLowMemory();
}
#Override
public void onConfigurationChanged(Configuration newConfig)
{
}
my manifest
<application
android:name="com.sample.test.MyApplication"
android:icon="#mipmap/icon"
android:label="#string/app_name"
android:largeHeap="true"
android:restoreAnyVersion="true"
android:usesCleartextTraffic="true">
SYNTAX
#Override
public void onCreate() {
super.onCreate();
}
Question - > I don’t understand why the onCreate() method is not always called ?
onCreate() called when the application is starting, before any activity, service, or receiver objects (excluding content providers) have been created. Read official guideline about Application class.
Because oncreate called when the activity is first created.
This is lifecycle of activity
onStop() --->onRestart() --->onStart()
For more details refer Activity Life cycle
It's your application instance, not an Activity instance which is shown on the screen.
I mean when you move your app to background - app is not killed. It's just in background.
onCreate method is called when application is launching.
If you need some another trigger to know when app is on foreground use activities onResume callback method or lifecycle observer.

Passing custom parameters to a parent activity through onCreate method yields confusing linter error

Why does passing custom parameters to a parent activity through an onCreate method, while leaving overriding the root method to the parent, result in the following linter error:
Overriding method should call super.onCreate
Background
For example, I have a MainActivity class that extends from ParentActivity that extends Android's Activity.
UML Generator
In order to make my app more abstract I am trying to handle several things in ParentActivity that the developer need not see in their development and use of MainActivity.
I have several parameters I would like to pass to the ParentActivity, like booleans turning on and off log functionalities, but it seems passing them through the onCreate() method is not ~~possible~~ recommended since this throws linter errors. I will make a separate question regarding the best practices for passing such parameters upward to custom parent classes using custom methods or directly setting parent fields, but I was looking to verify my current understanding of why this is not ~~possible~~ recommended through the existing onCreate method and additional parameters.
What has been tried
As a starting point, if I have some basic MainActivity and ParentActivity:
Code 0.1
public class MainActivity extends ParentActivity{
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//Do stuff
}
}
public class ParentActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//Do stuff
}
}
and then try to add further parameters to onCreate, e.g. a boolean to turn on/off some logger functionality within ParentActivity:
Code 0.2
public class MainActivity extends ParentActivity{
boolean logOn = true;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState, logOn);
//Do stuff
}
}
public class ParentActivity extends Activity{
// No longer overriding Activity.onCreate() due to diff in params
protected void onCreate(Bundle savedInstanceState, boolean logOn){
super.onCreate(savedInstanceState);
//Do stuff
}
}
Android Studio first warns me that I am not overriding the parent's method, which makes sense as it has a different parameter count, but then I thought I can just remove the #Override and call it good since I'm still calling super.onCreate(savedInstanceState) in ParentActivity, which will pass the savedInstanceState up to Activity, and I'm still passing the savedInstanceState to ParentActivity from MainActivity. At this point I encountered my first unknown issue: back in MainActivity, I get a linter error that states
Overriding method should call super.onCreate
Whats confusing is that I do call super.onCreate(savedInstanceState, logOn) directly below where I get this error. Although the error message is not too informative, I can get rid of the error by calling super.onCreate(savedInstanceState) directly above the already existing call to super.onCreate(savedInstanceState, logOn), i.e.:
Code 0.3
public class MainActivity extends ParentActivity{
boolean logOn = true;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
super.onCreate(savedInstanceState, logOn);
//Do stuff
}
}
public class ParentActivity extends Activity{
// No longer overriding Activity.onCreate() due to diff in params
protected void onCreate(Bundle savedInstanceState, boolean logOn){
super.onCreate(savedInstanceState);
//Do stuff
}
}
Looking at the tooltip inline doc using Android Studio, I see that super.onCreate(savedInstanceState); is calling the onCreate method from Activity (i.e the parent class of ParentClass) and super.onCreate(savedInstanceState, logOn); is calling the onCreate method of ParentClass. With typical inheritance in mind, and matching parameter lengths and types, this makes sense.
What doesn't make sense to me is why I have to call the onCreate method of Activity in MainActivity. Why does the call to onCreate within ParentActivity not suffice? i.e. why does Code 0.2 throw the linter error:
Overriding method should call super.onCreate
? I note, as per the comment by #greeble31 that Code 0.2 compiles, and runs on my example smartphone, but the linter error remains.
I don't think it's too much to worry about, since the problem is limited to a lint warning. You just did something a little too complicated for the linter to follow; your program is not, in fact, incorrect.
You could suppress the warning (#SupressLint), or simply ignore it.
...I can just remove the #Override and call it good...
Not too sure I agree with you, there... Removing the #Override annotation can't really help anything; the linter/compiler still knows what's an override and what's not. I consider the annotation useful b/c the IDE will tell you if you think you're overriding a method, but you're actually not, i.e. due to a signature mismatch or something (as here).
SUGGESTED APPROACH
FWIW, I would've solved this problem a little differently. (Note that code 0.3 actually results in two calls to the base class onCreate(); that's probably illegal.) I would just change the method name (to reflect a semantic distinction between configuration and creation), and store some state information in the base class:
public class MainActivity extends ParentActivity{
boolean logOn = true;
#Override
protected void onCreate(Bundle savedInstanceState){
configure(logOn); //Required, per base class specification
super.onCreate(savedInstanceState);
//Do stuff
}
}
public abstract class ParentActivity extends Activity{
boolean logOn;
boolean configured = false;
/** Subclasses are obligated to call this before calling super.onCreate() */
protected void configure(boolean logOn)
{
this.logOn = logOn;
this.configured = true;
}
#Override
protected void onCreate(Bundle savedInstanceState){
if(!configured)
throw new IllegalStateException("configure() not called prior to onCreate()");
super.onCreate(savedInstanceState);
//Do stuff
}
#Override
protected void onDestroy() {
configured = false; //(just being pedantic)
}
}
It's really just a matter of taste.
Sometimes people don't realize that Android can spontaneously create Activities on its own, like when it restores the back-stack state of your app. (This is why you want to be able to serialize and deserialize your Activity state to/from the bundle; b/c your Activity might not be re-created using the same workflow that caused its creation the first time).
I don't think that's going to be an issue for you, though, since ParentActivity (which I've declared as abstract) is always going to be instantiated via a concrete subclass, and all subclasses are guaranteed to call configure() in their onCreate() methods. (IOW, ParentActivity wouldn't have a manifest entry, so the system is never going to try to instantiate a base-class ParentActivity by itself.)
Just something to be aware of. (You had logOn set to a constant value in MainActivity, so if you were planning on changing that dynamically based on the app state, before calling configure()/super.onCreate(), just bear in mind that -- if you don't take steps to prevent it -- that information could be lost when your app is restored to the foreground.)
IDE will check #CallSuper annotation when on compilation {#link Activity#onCreate}.

Why cache data is not deleting on app destroy

When I try using the code bellow in the onDestroy() method in MainActivity it seams it does not work. What I am doing wrong?
Code:
#Override
protected void onDestroy() {
super.onDestroy();
deleteCacheData();
}
public void deleteCacheData() {
File cacheDir = this.getCacheDir();
File[] files = cacheDir.listFiles();
if (files != null) {
for (File file : files) {
file.delete();
}
}
}
There is two cases with your code:
You can't reliably depends on the case that onDestroy() method will be called. Because there is no such guarantee that it will always be called by the system. Here the excerpt from onDestroy() documentation:
protected void onDestroy ()
Perform any final cleanup before an activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it), or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method.
Note: do not count on this method being called as a place for saving data! For example, if an activity is editing data in a content provider, those edits should be committed in either onPause() or onSaveInstanceState(Bundle), not here. This method is usually implemented to free resources like threads that are associated with an activity, so that a destroyed activity does not leave such things around while the rest of its application is still running. There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it, so it should not be used to do things that are intended to remain around after the process goes away.
Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.
You should call your deleteCacheData() before calling the super.onDestroy(). So, this is incorrect:
#Override
protected void onDestroy() {
super.onDestroy();
deleteCacheData();
}
this is the correct one:
#Override
protected void onDestroy() {
deleteCacheData();
super.onDestroy();
}
If you using Windows OS
Because In your Windows task manaegr one Process is Running when the android studio start or build run or stop named
Java Jmt first stop it then your can directly delete the both build folder not need to clear cache

How to wait for the service to load before starting the activity

The Service class will load a library and it takes about 4-5 seconds for the library to become ready. What is the best way to make MainActivity to keep checking on the status of a static boolean in Service class and do something when it's ready? I looked around and knew that using busy wait loop is bad.
The outline of my planned MainActivity is
onCreate - start the service
onResume - show the splash screen until a specific boolean in Service become true then switch to another fragment
You could use a broadcast receiver from the Service to your MainActivity which triggers a method inside the MainActivity... instead of constantly checking a static bool in the service.
But you want to be very sure to handle cases where it never loads for whatever reason, otherwise users will be staring at a splash screen forever.
Simple solution is Broadcast Reciever Try this
BroadcastReceiver broadCastNewMessage = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// do your stuff here
}
};
Now in onCreate() register this
registerReceiver(this.broadCastNewMessage, new IntentFilter("bcNewMessage"));
And in onDestroy()
unregisterReceiver(broadCastNewMessage);
Now Call this method from the service class where u want to update the activity
sendBroadcast(new Intent().setAction("bcNewMessage"));

Android: How to set a listener for Acivity.onNewIntent()?

I'm writting my own plug-in for an existing game engine (so to say it's 3rd-party lib in relation to the main application).
So, I have no access to the MainActivity sources.
Nevertheless I have to react somehow on main activity lifecycle events (onCreate, onDestroy, onPause, onResume, onNewIntent and some unimportant others).
Thanks to Application.ActivityLifecycleCallbacks, I have no problems with most of them.
The problem occurs with onNewIntent(). I can't find out a listener for this event and imagine a way to handle it.
Does anybody know how to catch onNewIntent event (surely, except overriding it)?
onNewIntent() works for singleTop or singleTask activities which already run somewhere else in the stack. if the MainActivity is not declared with singleTop or singleTask attributes, even if you use below code, it won't work:
#Override //won't be called if no singleTop/singleTask attributes are used
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// ...
}
To assure all setup logic hooked, it is best use onResume() by utilizing getIntent().
#Override
protected void onResume() { //will be called in any cases
super.onResume();
// getIntent() should always return the most recent
}

Categories