An example analysis of the Android Observer model _android

Source: Internet
Author: User
Tags server port

This example describes the Android observer model. Share to everyone for your reference. The specific analysis is as follows:

First, the environment:

Host: WIN8
Development environment: Eclipse

Second, note:

1. Open the XML file in the SD card, if it does not exist, create a new one and write the default configuration
2. Reading XML files
3.config_info.java for configuration information data structure
4.if_config.java is the access interface for the configuration class, and other classes can get configuration information directly from this interface
5.if_subject_config.java for observer mode target class interface
6.IF_OBSERVER_CONFIG.JAVA for observer mode Observer class interface
7.config.java is a configuration class that completes 1, 22, and is the target class for the observer model, once the configuration information is changed to notify the Observer class
8.TESTCLASS.JAVA as observer mode Observer
The design of loose coupling can be realized by Access Interface + Observer mode.

Three, XML file format:

<?xml version= "1.0" encoding= "UTF-8" standalone= "true"?> 
-<config> 
<title> Remote video interview system </ title> 
<local_port>12600</local_port> 
<schedule_service_ip>10.58.1.59</ schedule_service_ip>
<schedule_service_port>12601</schedule_service_port> 
</config >

Four, the source code:

Config_info.java:

/** 
 * Configuration information data type 
 * New time: 2014/12/8 by JDH * * 
package com.example.helloanychat; 
public class Config_info { 
 //Header public 
 String title; 
 Native IP public 
 String local_ip; 
 Native port public 
 int local_port; 
 Dispatch server IP public 
 String schedule_server_ip; 
 Dispatch server port public 
 int schedule_server_port; 
}

If_config.java:

/** 
 * Interface: Configuration class, read-write 
 * New time: 2014/12/8 by JDH * * 
package com.example.helloanychat; 
Public interface If_config {public 
 config_info get_config_info (); 
}

If_subject_config.java:

/** 
 * Interface: Configuration class, observer mode: Target 
 * New time: 2014/12/8 by JDH * 
 * 
package com.example.helloanychat; 
Public interface If_subject_config {public 
 void Register_observer (If_observer_config observer); 
 public void Remove_observer (If_observer_config observer); 
 public void Notify_observer (); 
}

If_observer_config.java:

/** 
 * Interface: Configuration class, Observer mode: Observer 
 * New time: 2014/12/8 by JDH * * 
package com.example.helloanychat; 
Public interface If_observer_config {public 
 void update (Config_info Info); 
}

Config.java:

/** * Configuration Information class * New Date: 2014/12/8 by JDH * Modified Date: 2014/12/9 by JDH/package com.example.helloanychat; 
Import Java.io.File; 
Import Java.io.FileInputStream; 
Import Java.io.FileOutputStream; 
Import java.io.IOException; 
Import Java.io.StringWriter; 
Import java.net.Inet6Address; 
Import java.net.InetAddress; 
Import Java.net.NetworkInterface; 
Import java.net.SocketException; 
Import java.util.ArrayList; 
Import java.util.Enumeration; 
Import java.util.List; 
Import Java.util.Timer; 
Import Java.util.TimerTask; 
Import Javax.xml.parsers.DocumentBuilder; 
Import Javax.xml.parsers.DocumentBuilderFactory; 
Import android.os.Environment; 
Import Android.util.Log; 
Import org.w3c.dom.Document; 
Import org.w3c.dom.Element; 
Import org.w3c.dom.NodeList; 
Import Org.xmlpull.v1.XmlPullParserFactory; 
Import Org.xmlpull.v1.XmlSerializer; 
 public class Config implements If_config,if_subject_config {//configuration information private Config_info info = new Config_info (); Store the list of observers private List<if_oBserver_config> observers = new arraylist<if_observer_config> (); 
 Timer Private Timer timer_work = new timer (); 
 Working interval, unit: Ms private final int interval_work = 5000; 
 /** * Constructor/public Config () {//Generate configuration information generate_config_info ();
 Create a timed thread timer_work.schedule (new Task (), interval_work,interval_work); 
 Timed task}//interface: read-write @Override public config_info Get_config_info () {return Info; 
 //Read/write, observer mode: Target @Override public void Register_observer (If_observer_config observer) {OBSERVERS.ADD (Observer); 
 @Override public void Remove_observer (If_observer_config observer) {int index = OBSERVERS.INDEXOF (Observer); 
 if (index >= 0) {OBSERVERS.REMOVE (Observer); @Override public void Notify_observer () {for (int i = 0; i < observers.size (); i++) {If_observer_confi 
  G o = (if_observer_config) observers.get (i); 
 O.update (Info); /** * Get native IP address * @return Native IP address * * Private String getlocalipaddress () {Try {for (enumeration<networkinterface> en = networkinterface. getnetworkinterfaces (); en.hasmoreelements ();) 
  {NetworkInterface intf = en.nextelement (); for (enumeration<inetaddress> enumipaddr = intf. getinetaddresses (); enumipaddr.hasmoreelements ();) 
   {InetAddress inetaddress = enumipaddr.nextelement (); if (!inetaddress.isloopbackaddress ()) {if (!inetaddress.isloopbackaddress () &&! ( 
   InetAddress instanceof inet6address)) {return inetaddress.gethostaddress (). toString (); 
 catch (SocketException ex) {LOG.E ("wifipreference IPAddress", ex.tostring ()); 
 return null; /** * Generate XML configuration file string data stream * Config_info native IP information does not save * @param info: Configuration information * @return XML string Data Flow * * Private S 
 Tring produce_xml_string (Config_info Info) {StringWriter StringWriter = new StringWriter (); 
  try {//Get XmlSerializer object Xmlpullparserfactory factory = Xmlpullparserfactory.newinstance (); XmlSerializer XmlseriaLizer = Factory.newserializer (); 
  Set the output Stream object Xmlserializer.setoutput (StringWriter); 
  Start tag xmlserializer.startdocument ("Utf-8", true); 
  Xmlserializer.starttag (null, "config"); 
  Title Xmlserializer.starttag (null, "title"); 
  Xmlserializer.text (Info.title); 
  Xmlserializer.endtag (null, "title"); 
  Native port Xmlserializer.starttag (null, "Local_port"); 
  Xmlserializer.text (integer.tostring (Info.local_port)); 
  Xmlserializer.endtag (NULL, "Local_port"); 
  Dispatch server IP xmlserializer.starttag (null, "schedule_service_ip"); 
  Xmlserializer.text (INFO.SCHEDULE_SERVER_IP); 
  Xmlserializer.endtag (NULL, "schedule_service_ip"); 
  Dispatch server port Xmlserializer.starttag (null, "Schedule_service_port"); 
  Xmlserializer.text (integer.tostring (Info.schedule_server_port)); 
  Xmlserializer.endtag (NULL, "Schedule_service_port"); 
  Xmlserializer.endtag (null, "config"); 
 Xmlserializer.enddocument (); 
 catch (Exception e) {e.printstacktrace (); return stringwriter.tostring (); 
 /** * Work task: Get configuration information * * private void Generate_config_info () {Boolean OK; 
 File Sd_path; 
 File File_cfg_dir; 
 File file_cfg; 
 FileOutputStream out; 
 String str; 
 FileInputStream in; 
 Config_info Info = new Config_info (); 
 Get the native IP address info.local_ip = getlocalipaddress (); 
 Get SD card Directory Sd_path = Environment.getexternalstoragedirectory (); 
 Determine if the folder exists File_cfg_dir = new file (Sd_path.getpath () + "//remote_meeting"); 
  if (!file_cfg_dir.exists () &&!file_cfg_dir.isdirectory ()) {System.out.println ("Configuration folder remote_meeting does not exist!"); 
  OK = File_cfg_dir.mkdirs ();
  if (OK) {System.out.println ("Create folder succeeded!");
  else {System.out.println ("Create folder failed!"); 
 }//Determine if the configuration file exists file_cfg = new file (File_cfg_dir.getpath (), "Cfg.xml"); 
  if (!file_cfg.exists ()) {System.out.println ("config file cfg.xml does not exist!"); 
  try {file_cfg.createnewfile (); 
  System.out.println ("Create File Cfg.xml successful!"); 
   Generate initialized configuration data try {out = new FileOutputStream (FILE_CFG); 
Save default configuration   Info.title = "Remote video interview system"; 
   Info.local_port = 12600; 
   INFO.SCHEDULE_SERVER_IP = "10.58.1.59"; 
   Info.schedule_server_port = 12601; 
   str = produce_xml_string (Info); 
   Out.write (Str.getbytes ()); 
   Out.close (); 
   Save Native IP info.local_ip = info.local_ip; 
  Inform the Observer Notify_observer (); 
  catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); 
  The catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); 
  } else {//parse XML file try {in = new FileInputStream (FILE_CFG); 
  Documentbuilderfactory factory = Documentbuilderfactory.newinstance (); 
  Documentbuilder builder = Factory.newdocumentbuilder (); 
  Document document = Builder.parse (in); 
  Gets the root node Element root = Document.getdocumentelement (); 
  NodeList node = root.getchildnodes (); 
  Get 1th child node: Title Info.title = Node.item (0). Getfirstchild (). Getnodevalue (); Get 2nd child node: Native Port Info.local_port = Integer.parseint (Node.item (1).Getfirstchild (). Getnodevalue ()); 
  Get 3rd child node: Dispatch server IP info.schedule_server_ip = Node.item (2). Getfirstchild (). Getnodevalue (); 
  Get 4th child node: Dispatch server Port Info.schedule_server_port = Integer.parseint (Node.item (3). Getfirstchild (). Getnodevalue ()); 
   Determines whether the configuration information changes do {if (!info.title.equals (Info.title)) {break; 
   } if (!info.local_ip.equals (info.local_ip)) {break; 
   } if (Info.local_port!= info.local_port) {break; 
   } if (!info.schedule_server_ip.equals (info.schedule_server_ip)) {break; 
   } if (Info.schedule_server_port!= info.schedule_server_port) {break; 
  //all the same return; 
  } while (false); 
  Assign value info.title = Info.title; 
  Info.local_ip = info.local_ip; 
  Info.local_port = Info.local_port; 
  Info.schedule_server_ip = info.schedule_server_ip; 
  Info.schedule_server_port = Info.schedule_server_port; 
  Inform the Observer Notify_observer (); 
  catch (Exception e) {e.printstacktrace (); } 
 } 
 /** * Timer Thread timed work */private class Task extends TimerTask {@Override public void run () {GENERATE_CONFI 
 G_info (); } 
 } 
}

Testclass.java:

Package com.example.helloanychat; 
public class TestClass implements If_observer_config {public 
 TestClass () { 
 } 
 @Override public 
 Void Update (Config_info Info) { 
 System.out.printf ("-------------Update data:%s,%s,%d,%s,%d\n", 
 info.title,info.local _ip,info.local_port,info.schedule_server_ip,info.schedule_server_port); 
 } 

Mainactivity:

TestClass TestClass = new TestClass (); 
Config config = new config (); 
Meditip.settext (Config.get_config_info (). local_ip); 

I hope this article will help you with your Android program.

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.