在进程间可公用的全局变量

来源:互联网 发布:手机淘宝买家秀在哪看 编辑:程序博客网 时间:2024/04/28 17:16




方法一:通过单实例:

publicclass Globals{
   privatestatic Globals instance;
 
   // Global variable
   privateint data;
 
   // Restrict the constructor from being instantiated
   privateGlobals(){}
 
   publicvoid setData(intd){
     this.data=d;
   }
   publicint getData(){
     returnthis.data;
   }
 
   publicstatic synchronized Globals getInstance(){
     if(instance==null){
       instance=newGlobals();
     }
     returninstance;
   }
}

在其他类中需要使用时:

Globals g = Globals.getInstance();
g.setData(100);
 
....
intdata=g.getData();




方法二:继承application

a) Create a new class that extends Application.

1
2
3
4
5
6
7
8
9
10
11
publicclass Globals extendsApplication{
   privateint data=200;
 
   publicint getData(){
     returnthis.data;
   }
 
   publicvoid setData(intd){
     this.data=d;
   }
}

b) Add the class to the AndroidManifest file as an attribute of <application> tag:

1
2
3
<application
   android:name=".Globals"
   .... />

c) Then you can access your global data from any Activity by callinggetApplication()

1
2
Globals g = (Globals)getApplication();
intdata=g.getData();




0 0
原创粉丝点击