Refer to the first line of code--Guo Lin
Recall what we have learned so long, you will find that there are a lot of places need to use the context, pop-up toast, need to start the event, the need to send a broadcast, the need to operate the database, the use of notifications when the need, and so on.
Perhaps you have not yet been worried about not getting the context, because a lot of our operations are carried out in the activity, and the activity itself is a context object. However, when the architecture of the application begins to become complex, many of the logic code will be out of the activity class, but at this point you need to use the context, and perhaps you will feel a bit of a headache.
For example, we have written a httputil class that encapsulates some common network operations, as shown in the following code:
Public classHttputil { Public Static voidSendhttprequest (FinalString Address,FinalHttpcallbacklistener Listener) { NewThread (NewRunnable () {@Override Public voidrun () {httpurlconnection connection=NULL; Try{URL URL=NewURL (address); Connection=(HttpURLConnection) url.openconnection (); Connection.setrequestmethod ("GET"); Connection.setconnecttimeout (8000); Connection.setreadtimeout (8000); Connection.setdoinput (true); Connection.setdooutput (true); InputStream in=Connection.getinputstream (); BufferedReader Reader=NewBufferedReader (NewInputStreamReader (in)); StringBuilder Response=NewStringBuilder (); String Line; while(line = Reader.readline ())! =NULL) {response.append (line); } if(Listener! =NULL) {listener.onfinish (response.tostring ()); } } Catch(Exception e) {if(Listener! =NULL) {listener.onerror (e); } } finally { if(Connection! =NULL) {connection.disconnect (); }}}). Start (); }}
There is obviously no problem using the Sendhttprequest () method to send HTTP requests, and we can also handle the data returned by the server in the callback method. But now we want to make some optimizations to the Sendhttprequest () method, give the user a toast prompt when it detects that the network is not present, and no longer execute the subsequent code. Seemingly a very simple function, but there is a headache problem, pop-up toast hint needs a context parameter, and we in the Httputil class is obviously not get the context object, what should we do?
In fact, to quickly solve this problem is also very simple, the big deal in the Sendhttprequest () method to add a context parameter is OK, so you can change the code in the Httputil as follows:
Public classHttputil { Public Static voidSendhttprequest (Finalcontext Context,FinalString address,FinalHttpcallbacklistener Listener) { if(!isnetworkavailable ()) {Toast.maketext (context,"Network is unavailable", Toast.length_short). Show (); return; } NewThread (NewRunnable () {@Override Public voidRun () {
...... } }). Start (); } Private Static Booleanisnetworkavailable () {
...}
As you can see, a context parameter is added to the method, and a isnetworkavailable () method is assumed to determine if the current network is available, and if the network is unavailable, The Toast prompt pops up and the method is gone.
Although this is really a solution, but a bit of the suspicion of shirking responsibility, because we will get the context of the task transferred to the Sendhttprequest () method of the caller, as for the caller can not get the context object, it is not a problem we need to consider.
As you can see, in some cases, getting context is not an easy thing to do, and sometimes it's quite nerve-racking. But don't worry, let's learn a technique that makes it easy to get to the context anywhere in your project.
Android provides a application class that automatically initializes the class whenever the application starts. And we can customize a application class to make it easier to manage some of the global state information in the program, such as the global context.
Customizing a self-application is not really complicated, first we need to create a MyApplication class that inherits from application, the code looks like this:
public class myapplication extends application { private Span style= "color: #0000ff;" >static context context; @Override public void OnCreate () {context = Getapplicationcontext (); public static context GetContext () { return context; }}
As you can see, the code in MyApplication is very simple. Here we rewrite the OnCreate () method of the parent class and get an application-level context by calling the Getapplicationcontext () method, and then provide a static GetContext () method, The context you just acquired is returned here.
Next we need to tell the system that the MyApplication class should be initialized when the program starts, rather than the default application class. This step is also very simple, under the <application> tag of the Androidmanifest.xml file to specify it, the code is as follows:
<Manifestxmlns:android= "Http://schemas.android.com/apk/res/android" Package= "Com.example.networktest"Android:versioncode= "1"Android:versionname= "1.0" >...<Applicationandroid:name= "Com.example.networktest.MyApplication"...>...</Application></Manifest>
Note that you must add the full package name when specifying MyApplication, or the system will not be able to find this class.
Thus we have implemented a global access to the context of the mechanism, then no matter you want to use the context anywhere in the project, only need to call Myapplication.getcontext ().
So next we'll refine the Sendhttprequest () method, as shown in the code below:
Public Static void sendhttprequest (finalfinal Httpcallbacklistener listener) { if (! Isnetworkavailable ()) { "network is unavailable", toast.length_short). Show (); return ; }}
As you can see, the Sendhttprequest () method does not need to pass the argument to get the context object, but just call the Myapplication.getcontext () method. With this technique, you no longer have to worry about not getting the context object.
android# global access to context tips