Article 3 MVC and observer models for Android Application Development

Source: Internet
Author: User

If the template mode is the core of the android framework, it provides the foundation of the application architecture components, while the observer mode provides the foundation of the androd architecture connector, it is also the basis for implementing the broadcast components and content provider components of the other two components, as well as the UI input mechanism. The observer mode is widely used in Android applications and frameworks.

The observer mode is also called the publishing/subscription mode. The implementation mechanism is the event-driven model of the message publishing/subscription mode: The producer publishing event of the message, and the user subscribes to events of interest.

We know that the observer mode is the basis of the MVC mode, while the MVC mode is an important mode hidden by the android framework. In the android framework, activity and its basic contextimpl assume the Controller role in the MVC mode, which is used to forward control requests sent by the view and interact with the model; the view bound to the activity also plays the view role in the MVC mode. The decorview is the main view of the activity, other child views or controls are generated by the activity by reading the layout file of the application (in XML format) and combined into a view tree, achieve the layout of the view (the view is combined into a view tree ). Every service in the framework and the data it generates provide the role of the MVC model. Each service is controlled by the local service management object registered in contextimpl, And the view registers the listening of model events through the Controller (contextimpl). The controller itself can also be registered as the listening object. The local service management object itself or the application view sends a request message to the model and interacts with the Service (model) through the local service management object (Controller). When the data generated by the service changes, notification View and controller in observer mode (broadcast or intent. In the MVC mode, the view is the observer. The view is combined into a view tree through the combination mode. The Controller acts as the intermediary between the view and the model, therefore, the MVC mode adopts the observer mode, combination mode, and mediation mode.

Using the MVC mode can simplify application development, while using the framework to provide model and controller implementation makes application development easier. The application only needs to inherit the controller (activity) and implement callback interfaces, compile the layout XML file of the view, provide the resource files used, register listening events to the model, and write and provide data interfaces for the model. (The adapter mode is recommended for Android. interfaces with various data sources, android provides the simplecursoradapter class for databases) and other five tasks to complete application development. The control requests for business logic and data provision and forwarding views are all handled by the Framework, so application development is so simple. The following is an example of an activity.

Private broadcastreceiver mscanlistener = new broadcastreceiver () {// instantiate a broadcast object

@ Override

Public void onreceive (context, intent) {// implement the callback interface for broadcast receipt

Musicutils. setspinnerstate (albumbrowseractivity. This );

Mrescanhandler. sendemptymessage (0 );

If (intent. getaction (). Equals (intent. action_media_unmounted )){

Musicutils. clearalbumartcache ();

}

}

};

Public class myactivity extends activity implements onitemclicklistener {

@ Override

Protected void oncreate (bundle savedinstancestate ){

Super. oncreate (savedinstancestate );

Intentfilter F = new intentfilter ();

F. addaction (intent. action_media_scanner_started );

F. addaction (intent. action_media_scanner_finished );

F. addaction (intent. action_media_unmounted );

F. adddatascheme ("file ");

Registerreceiver (mscanlistener, f); // registers a broadcast listening event for the model.

Setcontentview (R. layout. media_picker_activity); // read the layout file to generate a view tree

Cursor c = getcontentresolver (). Query (settings. system. content_uri, null );

// First obtain the data source pointer through the Controller

Listadapter adapter = new simplecursoradapter (this,

Android. R. layout. simple_list_item_1,

C,

New String [] {People. name },

New int [] {Android. R. Id. text1 });

Setlistadapter (adapter); // set the interface with the data source in adapter Mode

Getlistview (). setonitemclicklistener (this); // sets the listener and Controller of the View control.

}

Public void onitemclick (adapterview parent, view, int position, long ID) {// callback interface of the view listener event

Intent dummyintent = new intent (this, listsimple. Class );

Startactivity (dummyintent );

}

In contextimpl, a static code block is used to pre-register a total of 34 System Service management objects to the contextimpl cache. The view or controller object obtains the service management objects from the cache through the getsystemservice interface, interaction with the model. This method instantiates an object only once during packaging and registers it to the cache. Therefore, it can speed up obtaining system service management objects.

Private Static final hashmap <string, servicefetcher> system_service_map =

New hashmap <string, servicefetcher> (); // instantiate and save the hashmap Of The fetcher object. The fetcher object actually reads the local service management object.

Private Static void registerservice (string servicename, servicefetcher fetcher ){

If (! (Fetcher instanceof staticservicefetcher )){

Fetcher. mcontextcacheindex = snextpercontextservicecacheindex ++;

}

System_service_map.put (servicename, Fetcher); // put The fetcher object in hashmap according to the service name

}

Static {

Registerservice (accessibility_service, new servicefetcher (){

Public object getservice (contextimpl CTX ){

Return accessibilitymanager. getinstance (CTX );

}); // Register a fetcher object to the hashmap corresponding to the accessibility_service name, and overwrite the getservice Function

 

Registerservice (account_service, new servicefetcher (){

Public object createservice (contextimpl CTX ){

Ibinder B = servicemanager. getservice (account_service );

Iaccountmanager service = iaccountmanager. stub. asinterface (B );

Return new accountmanager (CTX, Service );

}); // Register a fetcher object to the hashmap corresponding to the account_service name and implement its createservice interface.

...

 

}

Static class servicefetcher {

Public object getservice (contextimpl CTX ){

Arraylist <Object> cache = CTX. mservicecache;

Object Service;

Synchronized (cache ){

If (Cache. Size () = 0 ){

For (INT I = 0; I <snextpercontextservicecacheindex; I ++ ){

Cache. Add (null );

}

} Else {

Service = cache. Get (mcontextcacheindex); // obtain the service from the cache

If (service! = NULL ){

Return service;

}

}

Service = createservice (CTX); // if no value is obtained in the cache, the service management object is instantiated.

Cache. Set (mcontextcacheindex, service); // Save the newly created service management object to the cache for future use.

Return service;

}

}

}

@ Override

Public object getsystemservice (string name) {// obtain the unified interface of the local service management object

Servicefetcher fetcher = system_service_map.get (name );

Return fetcher = NULL? Null: Fetcher. getservice (this); // get the local service management object through the getservice interface of Fetcher.

}

The observer mode is widely used in the framework, including JNI sending notifications to the Java layer. See the android_media_mediaplayer.cpp file.

 

Static void android_media_mediaplayer_native_setup (jnienv * ENV, jobject thiz, jobject weak_this)

{

Logv ("native_setup ");

Sp <mediaplayer> MP = new mediaplayer ();

Sp <jnimediaplayerlistener> listener = new jnimediaplayerlistener (ENV, thiz, weak_this );

MP-> setlistener (listener); // register the listener of the C ++ Layer Media Player as a JNI object.

}

Void jnimediaplayerlistener: Policy (int msg, int ext1, int ext2, const parcel * OBJ)

{

Jnienv * Env = androidruntime: getjnienv ();

If (OBJ & obj-> datasize ()> 0 ){

...

Env-> callstaticvoidmethod (mclass, fields. post_event, mobject,

MSG, ext1, ext2, jarray); // here, the JNI listener object forwards events generated by the player

}

}

Void mediaplayer: Running y (int msg, int ext1, int ext2, const parcel * OBJ)

{

Sp <mediaplayerlistener> listener = mlistener;

If (listener! = 0) & send ){

Listener-> Y (MSG, ext1, ext2, OBJ); // The callback API for player event generation sends a notification to the JNI listener object.

Logv ("back from callback ");

}

}

 

You are welcome to repost the document. Please respect the source of the original article.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.