Introduction and framework of "assistant app"

Source: Internet
Author: User

Recently did not how to code, put off and do a half-yearly graduation design to take a look back.

Campus Assistant, divided into server-side and Android client, the main introduction to the client, the server is a great God with node. js written.

The main implementation of the functions are: Landing, information query, map, ordering meals, Web page calls and analysis, the main difficulty is the interface.


The client's framework is a reference to the Web-based video on Sina Weibo clients. In the current work often encounter the inconvenience of the interface update, but this framework has solved this problem, but just getting started I do not know, encountered a lot of setbacks after the easy to find the framework. Let's start with a brief description:

public class mainservice extends service implements runnable {private  static final string tag =  "Mainservice";p rivate static queue<task>  tasks = new LinkedList<Task> ();p rivate static arraylist<activity>  appActivities = new ArrayList<Activity> ();/** *  flag whether the thread performing the task starts  */ public static boolean isrun;/** *  Current user  */public static userinfo of the system  nowUser;/** *  flag whether the current network is available  */public static boolean isnetavailable =  false; @Overridepublic  void oncreate ()  {//Start thread Execution task thread thread = new  Thread (this); Thread.Start (); isrun = true;//start a new thread get network status New thread (New runnable ()  {@ Overridepublic void run ()  {//always gets the network status isnetavailable = netservice.getnetworkstate ( mainservice.this);}). Start (); SuPer.oncreate ();} @Overridepublic  ibinder onbind (intent intent)  {return null;} /** *  add an Activity object   Call this function when each activity starts, add its own reference to the main service, easy to manage, more convenient interface update  *  @param  activity */public static void addactivity (activity activity)  {if  (! Appactivities.isempty ())  {for  (activity at : appactivities)  {if  ( At.getclass (). GetName (). Equals (Activity.getclass (). GetName ()))  {appactivities.remove (at); Appactivities.add (activity);} /** *  activity  name  Gets the activity object   needs the interface reference, it is obtained from the list, it is convenient to get the interface reference, so as to update the interface  * @ param name *  @return  */private static activity getactivitybyname (String  name)  {if  (!appactivities.isempty ())  {for  (activity activity :  appactivities)  {if  (null != activity)  {if  (Activity.getclass (). GetName (). indexOf (name)  > 0) &nbsp {return activity;}}}} Return null;} /** *  the new task   interface requires a time-consuming operation, call this function, assign the task to service execution, and then call the activity's reference to update the interface  *  @param when execution is complete  t  */public static void newtask (task t)  {tasks.add (t);} /** *  after the master service starts, the task is removed from the task Queue execution  */public void run ()  {while  (Isrun)  {task  task = null;if  (!tasks.isempty ())  {task = tasks.poll ();//  Remove if  (null != task)  {dotask (Task) from the task queue after performing the task;}}}   Processing Task Private void dotask (task t)  {Message msg =  Handler.obtainmessage (); Msg.what = t.gettaskid ();switch  (T.gettaskid ())  {                                  //is here to take time-consuming operations                  //it is best to encapsulate each module so that the code for the main service is concise and straightforward case task.user_login: {userinfo loginuser =  ( UserInfo)  t.gettaskparams (). Get ("Loginuser");if  (Null != loginuser)  {nowuser =  loginservice.login (Loginuser);//time-consuming Operation msg.obj = nowuser; LOG.I (tag,  "User login ———————— >"  + nowuser.getusername ());} break;} Default:break;}  end of switchhandler.sendmessage (msg);} /** *  asynchronously processes the message  */@SuppressLint ("Handlerleak") public static handler handler =  new handler ()  {public void handlemessage (android.os.message msg)  { iassistantactivity activity = null;switch  (msg.what)  {//processing time-consuming operations, sent over the message//The results through the parameters passed over, Then pass the activity reference to the interface case task.user_login: {if  (null != msg.obj)  {activity =   (iassistantactivity)  getactivitybyname ("loginactivity");} break;} Default:break;} end of switch//calls the update of the corresponding interface via the activity referencefunction Activity.refresh (msg.obj);};};/ ** *  exit the System   exit the system, it is easy to clear out all the activity *  @param  context */public static  void appexit (Context context)  {// Finish  all activityfor  (activity  activity : appactivities)  {if  (!activity.isfinishing ()) Activity.finish ();}   End  serviceintent service = new intent ("Cn.edu.wit.services.MainService"); Context.stopservice (service);}}

This main service can be completely reused, adding some content to your needs.

Let's see how the interface is built here.

public class loginactivity extends activity implements iassistantactivity { public static final string tag =  "Loginactivity";p Rivate progressdialog  progressDialog = null;private Button btn_Login;private ClearEditText  etuserid;private clearedittext etpassword;private checkbox cbisremember;private  Checkbox cbisauto;private imagebutton ib_spinner;protected view listview;private  PopupWindow pop;private List<String> userIDs ;p Rivate list<userinfo > loginedUsers ;p rivate myadapter adapter;private animation shake ; private userinfoservices userinfoservices = null; @Overrideprotected  void  OnCreate (bundle savedinstancestate)  {super.oncreate (savedinstancestate); Setcontentview ( R.layout.login);//Initialize Interface init ();} @Overridepublic  void&Nbsp;init ()  {                 //ensure that the primary service is started if (! Mainservice.isrun) {intent service = new intent (this, mainservice.class); StartService ( Service);} Get all users, add to the drop-down list in the Login box userinfoservices = new userinfoservices (loginactivity.this);// Get the user initdata (); Initview ();//  add yourself to the Activity collection mainservice.addactivity (this);} /** *  Initialization Interface  */private void initview ()  {                 //a dithering animation shake =  Animationutils.loadanimation (Loginactivity.this, r.anim.shake);etuserid =  (ClearEditText)   Findviewbyid (R.id.userid);etpassword =  (clearedittext)  findviewbyid (R.id.password); cbIsRemember  =  (checkbox)  findviewbyid (r.id.isremember);cbisauto =  (checkbox)  findviewbyid ( R.id.isauto); Textview tvgetpassword =&nBSP; (TextView)  findviewbyid (R.id.tvgetpassword);//"Retrieve password" underline, add underline to Text Tvgetpassword.getpaint (). SetFlags ( Paint.underline_text_flag); Tvgetpassword.setonclicklistener (New onclicklistener ()  {@Overridepublic  void onclick (view arg0)  {intent intent = new intent ( Loginactivity.this, findpwdactivity.class); startactivity (intent); Overridependingtransition ( Switchactivityanim.rightin (),  switchactivityanim.rightout ());}); /Login button btn_login =  (button)  findviewbyid (R.ID.LOGIN_OK); Btn_login.setonclicklistener (new  Onclicklistener ()  {@Overridepublic  void onclick (view v)  {string userid =  etuserid.gettext (). toString (). Trim (); String password = etpassword.gettext (). toString (). Trim ();if  (! "". Equals (userId)  && ! "". Equals (password))  {log.i (tag,  "Click login"); Userinfo loginuser = new userinfo (); LOGINUSER&NBSP;=&NBSP;NEW&NBsp UserInfo (); Loginuser.setuserid (userId); Loginuser.setpassword (password);//  Call function Create New task NewTask (Loginuser);}  else {if  ("". Equals (UserId))  {//The input box is empty when the jitter etuserid.startanimation (shake); Etuserid.sethint ( "Study number cannot be empty"); Etuserid.sethinttextcolor (color.red);}  else {etpassword.startanimation (shake); Etpassword.sethint ("Password cannot be empty"); Etpassword.sethinttextcolor ( color.red);}}}); /drop-down list showing logged-in user ib_spinner =  (ImageButton)  findviewbyid (r.id.ib_spinner); ib_ Spinner.setonclicklistener (New onclicklistener ()  {@Overridepublic  void onclick (View v )  {//  pop-up drop-down list Listview listview = new listview (Getapplicationcontext ()); Listview.setcachecolorhint (0x00000000);//  when sliding   does not change color listview.setverticalscrollbarenabled (false); Listview.setbackgroundcolor (Getresources (). GetColor (R.color.white));//Set Transparency Listview.getbackground (). Setalpha ( Listview.setadapter (New myadapter ());p Op = new popupwindow (listview,&Nbsp;etuserid.getwidth () +ib_spinner.getwidth (), layoutparams.wrap_content, true);//  Pop Hidden Pop.setbackgrounddrawable (new colordrawable (0x00000000));p op.setoutsidetouchable (true); Pop.setfocusable (True);//pop.setanimationstyle (r.style.popupanimation);p Op.showasdropdown (etUserId, 0,  -8);p op.update ();}});}                 // Encapsulate the time-consuming operation to the Master service Private void newtask (Userinfo loginuser)  {if (! mainservice.isnetavailable) {toast.maketext (loginactivity.this, ) network is not available! ",  toast.length_long). Show ();} Else {map<string, object> taskparams = new hashmap<string, object > (); Taskparams.put ("Loginuser",  loginuser); Task task = new task (task.user_login, taskparams);//Add the task to the main service thread Mainservice.newtask ( Task); Showdialg ();}} /** after the main service finishes processing the task, call this function by reference to achieve the purpose of the Update interface  *  update the login interface, or to jump after a successful login, or to display an error message  */@Overridepublic &NBSP;VOId refresh (Object... obj)  {progressdialog.dismiss ();if  (null != obj[0])  {if   (obj[0] instanceof exception)  {Exception exception =  (Exception)  obj[ 0]; System.out.println (Exception.getmessage ()); Toast.maketext (this,  "Login failed! ",  toast.length_short). Show (); return;} userinfo user =  (UserInfo) obj[0];if  (Null == user.getusername ()  | |   "". Equals (User.getusername ()))  {//User name password error toast.maketext (this,  "Login failed! ",  toast.length_short). Show (); Toast.maketext (this,  "Please check user name password and network connection is available",  toast.length_long). Show (); else {//login success, jump to the main interface Toast.maketext (loginactivity.this,  "Login successful! ",  toast.length_short). Show (); Toast.maketext (loginactivity.this,  "Welcome  " +user.getusername () + "Children's Shoes",  toast.length_short). Show (); Int isremember = cbisremember.ischecked ()  ? 1 :0 ;int isauto =  cbisauto.ischecked ()  ? 1 :0 ;//  Jump Intent intent = new intent (loginactivity.this,  Homeactivity.class); startactivity (intent); Overridependingtransition (Switchactivityanim.fadein (),  Switchactivityanim.bloomout ());if  (1 == isauto)  {//automatic login is stored in the database, and write to configuration file Sharedpreferencesutil.saveloginuser (loginactivity.this, user); Userinfoservices.insertuserinfo (user );} else if  (1 == isremember)  {//Remember the password to write to the database Userinfoservices.insertuserinfo (user);} This.finish ();}} Else {toast.maketext (loginactivity.this,  "Login Failed",  toast.length_long). Show ();}} Private void initdata () {userids = new arraylist<string> (); loginedUsers =  userinfoservices.getalllogineduser (); string users =  "";if  (null != loginedusers &&  Loginedusers.size ()  > 0)  {for  (userinfo user : loginedusers)  { Userids.add (User.getuserid ()); users +=&Nbsp;user.getuserid () + "\t   Password:" +user.getpassword () + "\ n";} System.out.println (users);}} To adapt a list of logged-in users to a drop-down list class myadapter extends baseadapter {@Overridepublic  int  GetCount ()  {return userids.size ();} @Overridepublic  object getitem (int position)  {return userids.get (position);} @Overridepublic  long getitemid (int position)  {return position;} @Overridepublic  view getview (Final int position, view convertview,viewgroup  parent)  {layoutinflater inflater = layoutinflater.from (GetApplicationContext ()); View view = inflater.inflate (R.layout.item_userids, parent, false); textview tv_name =  (TextView)  view.findviewbyid (r.id.tv_name); imagebutton delete  =  (ImageButton)  view.findviewbyid (r.id.delete) Tv_name.settext (userids.get (position)); tv_ Name.setonclicklistener (New onclicklistener () &nbSp {@Overridepublic  void onclick (view v)  {etuserid.settext (userids.get (position)); Etpassword.settext (Loginedusers.get (position). GetPassword ());p Op.dismiss ();}); Delete.setonclicklistener (New onclicklistener ()  {@Overridepublic  void onclick (View v)  {userids.remove (position); adapter.notifydatasetchanged ();}); Return view;}} Private void showdialg ()  {if  (null == progressdialog  )  { Progressdialog = new progressdialog (this);} Progressdialog.setmessage ("Getting info ...");p rogressdialog.show ();}}

You should be able to see clearly through comments.


I am learning Android through this project, so there is not too much Android processing skill, due to the reason of work, just using the previous code, and not optimized. This also allows you to see the process of growing up slowly.

This article from the "Young Wind" blog, declined to reprint!

Introduction and framework of "assistant app"

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.