Android connection between activity and fragment

I have an activity that contains a ViewPager inside it. ViewPager Adapter - FragmentStatePagerAdapter . Each page is a Fragment . Fragment contains several threads. My problem is that I have to stop all threads inside the fragment when the ViewPager's page ViewPager's . How can i do this?

+4
source share
2 answers

you asked about the relationship between activity and the fragment that you reach using the interface:

Your snippet:

 public class YourFragment extends Fragment{ private OnListener listener; public interface OnListener { void onChange(); } void initialize( OnListener listener) { this.listener = listener; } //onview pager change call your interface method that will go to the activity as it has the listener for interface. listener.onChange(); } 

Your activity:

 public class yourActivity extends Activity implements yourFragment.OnListener { // intialize the method of fragment to set listener for interface where you define fragment. yourFragment.initialize( this ); // implement what you want to do in interface method. @Override public void onChange() { // implement what you want to do } } 

hope this helps.

+8
source

The philosophy of Android with apps is to kill processes, so maybe by following the same idea you can kill your threads. Remember that this can lead to deadlocks if your threads own locks or monitors.

A more serious approach to me seems to be using Thread.interrupt () from your activity. Then your threads in your fragment should check Thread.interrupted to interrupt and finish gracefully if they were interrupted.
You can use Thread.join () if you want some kind of synchronous behavior

In addition, you can wait a while for your thread to finish gracefully using a timer and then kill them by timeout.

Please see java.lang.Thread


To make this easier to implement, you can use ThreadPoolExecutor or some other java.util.concurrent package helper.

+1
source

Source: https://habr.com/ru/post/1500302/


All Articles