Skip to content Skip to sidebar Skip to footer

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 pr

Solution 1:

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

Your Fragment:

publicclassYourFragmentextendsFragment{

private OnListener listener;

 publicinterfaceOnListener
    {
        voidonChange();
    }

voidinitialize( 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:

publicclassyourActivityextendsActivityimplementsyourFragment.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.@OverridepublicvoidonChange()
    {
     // implement what you want to do 
     }
}

hope it will help.

Solution 2:

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.

Post a Comment for "Android Communication Between Activity And Fragment"