Android Application 类共享全局数据

android系统会为每一个程序执行时创建一个Application类的对象且仅创建一个。所以Application能够说是单例模式的一个类。且application对象的生命周期是整个程序中最长的,它的生命周期就等于这个程序的生命周期。

由于它是全局的单例的。所以在不同的Activity,Service中获得的对象都是同一个对象。所以通过Application来进行一些,数据传递。数据共享 等,数据缓存等操作。代码例如以下:

package com.example.five;
import android.app.Application;
public class MyApp extends Application{
	private int type;
	public int gettype(){
	return type;	
	}
	public void settype(int x){
	this.type=x;
	}
	@Override
	public void onCreate(){
		super.onCreate();
		settype(0);
	}
}
接着在androidManifest.xml文件里指定Application类:

<application   
android:name=".MyApp"     
android:icon="@drawable/icon"     
android:label="@string/app_name"> 
Activity中存值:

((MyApp)getApplication()).settype(1);
Activity中取值:

((MyApp)getApplication()).gettype();
View中取值:

((MyApp)getContext().getApplicationContext()).gettype();

posted @ 2017-06-06 16:13  jhcelue  阅读(421)  评论(0编辑  收藏  举报