Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a custom View know that onPause has been called?

I have a custom View that runs a Thread operation which sits around making calls to the interwebs periodically. I would like to know if there's a way for me to not have to kill that thread from the parent Activity (onPause) so that the Thread isn't milling about in the background after the Activity has been backgrounded (and/or killed).

The intention here is for the custom View to be self sufficient and not need additional handling from the Activity. The way to do that would be for it to listen for when its parent was backgrounded and for it to then let the infinite sleep loop in the Thread expire. I'm not seeing a way to do that, but am hoping that I'm overlooking something.

like image 458
Yevgeny Simkin Avatar asked Mar 13 '14 03:03

Yevgeny Simkin


People also ask

Is onPause always called before onStop?

onPause() is always called. This is guaranteed. If you need to save any state in your activity you need to save it in onPause() . onStop() may be called after onPause() , or it may not.

When onPause method is called when?

onPause() method of an activity is call when you receive a phone call. Otherwise in lots of cases onPause() is always call with onStop() . Example like when you press home button, call another intent and more like when your activity is in background.

When onPause method is called in Android?

onPause. Called when the Activity is still partially visible, but the user is probably navigating away from your Activity entirely (in which case onStop will be called next). For example, when the user taps the Home button, the system calls onPause and onStop in quick succession on your Activity .

What is the difference between onPause and onStop?

If screen times out on your activity, then onPause is called. After sometime if you will not open the screen then onStop will be called.


1 Answers

Yes you can using below code,

@Override protected void onVisibilityChanged(@NonNull View changedView, int visibility) {     super.onVisibilityChanged(changedView, visibility);     if (visibility == View.VISIBLE) //onResume called     else // onPause() called }  @Override public void onWindowFocusChanged(boolean hasWindowFocus) {     super.onWindowFocusChanged(hasWindowFocus);     if (hasWindowFocus) //onresume() called     else // onPause() called }  @Override     protected void onDetachedFromWindow() {         super.onDetachedFromWindow();         // onDestroy() called }  @Override     protected void onAttachedToWindow() {         super.onAttachedToWindow();         // onCreate() called } 
like image 56
Yogesh Rathi Avatar answered Oct 12 '22 11:10

Yogesh Rathi