Step One The first thing while creating your app that uses fragments is to create  your layouts. Once you have created your layouts which could be a list view or anything you want, you can then create your Fragment class. Inside your onCreateView method of your fragment, you should inflate that view – again, a list view is a good example here. You normally return a view inside this method. Now, using a list view for example, you would probably like to do something whenever a user selects an item from that list like pop open a dialog to let them confirm their actions or load a whole new view to display the details for that particular item. So, how do you accomplish that? You simply want to implement anOnClickListener then override itsonClick method (this depends on what type of view you have – which could be a grid view or just a list view). Overriding such a method provides you with certain arguments like position – which is important when you really want to deal with particular items in a list and you can then pass the value back to the activity! Step Two The second step after inflating your view and implementing a click listener (as an example), you want to define an interface and then create a method – always remember than interface methods do not have bodies in them – it is the responsibility of the implementing class to override them and do what they want with them. You can define your interface from within the fragment class or as a standalone class in your project src folder. Step Three The third step is to implement that interface in your main activity. You will do something along the lines of MainActivity extends Activity implements FragmentOne.OnContactSelectedListener – from there on, you will have to override the method you defined earlier (from the fragment) in your activity. If your method inside your fragment expected an integer argument, remember to define it exactly as it is in your activity(same signature). Step Four Now that you have that covered, here comes the beauty of interfaces – whenever a user clicks an item, you can grab the position of that item (from the onClick method) and pass it back to the activity by simply calling the interface method. After that, you can pick it from the activity – inside the method you overrode and do some really awesome stuff with that position like query the database or get a value from a list array depending on which position you get back! Pretty cool right? Let us try and create some stuff here. MainActivity.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47     /** * The main activity that communicates with the fragment(s) * @author Elisha Chirchir - Simple Developer * @since - 2014 * */   public class MainActivity extends Activity implements NewsItemsFragment.OnNewsItemSelectedListener {     private NewsItemsFragment mItemsFragment;       @Override     public void onCreate(Bundle saveInstanceState)     {         super.onCreate(saveInstanceState);           setContentView(R.layout.main);           //Instantiate some stuff here like view components         mItemsFragment = new NewsItemsFragment();           //Now you can set the fragment to be visible here         setFragment(mItemsFragment);     }       public void setFragment(Fragment frag)     {              FragmentManager fm = getFragmentManager();            if (fm.findFragmentById(R.id.container) == null) {             fm.beginTransaction().add(R.id.container, frag).commit();         }          }       //Override the method here     @Override     public void onNewsItemPicked(int position)     {         //Do something with the position value passed back         Toast.makeText(activity, "Clicked "+ position, Toast.LENGTH_LONG).show();              } }     Now we can create our Fragment class here – the order is up to you really! NewsItemsFragment.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65     /** * Fragment that inflates a list view to display news headlines * @author - Elisha Chirchir - Simple Developer Blog * @since - 2014 */   public class NewsItemsFragment extends ListFragment implements AdapterView.OnItemClickListener {     Activity activity;     public static List<string> newsHeadlines = new ArrayList</string><string>(){{         add("Android Is Awesomerrrrrrrrrrrrrrrrrrr");         add("A teenager asks Miss America To Prom and gets suspended");         add("The Congress in The History of the United States is..");         add("How To Drive Safely When No One else Is.");         add("Learn How To Program On Your Own");         add("How To Communicate Between Fragments and Activities");         add("What to do when you have nothing to do");         add("The next big thing is here - your awesome app!");     }};          @Override     public void onAttach(Activity activity)     {         super.onAttach(activity);         this.activity = activity;     }       @Override     public void onActivityCreated(Bundle savedInstanceState){         super.onActivityCreated(savedInstanceState);           ArrayAdapter</string><string> adapter = new ArrayAdapter</string><string>(activity, R.layout.simple_row_item, newsHeadlines);         setListAdapter(adapter);         getListView().setOnItemClickListener(this);         }       @Override     public View onCreateView(LayoutInflater inflater, ViewGroup container,                              Bundle savedInstanceState){         return inflater.inflate(R.layout.head_lines_fragment, container, false);         }       @Override     public void onItemClick(AdapterView< ?> parent, View view, int position, long id) {         Toast.makeText(activity, "Clicked "+ position, Toast.LENGTH_LONG).show();           try{             ((OnNewsItemSelectedListener) activity).onNewsItemPicked(position);         }catch (ClassCastException cce){           }     }       public interface OnNewsItemSelectedListener{         public void onNewsItemPicked(int position);     } }     Summary of How To communicate between fragments and activities The reason why fragments are very powerful is because they do almost anything you would do inside an activity. That being said, you could decide to instead of passing back just theposition, you could do other manipulations like query the database to get the details from tables and then pass back the string value for the news articles. You can do a hell lot more to say the least. As you can see, communication between fragments and activities is made so much easier through interfaces in Java and you can really do whatever you want. For example, inside the method we overrode in the activity, we could do something else like load a new fragment to display the details or even start a new intent to open a web page and other crazy things you can imagine! This post is getting longer so I will halt it here for today and perhaps continue next time with other exciting stuff in android fragments! You can always visit the Google docs for more information on Fragments.

Today I am going to discussion Process and Thread in Android application.
When an android application clicked and open by user. Then android application starts its core component in a new Linux process for the application with a single thread of execution. the only condition is that application does not have any other components running at that time. If not then it starts it component in that time running process.

Example Source Code on Github
Processes
By default, all components of the same application run in the same process and most applications should not change this. However, if we find that our need to control which process a certain component belongs to, We can do so in the manifest file.
The manifest entry for each type of component element—<activity>, <service>,<receiver>, and <provider>—supports anandroid:process attribute that can specify a process in which that component should run.
We can set this attribute so that each component runs in its own process or so that some components share a process while others do not.
We can also set android:process so that components of different applications run in the same process—provided that the applications share the same Linux user IDand are signed with the same certificates.

Android might decide to shut down a process at some point, when memory is lowand required by other processes that are more immediately serving the user. Android system is deciding which processes to kill, based on apps  relative importance to the user. For example, it more readily shuts down a process hosting activities that are no longer visible on screen, compared to a process hosting visible activities.
Some Important points :-

The Android system tries to maintain an application process for as long as possible, To reclaim memory for new or more important processes, it follow hierarchy system. To determine which processes to keep and which to kill, the system places each process into an "importance hierarchy" Processes with the lowest importance are eliminated first from hierarchy

There are five levels in the importance hierarchy. The following list presents the different types of processes in order of importance (the first process is most important and is killed last):

Process lifecycle

Foreground processVisible processService processBackground processEmpty process

For detail you can click here

Threads

When an application is launched, the system creates a thread of execution for the application, called "main." This thread is very important because it is in charge of dispatching events to the appropriate user interface widgets, including drawing events. 

It is also the thread in which your application interacts with components from the Android UI toolkit (components from the android.widget and android.view packages). As such, the main thread is also sometimes called the UI thread.

 The Andoid UI toolkit is not thread-safe. So, we must not manipulate our UI from a worker thread. We  must do all manipulation to your user interface from the UI thread. Thus, there are simply two rules to Android's single thread model:

Do not block the UI threadDo not access the Android UI toolkit from outside the UI thread

Android offers several ways to access the UI thread from other threads. Here is a list of methods that can help:

Activity.runOnUiThread(Runnable)View.post(Runnable)View.postDelayed(Runnable, long)HandlerAsyncTask

No comments:

Post a Comment