Android Weibo client building of the system main frame in the second day

Source: Internet
Author: User

From the last more than three days, not because of laziness, but the content of this lesson for the basis of the poor I am a bit too much information, so long before barely eat it. So the nonsense is not much to say, directly into today's content bar.

First look at the UI so far:

   

In addition to the following a "Welcome to Sina" of the TextView, there is no change ah. Haha, then you are wrong, the last time we two buttons are not moving, this time have their own function, first enter the user name and password points under login to try.

Well, you're not mistaken, it's changing the TextView content below. Haha, there may be someone to dozens, this is not a pupil will change it. Well, really, just want to get rid of it is very easy, but our theme is the main frame of the building, which is only to the framework filled with a little content of the results, the whole process is a bit of a struggle, so also please a little Ann do not spray. We continue to look at the UI

This is the result of dot next to register button

In this activity, clicking the Cancel button will return to the previous activity and has not yet given the Register button to bind the listener, but our focus is on framing frame framing, framing the frame, and adding functionality to it easily. Well, here's the UI show, and here's how the skeleton behind the ugly UI is built.

==================== Split Line ====================

This is the entire main framework of the workflow, a few more nouns, service, handle, thread. These for the veteran should have heard the calluses, but for like I just touch the small white of Android is still very unfamiliar, ah, put two links below to give small white rose posture. Service, handle these two things are very important, do not understand them our project will not be able to continue to go on. Well, let's take this picture for three minutes.

Http://www.360doc.com/content/14/0415/18/2793098_369238276.shtml

Http://blog.sina.com.cn/s/blog_77c6324101016jp8.html

First of all, our main activit, because in the late to refresh our UI, so we define the way the activity is also a lot of

 Public class extends Implements Iweiboactivity

Methods for manipulating the UI are defined in the Iweiboactivity interface

 Public Interface iweiboactivity {//     Initialize data    void  init (); //     Refresh UI    void Refresh (object...params);}

Loginactivity's entrance or OnCreate method.

protected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.login); Loginbutton=(Button) Findviewbyid (R.id.loginbutton); Registerbutton=(Button) Findviewbyid (R.id.regisrerbutton); Intent Intent = new Intent (this, Mainservice.class);        StartService (intent); Buttonclicklistener Buttonclicklistener=NewButtonclicklistener ();        Loginbutton.setonclicklistener (Buttonclicklistener);        Registerbutton.setonclicklistener (Buttonclicklistener); Mainservice.addactivity ( This); }

Well, it's starting to define a few buttons, which are not the focus, but later. The point is my red highlighted code. Here we use intent to start a service, which is the mainservice in the flowchart. Wirelessly activity is only responsible for dealing with the users of the monster, the dirty work behind the dirty are service in the dry. Let's see how mainservice is defined.

 Public class extends Implements

Here our Mainservice also inherits the Runnable interface, but does not say that the service is a thread, and it has no relationship with the thread half-dime. The article I shared above emphasized, here in the emphasis again, service is not a thread! Service is not a thread! Service is not a thread! OK, let's go on.

Likewise, the main entrance to the service is the OnCreate method

 Public void onCreate () {        super. OnCreate ();         true ;         New Thread (this);        Thread.Start ();    }

Since our Mainservice inherits the Runnable interface, this can be passed as a parameter to the thread constructor. A new thread is opened here, so let's look at the Run method

 Public voidrun () {Task Task=NULL;  while(isrun) {if(!Tasks.isempty ()) {//the queue is not empty and is assigned to a task and removed from the queueTask =Tasks.poll (); if(Task! =NULL)                {//task is executed without being empty and will be implemented laterdotask (Task); }            }            Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); }        }    }

The task of this thread is to detect that there are currently no tasks, to execute, and to continue the loop. Where tasks is a task queue, defined in the following way

Private Static New Linkedlist<task> ();

Queue, first-out, data structures have been learned, do not understand the small partners on the internet search for a search on the good. <> the object in the angle bracket is called generics, which is the type of each element in the queue, the contents of the task class

  

 Public classTask {//task ID    Private inttaskId;//Micro Blog Login     Public Static Final intWeibo_login = 1;//Weibo registration     Public Static Final intWeibo_register = 2;//Parameters    PrivateMap<string, object>Taskparams;  Public voidSettaskid (inttaskId) {         This. TaskId =taskId; }     Public voidSettaskparams (map<string, object>taskparams) {         This. Taskparams =Taskparams; }     Public intGetTaskID () {returntaskId; }     PublicMap<string, object>Gettaskparams () {returnTaskparams; }     PublicTask (intTaskId, Map<string, object>taskparams) {         This. TaskId =taskId;  This. Taskparams =Taskparams; }}
View Code

Although this task content is many, actually defines a task ID "TaskId" and the parameter key value pair Taskparams also has some static constants, the rest is the constructor and the set, the Get method.

So who's going to assign a job to our service when we're done with the task of testing? Actually think can come to the answer: The app is for the user Service, so the task must also be a person to release, and the app and human interaction is the UI, so to the service to release the task is certainly the UI. Looking at our flowchart can also draw the conclusion that the task is given by the UI. Now go back to loginactivity and see how he got the job done.

Several buttons are defined in the loginactivity, the listener is bound, and the listener contents are as follows

 Private classButtonclicklistenerImplementsView.onclicklistener {@Override Public voidOnClick (View v) {Task Task=NULL; Switch(V.getid ()) { CaseR.id.loginbutton:task=NewTask (Task.weibo_login,NULL);                    Mainservice.newtask (Task);  Break;  CaseR.id.regisrerbutton:task=NewTask (Task.weibo_register,NULL);                    Mainservice.newtask (Task);  Break; default:                     Break; }        }    }
View Code

As you can see, a task object is generated in the case and added to the task queue using a static method in Mainservice

//     Adding tasks to the task queue     Public Static void NewTask (Task t)    {        Tasks.add (t);    }

Well, because our tasks are static, it can't be used (the member variables used in static methods must all be static)

This way add the task to the message queue, remember that thread that was previously opened in Mainservice? It detects a new task in the task queue and calls the Dotask method to execute.

Private voiddotask (Task t) {Message msg=Handler.obtainmessage (); Msg.what=T.gettaskid (); Switch(T.gettaskid ()) { CaseTask.WEIBO_LOGIN:System.out.println ("Dotask >>>>>> User Login Tasks"); Msg.obj= "Logging in ....";  Break;  CaseTask.WEIBO_REGISTER:System.out.println ("Dotask >>>>>> User Registration Tasks");  Break; default:                 Break;    } handler.sendmessage (msg); }
View Code

In Dotask, a message instance is generated with handler, the ID of the task is put into MSG, the task is further subdivided according to TaskID, and the message is finally sent to handler. Note that this dotask is in thread threads, handler

is defined in the Mainservice.

classMyHandlerextendsHandler {@Override Public voidhandlemessage (Message msg) {Super. Handlemessage (msg); Iweiboactivity Activity=NULL; Switch(msg.what) { CaseTask.weibo_login://Update UIActivity= (iweiboactivity) getactivitybyname ("Loginactivity");                    Activity.refresh (Msg.what, msg.obj);  Break;//Jump to registration page                 CaseTask.WEIBO_REGISTER:activity= (iweiboactivity) getactivitybyname ("Loginactivity");                    Activity.refresh (Msg.what);  Break; default:                     Break; }}} MyHandler Handler=NewMyHandler ();
View Code

Then the question comes, why can obviously in Dotask in the UI to make the change, why have to bother to write it to handlemessage function again? The answer is: Android does not allow threads other than the main thread in the activity to change ui! Another thing to say is that the code in the service is actually the main thread of the activity that started it. Therefore, we are not able to refresh the UI in Dotask.

The work behind it is simple, get the activity to change, and call the corresponding refresh. The activity obtained here must inherit the Iweiboactivity interface, because the Refresh method is defined in the Iweiboactivity interface. There's a getactivitybyname method in it.

PrivateActivity getactivitybyname (String name) {if(!Appactivities.isempty ()) {             for(Activity activity:appactivities) {if(Activity! =NULL)                {                    if(Activity.getclass (). GetName (). IndexOf (name) > 0) {System.out.println (Activity.getclass (). GetName ()); returnactivity; }                }            }        }        return NULL; }
View Code

Appactivities is a variable of type ArrayList, and also a type of organization data, defined as follows

Private Static New Arraylist<activity> ();

In the same vein as the queue, the elements in the appactivities are activity types. Until then, the work we have to do in Mainservice is done.

Finally, a little tail, is the activity of the Refresh function implementation, this part is very simple, because the different tasks passed the parameters, so the use of the variable parameter function

 Public voidRefresh (Object ... paramas) {intChoose = Integer.parseint (paramas[0].tostring ()); Switch(choose) { CaseTASK.WEIBO_LOGIN:LOG.D ("Mainservice", paramas[1].tostring ()); TextView=(TextView) Findviewbyid (R.id.textid); Textview.settext (paramas[1].tostring ());  Break;  CaseTask.WEIBO_REGISTER:Intent Intent=NewIntent ( This, Registeractivity.class);            StartActivity (Intent); default:                 Break; }    }
View Code

This is the design of the entire main frame. Yes, it's easy to get rid of the UI, but that's just a sign-in, and it wouldn't be that simple if you really did. And with the framework we want to add another feature that is particularly easy, defining a task instance to be added to the queue of tasks, and implementing specific functions, so that the whole project is logical, easy to manage and optimize.

This time the note is done here, to summarize the get to the new skills: service, the use of handler, Java in the foreach statement (light spray, Java Foundation is not solid), and return to the previous level of activity of the finish method. Because the amount of information for me is a little big, this time the logic is quite chaotic, welcome you to shoot bricks.

Project source Download Link: http://files.cnblogs.com/files/51qianrushi/Iweibo.zip

So much for this time, see you next time. Reprint please notify oneself or indicate source

Android Weibo client building of the system main frame in the second day

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.