android全局变量2

时间:2020-12-24 10:32:07
The more general problem you are encountering is how to save stateacross several Activities and all parts of your application. A staticvariable (for instance, a singleton) is a common Java way of achievingthis. I have found however, that a more elegant way in Android is toassociate your state with the Application context.
) [# b6 x& b5 t5 E0 y) ^/ x! ^7 r5 @- s' k
--如想在整个应用中使用,在java中一般是使用静态变量,而在android中有个更优雅的方式是使用Application context。 ) j% o1 o# A2 P3 T+ a4 g7 Q9 e2 \

# {5 u/ h/ E! t8 `, @# n- d, F( B: iAs you know, each Activity is also a Context, which is informationabout its execution environment in the broadest sense. Your applicationalso has a context, and Android guarantees that it will exist as asingle instance across your application.
1 _, f: T6 r0 w: w) u--每个Activity 都是Context,其包含了其运行时的一些状态,android保证了其是single instance的。 ; @% H& Z. k+ }4 x. ^7 w
$ b& D- e" j3 M8 N- ^+ x2 \
The way to do this is to create your own subclass of android.app.Application,and then specify that class in the application tag in your manifest.Now Android will automatically create an instance of that class andmake it available for your entire application. You can access it fromany context using the Context.getApplicationContext() method (Activityalso provides a method getApplication() which has the exact sameeffect):
0 i) U  C4 e3 Z0 f( o( l--方法是创建一个属于你自己的android.app.Application的子类,然后在manifest中申明一下这个类,这是android就为此建立一个全局可用的实例,你可以在其他任何地方使用Context.getApplicationContext()方法获取这个实例,进而获取其中的状态(变量)。 ; `7 \) s/ o$ \3 S1 B! A9 ]8 v
: e' G3 P  x/ F! ?
给个例子:
7 g: L4 ~" h6 B8 q* `+ gclass MyAppextends Application {
  t7 h# O7 Z  y# F   private String myState;
/ T$ t4 g( D2 b" D. M. w- S
  public String getState(){
8 \% S' @5 \" ~/ ~# h6 d" ?9 f, n* ?    return myState;. k, y) E4 B2 \: b
  }% `: `$ Y5 g- [- H9 i3 R
  public void setState(String s){3 O. T  ^: p2 f4 {
    myState = s;( C: {% d8 v$ K
  }
% d6 t+ t. v, p4 F" l+ }+ A2 E}; Q  }2 j7 |( j, B1 e
class Blah extends Activity {6 d# @& d& s- j
  @Override
. q$ h7 m/ I7 t, U5 X! t  public void onCreate(Bundle b){! Y: ~+ O, z9 g6 ]
    ...
7 q% T/ i  D0 C3 K% w    MyApp appState = ((MyApp)getApplicationContext());6 m. p7 X# c" G. E1 [, G/ M0 f# U
    String state = appState.getState();( I8 K3 `8 {! {4 w! W
    ...
2 @+ L" v) m2 L* }3 E! Y  }
, c0 U: ]" T" y5 S" I: D1 k$ R}& Q& g& H. V' G1 K4 Y5 d) v& h8 x
& K3 M3 V1 q$ s
注意:这个MyAPP类一定要放在应用存放activity的那个包下,不能放在其他的包中,不然会报错!
2 l; ^' _# p$ ?* U
然后再manifest中添加应用:
% b+ G  i- z8 k< application android:name=".MyApp" android:icon="@drawable/icon" android:label="@string/app_name">& U2 N; N, O% k( p' |( E3 }
        <activity android:name=".ClickableListItemActivity"7 d6 D5 x8 U. d6 o
                  android:label="@string/app_name">
& T, m! W* O% F            <intent-filter># t; H7 z9 h# ]1 q8 {: U
                <action android:name="android.intent.action.MAIN" />3 G( _- p$ `: T! U6 g& D
                <category android:name="android.intent.category.LAUNCHER" />
' M4 ^5 N" s5 {; p2 c- \3 \            </intent-filter>5 U0 J1 M6 L" _7 E
        </activity>7 Q4 D- j. d* a4 j
    </application>
3 E( s2 S  b* L3 E  ~2 l
说明:
' B8 m' b  y& ^: r( D( c8 @4 U& b4 x  |- x3 y& p

5 Q; d/ A; @% X
. V/ j- a1 O5 [* m$ t7 V, t$ u: m9 Y& E
需添加的内容:android:name=".your_App_Name"位置:当前activity所在的位置,(我刚开始以为需要新建一个<application></application>);
" j, X5 R1 X3 i  L2 G 完成之后,我们在应用程序的任何一个Activity中可以通过如下方法访问我们的变量:

0 R1 Q* A9 V+ y% N ((MyApp )getApplication()).setGlobalVariable(10); int valiable=((MyApp )getApplication()).getGlobalVariable();
* P- D5 r& z0 h: K7 \! x
) t" X2 _1 p3 I4 Y' |+ I/ A

4 d! Z# p  P! X Application对象只有在应用程序中所有Activity都destroy时才会destrory,所有我们可以在任何一个Activity中访问它。, O$ N% V$ [+ r

2 `, T3 A6 c7 G' {' X6 N
, m. k6 P6 M" V- P

2 ]$ o/ }/ r. c1 J8 K. L, w# K3 _) tThis has essentially the same effect as using a static variable orsingleton, but integrates quite well into the existing Androidframework. Note that this will not work across processes (should yourapp be one of the rare ones that has multiple processes). & q( k( B( f4 ^$ t/ l
--这个效果就是使用静态变量是一样的,但是其更符合android的架构体系。