Context——Context的使用

本文介绍如何在Android应用中创建和使用全局Context,包括自定义Application类以保存全局变量,并通过工具类实现两种不同方式调用Context的方法。

转自http://blog.youkuaiyun.com/android_tutor/article/details/8026018

Context大致可以分为两种:一是传递Context参数,二是调用全局的Context.

其实我们应用启动的时候会启动Application这个类,这个类是在AndroidManifest.xml文件里其实是默认的

    <application  
           android:icon="@drawable/ic_launcher"  
           android:label="@string/app_name"  
           >  
           <activity  
               android:name=".ApplicationDemoActivity"  
               android:label="@string/app_name" >  
               <intent-filter>  
                   <action android:name="android.intent.action.MAIN" />  
                   <category android:name="android.intent.category.LAUNCHER" />  
               </intent-filter>  
           </activity>  
       </application>  

这个Application类是单例的,也就是说我们可以自己写个Application(比如名为:MainApplication)类,来代替默认的Applicaiton,这个类可以保存应用的全局变量,我们可以定义一个全局的Context.供外部调用.用法如下:
    package com.tutor.application;  
      
    import android.app.Application;  
    import android.content.Context;  
      
    public class MainApplication extends Application {  
      
        /** 
         * 全局的上下文. 
         */  
        private static Context mContext;  
          
        @Override  
        public void onCreate() {  
            super.onCreate();  
              
            mContext = getApplicationContext();  
              
        }     
          
        /**获取Context. 
         * @return 
         */  
        public static Context getContext(){  
            return mContext;  
        }  
          
          
        @Override  
        public void onLowMemory() {  
            super.onLowMemory();  
        }  
          
          
    }  
我们需要在AndroidMainifest.xml把MainApplication注册进去(第10行代码):

    <?xml version="1.0" encoding="utf-8"?>  
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
        package="com.tutor.application"  
        android:versionCode="1"  
        android:versionName="1.0" >  
          
        <application  
            android:icon="@drawable/ic_launcher"  
            android:label="@string/app_name"  
            android:name=".MainApplication" >  
            <activity  
                android:name=".ApplicationDemoActivity"  
                android:label="@string/app_name" >  
                <intent-filter>  
                    <action android:name="android.intent.action.MAIN" />  
                    <category android:name="android.intent.category.LAUNCHER" />  
                </intent-filter>  
            </activity>  
        </application>  
          
    </manifest>  

工具类ToolsUtil.java

ackage com.tutor.application;  
  
import android.content.Context;  
import android.widget.Toast;  
  
/** 
 * @author frankiewei. 
 * 应用的一些工具类. 
 */  
public class ToolUtils {  
      
    /** 
     * 参数带Context. 
     * @param context 
     * @param msg 
     */  
    public static void showToast(Context context,String msg){  
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();  
    }  
      
    /** 
     * 调用全局的Context. 
     * @param msg 
     */  
    public static void showToast(String msg){  
        Toast.makeText(MainApplication.getContext(), msg, Toast.LENGTH_SHORT).show();  
    }  
}  
新建一个View命名为MainView.java就是我们Activity现实的View.代码如下:
package com.tutor.application;  
  
import android.app.Activity;  
import android.content.Context;  
import android.util.AttributeSet;  
import android.view.LayoutInflater;  
import android.view.View;  
import android.widget.Button;  
import android.widget.FrameLayout;  
  
/** 
 * @author frankiewei. 
 * 自定义的MainView. 
 */  
public class MainView extends FrameLayout implements View.OnClickListener{  
      
    private Context mContext;  
      
    private Activity mActivity;  
      
    /** 
     * 参数Button. 
     */  
    private Button mArgButton;  
      
    /** 
     * 全局Button. 
     */  
    private Button mGlobleButton;  
      
    /** 
     * 退出Button. 
     */  
    private Button mExitButton;  
      
    public MainView(Context context){  
        super(context);  
        setupViews();  
    }  
  
    public MainView(Context context, AttributeSet attrs) {  
        super(context, attrs);  
        setupViews();  
    }  
      
      
    private void setupViews(){  
        //获取View的上下文.  
        mContext = getContext();  
        //这里将Context转换为Activity.  
        mActivity = (Activity)mContext;  
        LayoutInflater inflater = LayoutInflater.from(mContext);  
        View v = inflater.inflate(R.layout.main, null);  
        addView(v);  
          
        mArgButton = (Button)v.findViewById(R.id.arg_button);  
        mGlobleButton = (Button)v.findViewById(R.id.glo_button);  
        mExitButton = (Button)v.findViewById(R.id.exit_button);  
          
        mArgButton.setOnClickListener(this);  
        mGlobleButton.setOnClickListener(this);  
        mExitButton.setOnClickListener(this);  
    }  
  
    public void onClick(View v) {  
        if(v == mArgButton){  
            ToolUtils.showToast(mContext, "我是通过传递Context参数显示的!");  
        }else if(v == mGlobleButton){  
            ToolUtils.showToast("我是通过全局Context显示的!");  
        }else{  
            mActivity.finish();  
        }  
    }  
  
} 

这里MainView.java使用的布局main.xml代码如下:

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent"  
    android:orientation="vertical" >  
  
    <TextView  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"  
        android:text="Welcome to frankie wei's blog."   
        />  
      
    <Button  
        android:id="@+id/arg_button"  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"  
        android:text="传递Context参数"  
        />  
      
    <Button  
        android:id="@+id/glo_button"  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"  
        android:text="全局的Context"  
        />  
      
    <Button  
        android:id="@+id/exit_button"  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"  
        android:text="退出App"  
        />  
  
</LinearLayout> 

修改ApplicationDemoActivity.java,代码如下
    package com.tutor.application;  
      
    import android.app.Activity;  
    import android.os.Bundle;  
      
    public class ApplicationDemoActivity extends Activity {  
        @Override  
        public void onCreate(Bundle savedInstanceState) {  
            super.onCreate(savedInstanceState);  
              
            MainView mMainView = new MainView(this);  
            setContentView(mMainView);  
         
        }  
          
    }  


### Spring - context 概述 Spring - context 是 Spring 框架的核心模块之一,它提供了依赖注入(DI)和控制反转(IoC)容器的支持,以及其他企业级服务,如事件传播、资源加载、国际化等。 ### 功能介绍 - **依赖注入和 IoC 容器**:Spring - context 实现了强大的 IoC 容器,它负责创建和管理对象(Bean),并通过依赖注入的方式将对象之间的依赖关系进行解耦。例如,可以通过 XML 配置、Java 注解或 Java 配置类来定义 Bean 及其依赖关系。 ```xml <!-- XML 配置示例 --> <bean id="userService" class="com.example.UserService"> <property name="userRepository" ref="userRepository"/> </bean> <bean id="userRepository" class="com.example.UserRepository"/> ``` ```java // Java 注解示例 import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; @Service public class UserService { private UserRepository userRepository; @Autowired public UserService(UserRepository userRepository) { this.userRepository = userRepository; } } ``` - **事件机制**:Spring - context 提供了事件传播机制,允许应用程序中的组件发布和监听事件。这有助于实现松耦合的组件通信。例如,当用户注册成功后,可以发布一个用户注册事件,其他组件可以监听该事件并执行相应的操作。 ```java import org.springframework.context.ApplicationEvent; // 自定义事件类 public class UserRegisteredEvent extends ApplicationEvent { public UserRegisteredEvent(Object source) { super(source); } } import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; // 事件监听器 @Component public class UserRegisteredListener implements ApplicationListener<UserRegisteredEvent> { @Override public void onApplicationEvent(UserRegisteredEvent event) { // 处理用户注册事件 } } ``` - **资源加载**:Spring - context 提供了统一的资源加载接口 `ResourceLoader`,可以方便地加载各种类型的资源,如文件、类路径资源、URL 资源等。 ```java import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.core.io.Resource; public class ResourceLoadingExample { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); Resource resource = context.getResource("classpath:config.properties"); // 处理资源 } } ``` - **国际化支持**:Spring - context 支持国际化(i18n),可以根据用户的语言环境提供不同的文本信息。通过配置消息源和使用 `MessageSource` 接口,可以轻松实现国际化功能。 ```xml <!-- 配置消息源 --> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename" value="messages"/> </bean> ``` ```java import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class InternationalizationExample { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); String message = context.getMessage("welcome.message", null, java.util.Locale.ENGLISH); System.out.println(message); } } ``` ### 使用指南 1. **添加依赖**:如果使用 Maven 项目,在 `pom.xml` 中添加 Spring - context 依赖。 ```xml <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.23</version> </dependency> ``` 2. **配置 Bean**:可以使用 XML 配置、Java 注解或 Java 配置类来定义和配置 Bean。 3. **启动 Spring 容器**:根据配置方式的不同,使用相应的方式启动 Spring 容器。 ```java import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { // 启动 XML 配置的 Spring 容器 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); // 获取 Bean UserService userService = context.getBean(UserService.class); // 使用 Bean userService.doSomething(); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值