首页 > 代码库 > Application 用法

Application 用法

Application用于存储和访问任何界面的变量,也就是说,在一个工程里,我们可以在Application定义全局变量,在其他Activity中引用。具体用法如下:

1.建立MyApplication.java文件

package entity;import com.android.volley.RequestQueue;import com.android.volley.toolbox.ImageLoader;import com.android.volley.toolbox.Volley;import android.app.Application;public class MyApplication extends Application {	private RequestQueue mRequestQueue;	private ImageLoader imageLoader;	@Override	public void onCreate() {		super.onCreate();		mRequestQueue=Volley.newRequestQueue(getApplicationContext());		imageLoader=new ImageLoader(mRequestQueue, new BitMapCache());	}	public RequestQueue getRequestQueue(){		return mRequestQueue;	}	public ImageLoader getImageLoader(){		return imageLoader;	}	}

  2.在主函数中引用,这里只写出Activity中的引用片段

public RequestQueue getmRequestQueue() {		MyApplication app = (MyApplication) getApplication();		return app.getRequestQueue();	}	public ImageLoader getImageLoader() {		MyApplication app = (MyApplication) getApplication();		return app.getImageLoader();	}

 注意,继承Application主要是重写onCreate()里面的方法,而且在AndroidMenifext.xml中还要注册一下

 <application        android:name="entity.MyApplication"        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="activity.MainActivity"            android:theme="@android:style/Theme.NoTitleBar"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <activity android:name="activity.ChannelActivity"/>        <activity android:name="activity.HouTaiActivity"></activity>    </application>

  

 

 

Application 用法