Detect when application is back from background - android

I would like to know when my app is back from background. onResume() is not a good solution, because i have another activities beside the Main Activity, so it can back from background to each of them. The purpose is to use Google analytics and to know when a user is launching the app and also bring it back from the background.
Thank you all and much appreciation.

Create a common base class which extends Activity. Implement onResume() with the functionality you need. Then extend all of your other activities from this base class.
The onResume() in the base class should call super.onResume() and this should also be the first line in each of the individual activity onResume methods.
Base class
public class BaseActivity extends Activity
#Override
public void onResume(){
super.onResume();
// code to do your analytics stuff
}
Derived Activities
public class MainActivity extends BaseActivity
#Override
public void onResume(){
super.onResume();
// code for the individual activity
}

You can detect background application with ActivityManager.getRunningAppProcesses() which returns a list of RunningAppProcessInfo records. If your application is in the background check RunningAppProcessInfo.importance field equals to RunningAppProcessInfo.IMPORTANCE_BACKGROUND while RunningAppProcessInfo.processName is equals to your application package name.
More info:
http://developer.android.com/intl/es/reference/android/app/ActivityManager.RunningAppProcessInfo.html

The android.arch.lifecycle package provides an interface that let you know when the app is back from background.
Your application should implement the LifecycleObserver interface:
public class MyApplication extends Application implements LifecycleObserver {
#Override
public void onCreate() {
super.onCreate();
ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
}
#OnLifecycleEvent(Lifecycle.Event.ON_STOP)
private void onAppBackgrounded() {
Log.d("MyApp", "App in background");
}
#OnLifecycleEvent(Lifecycle.Event.ON_START)
private void onAppForegrounded() {
Log.d("MyApp", "App in foreground");
}
}
To do that, you need to add this dependency to your build.gradle file:
dependencies {
implementation "android.arch.lifecycle:extensions:1.1.1"
}
As recommended by Google, you should minimize the code executed in the lifecycle methods of activities:
A common pattern is to implement the actions of the dependent
components in the lifecycle methods of activities and fragments.
However, this pattern leads to a poor organization of the code and to
the proliferation of errors. By using lifecycle-aware components, you
can move the code of dependent components out of the lifecycle methods
and into the components themselves.
You can read more here:
https://developer.android.com/topic/libraries/architecture/lifecycle

Related

onResume() in BaseActivity is getting called in all the activities which extends BaseActivity

In my application, bluetooth device scanning code is written in onResume() method in BaseActivity.
I extended some activities with BaseActivity so, if I switch to any activities, bluetooth scanning is being done.
Is there any way to write onResume() in BaseActivity works only once? Please help me. Thanks in advance.
Thats how inheritance works. But you can overwrite the onResume in your subclas with an empty method.
#Override
public void onResume(){
// no super class is called
}
But i think there is something wrong with your program design.
try this:
public class BaseActivity extends AppCompatActivity {
static Boolean IsResumecalled = false;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
super.onResume();
if (!IsResumecalled) {
IsResumecalled= true;
//write your code here
}
}
}
Your active Bluetooth connection should not reside in the BaseActivity. It rather should bind itself on his onCreate() via bindService to the BluetoothService - so it does not matter if one Activity destroys itself and the next one is getting started, because the Service is not Acitivity-dependent.
Look here for the general android developer guide on BluetoothService
https://developer.android.com/guide/topics/connectivity/bluetooth.html
And and how to use Services namely the bounded Service
https://developer.android.com/guide/components/services.html
There are also google code examples which you can use as a guideline.
It's a bad idea to block the onResume() call since it's a important part of the lifecycle for example if you minimize and maximize the app.
Override onResume in your child activities but do not call super.onResume()
#Override
public void onResume(){
// super.onResume(); // do not call this line in your child activities
}

What is the best approach to call register/unregister eventbus on fragments?

I'm brand new using Event Bus from otto lib, So far I created a Event Bus Singleton class, which I'm using in several parts of my code. Now I'm working on a fragment view, But I still have a question, regarding:
When is the best time to register/unregister my event bus?
In a couple of posts I read that onStart() and onStop(), but without any specific reason why.
public class SomeFragment extends Fragment {
#Override
public void onStart() {
super.onStart();
EventBusSingleton.register(this);
}
#Override
public void onStop() {
super.onStop();
EventBusSingleton.unregister(this);
}
}
If I follow the same approach as in the activities doing the call onResume() and onPause() works fine as well.
public class SomeFragment extends Fragment {
#Override
public void onResume() {
super.onResume();
EventBusSingleton.register(this);
}
#Override
public void onPause() {
super.onPause();
EventBusSingleton.unregister(this);
}
}
What could be the potential risk(if exist) from each call way?
onPause()/onResume() is called when your activity does not have the focus anymore but could still be visible (think a dialog or alert on top of your activity).
onStop()/onStart() is called when your activity is not visible anymore.
Which one to use depends your use case. I believe it's not really a problem to have callbacks executed while in the paused state so I would just put the register/unregister in onStop()/onStart() but if you really want to make sure, you can put them in onPause()/onResume().
My problem was what my fragmets had two instances for bad coding, y delete de uneccesary instance and it solve the problem

Android - Display notification when application is in background

I am using AlarmManager to periodically check for new content at some endpoint, validate if the results coming from the endpoint are the same as the ones I already have on my app, and if its not the same create a notification for each item.
What i need to know is how should i make the alarms to start only when the application is paused or stopped and cancel the alarms when de application is started or resumed.
where should i start the alarms and where should i cancel them?
In Android Notifications Guideline it says (on chapter: When not to display a notification):
Don't create a notification if the relevant new information is currently on screen. Instead, use the UI of the application itself to notify the user of new information directly in context. For instance, a chat application should not create system notifications while the user is actively chatting with another user.
If I have the application open i just want to disable alarms, when the application is closed/paused i want to cancel everything.
You need to create a Custom Application with global state and implement your own onPause and onResume at Application Level.
Create your own subclass of Application like this:
public class MyApplication extends Application {
private static MyApplication sInstance;
public MyApplication getInstance(){
return sInstance;
}
#Override
public void onCreate() {
super.onCreate();
sInstance = this;
}
public void onStart() {
// TODO: Stop your notification.
}
public void onStop() {
// TODO: Start your notification.
}
}
Specify its name in your AndroidManifest.xml's tag:
<application
android:icon="#drawable/icon"
android:label="#string/app_name"
android:name="MyApplication">
Create a class to hold the counts of activities:
public class ActiveActivitiesTracker {
private static int sActiveActivities = 0;
public static void activityStarted()
{
if (sActiveActivities == 0) {
// TODO: Here is presumably "application level" resume
MyApplication.getInstance().onStart();
}
sActiveActivities++;
}
public static void activityStopped()
{
sActiveActivities--;
if (sActiveActivities == 0) {
// TODO: Here is presumably "application level" pause
MyApplication.getInstance().onStop();
}
}
}
Then create a base activity (or do that in every activity), simply call the activityStarted() and activityStopped() methods:
#Override
public void onStart() {
super.onStart();
ActiveActivitiesTracker.activityStarted();
}
#Override
public void onStop() {
super.onStop();
ActiveActivitiesTracker.activityStopped();
}
For more details about Custom Application, see this.
For more details about Android Application Level Pause and Resume, see this.
Hope this helps.
you can try using a service and override in it , the onTrimMemory method and show the notificaton when "level" is equal to TRIM_MEMORY_UI_HIDDEN
#Override
public void onTrimMemory(int level) {
super.onTrimMemory(level);
switch (level) {
case ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN:
break;
}
}
check the documentation for more info
http://developer.android.com/reference/android/content/ComponentCallbacks2.html#TRIM_MEMORY_UI_HIDDEN
I am not sure that this will be feasible within your project or if it will achieve what you hope to, however you could extend all of your activities from one base activity. In that base activity's onPause/onStop/onDestroy methods start the alarms and in that base activities onCreate/onStart methods cancel the alarms with the pending intent.
This will provide you with a set location from which you can handle your alarms if you have multiple activities from which the app may close.
You can learn more about the life cycle of activities here.

Connecting and Disconnecting sockets in android

iam doing a small chat app in android with socket .. I want the app in such a way that the socket should connect when we open the app and it should disconnect as soon as the user leaves the app..and the main thing is, it should be connected when user is at any activity in the app(example :profile, create groups or any activity other than conversation page) Like same thing in whatsapp and similar chat app..How this can be achieved?
thanks in advance
My trick, and I'm sure there are others, is to create an abstract BaseActivity with an activity counter and have all 'real' activities instantiate from this class:
abstract class BaseActivity extends Activity {
protected static int numForegroundActivities;
#Override
public void onStart() {
super.onStart();
numForegroundActivities++; // no need for thread sync
}
#Override
protected void onStop() {
super.onStop();
if (--numForegroundActivities == 0) {
doAppClosedCode(); // <----------------------------
}
}
}
// all instantiable activities should extends BaseActivity
class MainActivity extends BaseActivity ....
Hope it helps.
You can monitor when Activities are in the foreground by using this api:
Application.registerActivityLifecycleCallbacks
An Activity is in the foreground when onActivityStarted is called.

Android - execute code onResume and onPause for all the activities of the app?

I'm designing an architecture where the app needs to execute certain set of operations everytime it goes to background (onPause) and a set of operations everytime it comes back to foreground (onResume), irrespective of the activity (for all the activities). Is there a way with which I can achieve this, without having to call those methods in every activity class' onPause and onResume overrides?
Make your own class that extends Activity and add your desired behavior to its onPause and onResume methods.
Then you extend that class on your activities.
public class BaseActivity extends Activity {
#Override
protected void onPause() {
// ...
}
#Override
protected void onResume() {
// ...
}
}
public class Activity1 extends BaseActivity {
// ...
}
You could extends your Activities by a BaseActivity which extends Activity, and create the two methods onPause / onResume in it.
See this answer for more information.

Categories

Resources