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

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
}

Related

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

Detect when application is back from background

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

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.

which Operation will perform first in onStart or onCreate in Android

I want to perform one data base Operation once. I want to do this when My Activity is Visible. Where shall I puty my LoadDatabase() function
LoadDatabase();
this is my oncreate of activity
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.retrospectscan);
}
this is my onStart
#Override
protected void onStart()
{
super.onStart();
}
Where Shall I put my LoadDatabase Code ? So that It will operated only if activity is fully Visible.
If Any other Approach is there please help me.
The complete activity lifecycle is here:
Though loading from database may be lengthy task , you can try doing it in AsyncTask or in onStart.
You can also use it on onResume. This depends on your application use.
user2737044
use Application context and load your database in application context create().
2nd thing is that, In activity onCreate() call first then it will call onstart().

Need to put #Overrides Methods for Android Life Cycle in Each Class or Just in the Main Class

#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
notify("onCreate");
}
#Override
protected void onPause() {
super.onPause();
notify("onPause");
}
#Override
protected void onResume() {
super.onResume();
notify("onResume");
}
#Override
protected void onStop() {
super.onStop();
notify("onStop");
}
#Override
protected void onDestroy() {
super.onDestroy();
notify("onDestroy");
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
notify("onRestoreInstanceState");
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
notify("onSaveInstanceState");
}
I'm if right, these are the methods to handle the life cycle of an activity. My question is, do you need to put these methods in each class if you want to handle your app life cycle properly, or just in the main class?
They have to be implemented once per activity. The code of one activity won't be used in anotherone unless the second is a subclass of the first.
As an additional note, only onCreate must be implemented, the others are optional.
You only need to override the methods that you want to use.
If you don't need to perform any special functions in onDestroy(), for example, you don't need to override it in any of your Activities.
A good way to identify whether or not you need it is to look at what you have in those methods. If all you are doing is calling super, then you don't need to include that method in your Activity because the default behavior will work just fine for you.
If you want your app to develop some certain behavior that can be applied to some specific part of the life cycle you have to put those methods in each class Activity. Because of the inheritance that a class have if you want some specific behavior through all the app I recommend you to use the Application class that modifies all the subsequent Activities the only problem is that not all the normal methods of an activity life cycle are available.
Here is some reference about lifecycle in Application class:
https://www.inkling.com/read/programming-android-mednieks-1st/chapter-11/life-cycle-methods-of-the
The best example of the method you always have to override is onCreate() because here is where you add all the normal start up behavior of the views and logic in your activity.
If you are not very well acquainted with android life cycle I do not recommend you to override these methods because they can lead you to strange behavior in your app, that is for my personal experience.

Categories

Resources