Android--全局变量 很好很强大
As you know, each Activity is also a Context, which is information about its execution environment in the broadest sense. Your application also has a context, and Android guarantees that it will exist as a single instance across your application.
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 and make it available for your entire application. You can access it from any context using the Context.getApplicationContext() method (Activity also provides a method getApplication() which has the exact same effect):
- class MyApp extends Application {
- private String myState;
- public String getState(){
- return myState;
- }
- public void setState(String s){
- myState = s;
- }
- }
- class Blah extends Activity {
- @Override
- public void onCreate(Bundle b){
- ...
- MyApp appState = ((MyApp)getApplicationContext());
- String state = appState.getState();
- ...
- }
- }
This has essentially the same effect as using a static variable or singleton,
but integrates quite well into the existing Android framework.
Note that this will not work across processes (should your app be one of the rare ones that has multiple processes).
然后再manifest中添加应用:
- <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>
说明:
-
需添加的内容:android:name=".your_App_Name"
-
位置:当前activity所在的位置,(我刚开始以为需要新建一个<application></application>)
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。