Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android communication between activity and fragment

I have an activity which contains a ViewPager inside it.The ViewPager's Adapter is FragmentStatePagerAdapter. Each page is Fragment.The Fragment contains a number of Threads. My problem is, I have to stop all the threads inside the fragment when ViewPager's page is changed.How can I do this ?

like image 387
Jis Jose Avatar asked Dec 26 '22 21:12

Jis Jose


2 Answers

you have asked about communication between activity and fragment that you achieve using interface:

Your Fragment:

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 it will help.

like image 84
KDeogharkar Avatar answered Dec 28 '22 10:12

KDeogharkar


Android's philosophy with applications is to kill processes, so maybe following the same idea you could kill your Threads. Be aware though that this can lead to deadlocks if your Threads own locks, or monitors.

A more serious approach to me seems to use Thread.interrupt() from your Activity. Then your Threads in your Fragment have to check Thread.interrupted for interruption, and finish gracefully if they've been interrupted.
You can use Thread.join() if you want some synchronous behavior

In addition, you can wait for a certain amount of time for your Thread to finish gracefully using a Timer, then kill them on timeout.

Please have a look at java.lang.Thread


To let this be more easy to implement, you could use a ThreadPoolExecutor or some other helper of java.util.concurrent package.

like image 42
Antoine Marques Avatar answered Dec 28 '22 09:12

Antoine Marques