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.
Related
In android lifecycle, is there any unique method that gets called when the app is swiped from the recent app list? We initially thought we would use onDestroy but it gets called during other activities as well.
Add a service like below and start it. When app close onTaskRemoved run your code.
Manifest
<service
android:enabled="true"
android:name=".ExitService"
android:exported="false"
android:stopWithTask="false" />
Service class
public class ExitService extends Service {
#Override
public void onStartService() {}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
this.stopSelf();
}}
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"));
When we press this button
We see the apps which we didn't close, like this
But when we want to close an app from this screen (below image), the method onDestroy() isn't called, however the app is closed. I need to call onDestroy() when the app is closed in this way. How can I do this?
As specified in the Android documentation, it is not guaranteed that onDestroy() will be called when exiting your application.
"There are situations where the system will simply kill the activity's hosting process without calling this method"
https://developer.android.com/reference/android/app/Activity.html#onDestroy%28%29
Instead, you can create a service which will be notified when the Task your activities are running inside is destroyed.
Create the service class:
public class ClosingService extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
// Handle application closing
fireClosingNotification();
// Destroy the service
stopSelf();
}
}
Declare / register your service in the manifest (within the application tag, but outside any activity tags):
<service android:name=".services.ClosingService"
android:stopWithTask="false"/>
Specifying stopWithTask="false" will cause the onTaskRemoved() method to be triggered in your service when the task is removed from the Process.
Here you can run your closing application logic, before calling stopSelf() to destroy the Service.
You should read some info about Activity lifecycle. There is one thing about onDestroy method, it doesn't get called all time. You mustn't rely on it.
Specify please what are you trying to achive and I'll try to offer better solution.
Suggestion
So, if I understood you right, I can suggest one thing. Start a Service that will fire LocalBroadcast every N seconds (it's not really heavy to system). Register and BroadcastReceiver for this broadcast in Activities. This way you'll get true or false depending on if there is any BroadcastReceiver that can catch your LocalBroadcast. And if no receivers than check for some SharedPreferences value that indicates if Button was pressed.
More promising approach than using a bound service would be using activity lifecycle callbacks in the Application. Though the approach shown in the accepted answer would work but the service would be running in the background until the activity is terminated which is expensive. Instead, I would suggest the use of your implementation of Application.
1) Make a class extending Application, then use it by providing its name in the name attribute of Application tag in Manifest file
class MusicPlayerApplication: Application() {
private val TAG = MusicPlayerApplication::class.java.simpleName
override fun onCreate() {
super.onCreate()
registerActivityLifecycleCallbacks(object: ActivityLifecycleCallbacks {
override fun onActivityPaused(activity: Activity?) {
}
override fun onActivityResumed(activity: Activity?) {
}
override fun onActivityStarted(activity: Activity?) {
}
override fun onActivityDestroyed(activity: Activity?) {
Log.d(TAG, "onActivityDestroyed: ")
val activityName = activity!!.localClassName
}
override fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) {
}
override fun onActivityStopped(activity: Activity?) {
}
override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) {
}
})
}
}
AndroidManifest.xml
<application
android:name=".MusicPlayerApplication"
....
I have tested this approach using logcat, my onDestory is not getting called but onActivityDestroyed in the callback is getting called every time I kill the activity from RAM but this doc says that onActivityDestroyed would be called when onDestory of an activity is called but that doesn't seem to happen. However, I find this approach better than using services.
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
}
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.