android的全局变量

来源:互联网 发布:店铺淘宝客还能做吗 编辑:程序博客网 时间:2024/05/29 12:03

关于android中是否可以使用全局变量,当然可以。做Java的人肯定都用过全局变量了,使用方法无非是定义一个静态变量,public类型,这样在其他类中就可以直接调用了,android中也可以这样使用。

 

As you know, each Activityis also a Context, which is information about its execution environmentin the broadest sense. Your application also has a context, and Androidguarantees that it will exist as a single instance across yourapplication.

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. Youcan access it from any context using theContext.getApplicationContext() method (Activity also provides a methodgetApplication() which has the exact same effect):

 

 

 


 

public class MyApp extends Application {
    private String myState;

    public String getState() {
        return myState;
    }
   
    public void setState(String state){
        myState = state;
    }
}

 

class Blah extends Activity { 
  
  @Override 
  public void onCreate(Bundle b){ 
    ... 
    MyApp appState = ((MyApp)getApplicationContext()); 
    String state = appState.getState(); 
    ... 
  }

 

然后再manifest中添加属性application android:name=".MyApp",如下

 

<application android:name=".MyApp" android:icon="@drawable/icon" android:label="@string/app_name"> 
<activity android:name=".ClickableListItemActivity" 
    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>

 

 

 

原创粉丝点击