Android-global Context Retrieval

Source: Internet
Author: User

Android-global Context Retrieval

In Android, Context is used in many places, it is required when the Toast is displayed, when the activity is started, when the broadcast is sent, when the database is operated, and when the notification is used.

Maybe you haven't worried about not getting Context yet, because now many of our operations are carried out in the activity, and the activity itself is a Context object. However, when the application framework becomes more complex, a lot of logic code will be separated from the Activity class, but at this time you just need to use Context, maybe you will feel a little worried at this time.

For example, we have compiled an HttpUtil class to encapsulate some common network operations:

package org.lxh.demo;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.ProtocolException;import java.net.URL;public class HttpUtil {public static  void sendHttpRequest(final String address,final HttpCallbackListener listener){new Thread(new Runnable() {public void run() {try {HttpURLConnection connection=null;URL url=new URL(address);connection=(HttpURLConnection)url.openConnection();connection.setRequestMethod(GET);connection.setConnectTimeout(8000);connection.setReadTimeout(8000);connection.setDoInput(true);connection.setDoOutput(true);InputStream inputStream=connection.getInputStream();BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream));StringBuilder response=new StringBuilder();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.disconnection();}}}}).start();}}


Here, sendHttpRequest () can be used to send Http requests, but if we want to optimize the sendHttpRequest () method, we will give the user a Toast prompt when it is detected that the network does not exist, it does not execute subsequent code. Here, we encountered a problem. The pop-up Toast prompts that we need a Context parameter, and we obviously cannot get the Context object in the HttpUtil class. What should we do?

In fact, this problem is often encountered. How can we solve it? Here we will introduce a technique that allows you to easily obtain Context anywhere in the project. Android provides an Application class to facilitate the management of some global state information in the program, such as the global Context. To create a custom Application, you must first create a MyApplication class inherited from the Application, as shown below:

package org.lxh.demo;import android.app.Application;import android.content.Context;public class MyApplication extends Application {private static Context context;@Overridepublic void onCreate() {context=getApplicationContext();}public static Context getContext(){return context;}}


Next, we need to inform the system that the MyApplication class should be initialized when the program is started, instead of the default Application class, which should be specified under the tag in the AndroidManifest. xml file:

android:name=org.lxh.demo.MyApplication

 

In this way, you can use Context anywhere in the project by calling MyApplication. getContext:

Toast.makeText(MyApplication.getContext(),message,Toast.LENGTH_SHORT).show();

 

 

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.