How to detect if whole application is close in android - java

Some times application be closed by pressing home button and onDestroy() doesn't call. I want to call a method when whole application is closed and I'm not going to call my method in all activities's onDestroy().

implements LifecycleObserver inside appication class an then use as blow:
public class App extends Application implements LifecycleObserver{
#SuppressLint("CheckResult")
#OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onMoveToForeground() {
}
#SuppressLint("CheckResult")
#OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onMoveToBackground() {
}
}
Also can use other events like Lifecycle.Event.ON_DESTROY or ON_CREATE

Application does not close on home button press.But it goes in background.
When you Application goes in background(Your front activity goes in background) it calls onStop() Method(Activity is not visible now).So you should do all stuff here.
There is no such call back the Application class. Which tell you that application is destroyed.
If you want to fire an event when application is fully closed.You should check your application's activity stack.If it does not have any activity than your application is closed. You should check it from a service.

Related

onBackPress in Service

I need to somehow press the back button, but do it programmatically, without pressing the physical button, or play finish(), only in another application.
I found this: Trigger back-button functionality on button click in Android, but this reproduces the click from activity, and I need from service
public class AutoService extends AccessibilityService {
#Override
public void onBackPressed(){
super.onBackPressed();
}
}
Error, writes that there is no such method

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.

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"));

Should DialogFragment be called through AsyncTask class?

I read many guides but I'm still confused.
Somewhere I read that the "activity flow" should not be interrupted by a DialogFragment, so you should call DialogFragment inside a AsyncTask Class inside the Activity Class.
In other guides I saw DialogFragment being called from the Activity Class without using AsyncTask.
So my question is: should DialogFragment be called only through AsyncTask class?
This is the way I did so far; the Activity class code:
public class LunchActivity extends AppCompatActivity {
....
public void callDialog(){
class ShowInfoToUser extends AsyncTask<Bundle, Void, Bundle> {
...
#Override
protected Bundle doInBackground(Bundle... args) {
...
}
#Override
protected void onPostExecute(Bundle resultBundle) {
DialogFragment permissionDialogManager= permissionDialogManager.newInstance(messageBundle);
permissionDialogManager.show(activity.getSupportFragmentManager(), "Permission Dialog");
}
}
}
This is the class that extends DialogFragment:
public class PermissionDialogManager extends DialogFragment {
public static PermissionDialogManager newInstance(Bundle bundle) {
PermissionDialogManager frag = new PermissionDialogManager();
frag.setArguments(bundle);
return frag;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
...
}
}
Thank you
The code inside AsyncTask's onPostExecute method execute in the UI Thread. In the example you have provided, there is not difference if you use AsynTask or not, because the code will be executed in the UI Thread.
Maybe in the example you have seen, they process some information in the AsyncTask's doInBackground method (that execute in separate thread) and later in the onPostExecute method they use the previous information to invoke the DialogFragment.
How to know when should you run code in the UI Thread?
Processes and Threads
When your app performs intensive work in response to user interaction, this single thread model can yield poor performance unless you implement your application properly. Specifically, if everything is happening in the UI thread, performing long operations such as network access or database queries will block the whole UI. When the thread is blocked, no events can be dispatched, including drawing events. From the user's perspective, the application appears to hang. Even worse, if the UI thread is blocked for more than a few seconds (about 5 seconds currently) the user is presented with the infamous "application not responding" (ANR) dialog. The user might then decide to quit your application and uninstall it if they are unhappy.
As the Dialog will interrupt the user, I see no reason to put it in an AsyncTask. The dialog is not supposed to take a huge amount of time to generate itself.

Google Play Game Services - Listener null pointer exception

I am still fairly new to Android and I am trying to implement Achievements inside my app. I basically want to replicate the achievements implemented in the "Type-a-Number Challenge" sample app given on the Google play developer site here.
I have a first activity that contains the methods and classes to handle the achievements, and a second activity where I have the variables that would be forwarded to the first activity for "processing". I copied the code that I believed was necessary for doing this, but I am always getting a null pointer exception when calling the listener inside the second class.
Here is my listener in the second activity:
public interface Listener {
public void onEnteredScore(int score);
}
Listener mListener = null;
public void setListener(Listener l) {
mListener = l;
}
The null pointer exception is flagged here when I call the listener as such (where mRequestedScore is different to 0):
mListener.onEnteredScore(mRequestedScore);
The first activity's class implements the second activity listener like this:
public class FirstActivity extends BaseGameActivity
implements SecondActivity.Listener
And includes the onEnteredScore method as such
#Override
public void onEnteredScore(int requestedScore) {
checkForAchievements(requestedScore);
pushAccomplishments();
}
I am not entirely sure if the error appears because the listener is expecting a click or some action by the user, or the "linkage" is not being established properly between both activities.
I looked around for similar issues but haven't found anything yet.
Apologies if the mistake is obvious.
Thanks in advance for any help provided.
Your "linkage" isn't established, hence the null.
If you want to pass data between Activities (not fragments), you'll need to use the Intent framework - see How do I pass data between Activities in Android application?
The Interface method that you are following in the Type a Number Challenge is useful for passing data between Fragments and the parent Activity. That is what it is being used for in that example. You don't appear to be using Fragments.
For achievements, you are probably better served using a class attached to your FirstActivity. That class can then implement your Listener interface (if the interface is even useful at that point). Using a separate activity is far more heavyweight than is required.

Categories