I think this question may simple but I didn't find any solution for this,
I there any way in Android that if any one of an activity calls onPause() I need to show Toast message or any notification kind of thing need to show. Generally I want to get notified when activity calls onPause() but I need it in one place since I may have some 15 activity I don't want to add it in all the activity.
ex:If I have activity when any one of the activity calls onPause I need to get notified but that notification code should be in one place and we should not add any line of code onPause() Is it possible to do this.
Thanks.
Create a baseActivity, which has for example :
open class BaseActivity : AppCompatActivity() {
override fun onPause() {
super.onPause()
Toast.makeText(this, "notified", Toast.LENGTH_SHORT).show()
}
}
Then you can extends this in your activities and handle the on pause call in BaseActivity
If your minSdkVersion >= 14, you can use Application.ActivityLifecycleCallbacks: ActivityLifecycleCallbacks
You have to define a custom Application class and you can register for this callbacks afterwards:
public class MyApplication extends Application {
private class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
#Override
public void onActivityCreated(final Activity activity, final Bundle savedInstanceState) {
//nothing to do
}
#Override
public void onActivityDestroyed(final Activity activity) {
//nothing to do
}
#Override
public void onActivityPaused(final Activity activity) {
// TODO Do your stuff, e.g. show toast.
}
#Override
public void onActivityResumed(final Activity activity) {
//nothing to do
}
#Override
public void onActivitySaveInstanceState(final Activity activity, final Bundle outState) {
//nothing to do
}
#Override
public void onActivityStarted(final Activity activity) {
}
#Override
public void onActivityStopped(final Activity activity) {
}
}
private final LifecycleCallbacks callbacks;
public void onCreate() {
super.onCreate();
callbacks = new LifecycleCallbacks();
application.registerActivityLifecycleCallbacks(callbacks);
}
}
Create a BaseActivity which contain all the methods you want to use in all other activities.
Then extend every activity with BaseActivity to call onPause() method.
Related
As the title says, I want to get the reference of currently visible activity or you can say activity which is at the top of backstack from a class, I don't want to send activity reference to that class, because I am using that class from many activities and if I do, I have to pass activity reference from every activity which is a long process.
I already have seen many answers which are typecasting context reference to activity but it is not working.
If anyone has the idea of how to do that in a short way, then please share.
I don't know what you mean by "long process".
Normally, if the Activity is delegating work to another class, it needs to pass itself as a reference so that the delegate knows how to call back the Activity to report progress, etc. This is standard Android stuff. AsyncTask works like this (as an example).
However, if all you want to do is display a Dialog, then you can, instead, start an Activity that looks like a Dialog. This is also a pretty common Android solution. There are themes that you can apply to an Activity that make it look just like a Dialog.
I have found a way via we can do this, In your application class add: registerActivityLifecycleCallbacks(this will listen to all activity lifecycle methods), like this:
public class MyApplication extends Application {
public static Activity currentActivity=null;
#Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
#Override
public void onActivityCreated(#NonNull Activity activity, #Nullable Bundle bundle) {
}
#Override
public void onActivityStarted(#NonNull Activity activity) {
currentActivity=activity;
}
#Override
public void onActivityResumed(#NonNull Activity activity) {
}
#Override
public void onActivityPaused(#NonNull Activity activity) {
}
#Override
public void onActivityStopped(#NonNull Activity activity) {
}
#Override
public void onActivitySaveInstanceState(#NonNull Activity activity, #NonNull Bundle bundle) {
}
#Override
public void onActivityDestroyed(#NonNull Activity activity) {
}
});
}
}
And then use it like:
if (MyApplication.currentActivity!=null){
// your code here
}
Don't forget to add your application class to manifest:
<application
android:name=".MyApplication"
.../>
I would like to know if there's a way to differentiate when the onResume() method of an activity is called from the same app or a different application.
For example I would like to differentiate when my main activity's onResume() is called when I return to the app from Whatsapp or another activity of my app.
I know there's a way to do it with GET_TASKS permission but that method is deprecated and not recommended.
Thank you
It appears you want to know when app comes from the background to foreground in each Activity. This can be achieved using a class that extends the Application class and implements the ActivityLifecycleCallbacks interface. Firstly, here's the code for this class:
public class MyApplication extends Application implements ActivityLifecycleCallbacks {
public boolean appInBackground;
private Handler mHandler;
...
#Override
public void onActivityResumed(Activity activity) {
Log.i("Activity Resumed", activity.getLocalClassName());
mHandler.cancelCallbacksAndMessages(null);
appInBackground = false;
}
#Override
public void onActivityPaused(Activity activity) {
Log.i("Activity Paused", activity.getLocalClassName());
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
appInBackground = true;
}
}, 5000);
}
...
}
If you notice in above code we are basically giving the app a grace period of 5 seconds to switch from one activity to other. If it exceeds more than that, it means the app was in background. The above class will need to registered in the <application> tag of your manifest file under android:name:"" property as android:name:"MyApplication".
To use this in your activity, override the onPause():
private boolean resumedFromBg;
#Override
protected void onPause() {
super.onPause();
resumedFromBg = ((MyApplication) getApplication()).appInBackground;
}
Let me know if you run into any issues~
I just recently started learning how to build android apps, and encountered a problem:
I want, when users leave the app (go to the homescreen, multitask), and they return, that the app calls a certain method. How can I do that?
This problem is more tricky than it may look like. When you return to app after leaving it, then is called method onResume of activity which was active when app was interrupted. But same happens when you go from one activity to another (onResume of second activity is called). If you just call method from onResume, it will be called every time onResume of any activity is called.
Take a look at this solution...
First, you have BaseActivity which is extended by all activities that need to call that method:
abstract public class BaseActivity extends Activity implements IName {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
if (AppClass.getPausedActivity() != null) {
if (this.getClassName().equals(AppClass.getPausedActivity()))
//call specific method
}
AppClass.setPausedActivity("");
super.onResume();
}
#Override
protected void onPause() {
AppClass.setPausedActivity(this.getClassName());
super.onPause();
}
#Override
abstract public String getClassName();
}
As you can see it implements interface IName:
public interface IName
{
String getClassName();
}
BaseActivity in onPause (when it is interrupted) calls setPausedActivity method of AppClass which remembers last activity name that was interrupted. In onResume (when app and activity is continued) we compare name of current activity and last paused activity.
So, when app is interrupted, these names will be same because you paused one activity and you got back to the same one. When you call activity from some other activity these names will not be same and method will not be called.
Here is code for AppClass:
public class AppClass extends Application {
public static String pausedActivity;
public static String getPausedActivity() {
return pausedActivity;
}
public static void setPausedActivity(String _pausedActivity) {
pausedActivity = _pausedActivity;
}
}
Also, here is example of activity that extends BaseActivity:
public class MainActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
}
//here you set name of current activity
#Override
public String getClassName() {
return "MainActivity";
}
}
You are bound to the Activity lifecycle. You will need to implement corresponding logic to figure out if the user has been in your app before (i.e. using SharedPreferences).
Please please don't minus my question i confused when googling.
I used Android Tab Layout with Swipeable Views in my code for when user pressed setting button on an activity.
now I need send message from TopRatedFragment.java that extends from fragment to the activity that call the mainActivity of "Android Tab Layout with Swipeable Views".
You can do this by implementing a call back
create an interface first
public interface CommunicationInterface {
public void onSuccess();
public void onFailed();
}
then in your activity implement the interface
public class YourActivity extends ActionBarActivity implements CommunicationInterface {
//default functions
#Override
public void onSuccess() {
//stuff you want to do in the acivity
}
#Override
public void onFailed() {
//stuff you want to do in the acivity
}
}
Now in the fragment
public class yourfragment extends Fragment {
CommunicationInterface callback;
//stuffs that usually come in yor fragment and like OncreateView etc
#Override
public void onActivityCreated(#Nullable Bundle outState) {
super.onActivityCreated(outState);
//after all the stuff you want to do in your fragment then implement //call back function to communicate with the activity
callback= (CommunicationInterface) getActivity();
callback.onSuccess();//according to your purpose use where ever you like
callback.onFailed();//according to your purpose use where ever you like
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
callback= (CommunicationInterface) activity;
}
}
Take a close look on this reference:
Creating event callbacks to the activity
The android docs recommend using this pattern of having the parent activity implement an interface of the fragment (Basically calling methods on it)
class MyFragment extends Fragment {
interface Listener {
public void onSomeEvent();
}
private void somethingHappeninInTheFragment() {
// let the activity know
((Listener) getActivity()).onSomeEVent();
}
}
class MyActivity extends Activity implements MyFragment.Listener {
// etc
#Override
public void onSomeEvent() {
// handle the message from the fragment
}
}
Explained with a more concrete example here: http://developer.android.com/guide/components/fragments.html#EventCallbacks
Here's the solution:
Step 1 : From your fragment.
Intent i = new Intent(getActivity(), YourActivity.class);
i.putExtra("key", "Your value1");
i.putExtra("key2", "Your value2");
i.putExtra("key3", "Your value3");
getActivity().startActivity(i);
Step 2 : In your Activity where you want the result
Intent getResults = getIntent();
String firstValue = getResults.getStringExtra("key1");
String secondValue = getResults.getStringExtra("key2");
String thirdValue = getResults.getStringExtra("key3");
Use those values your needs are.
Hope this helps.. :)
Is there a way to register for an activity's events? I'm specifically interested in the onStart / onStop events, and I don't want to add special operations in the activity for that.
One way to get events from the lifecycle of other activities is to register your class as an Application.ActivityLifecycleCallbacks with the main Application instance and filter events for the Activity you're interested in.
This is a short example (you may want to register the callbacks from another method/class other than MainActivity.onCreate or you'll miss that message ;) and you may have a dependency there that you don't want)
On the activity you want to spy:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Register a spy for this activity
getApplication().registerActivityLifecycleCallbacks(new ActivitySpy(this));
}
}
Then the Spy code looks something like:
public class ActivitySpy implements ActivityLifecycleCallbacks {
private final Activity mActivity;
public ActivitySpy(Activity activity) {
mActivity = activity;
}
#Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
if (mActivity == activity)
Log.i("SPY", "Activity Created");
}
#Override
public void onActivityDestroyed(Activity activity) {
if (mActivity == activity)
Log.i("SPY", "Activity Destroyed");
}
// (...) Other overrides
}
You can also register the spy from another place if you have a reference to the Activity you want to follow.
I hope this helps :)
EDIT: I forgot to mention, this will only work on API Level 14 and above...