以前都是建立一个ConstData的类来保存全局用的变量,但是有时候确实是有点小问题。
所以研究了一下使用Application来建立全局变量,下面就是代码,主要分为四个文件:
(1)是MyApplication类,保存全局变量以及变量的查询和修改
(2)TestAndroid 类 也是主类
(3)otherActivity 另外一个类调用全局变量试试是不是被主类改变了
(4)manifest.xml文件
MyApplication
package an.test.android;
import android.app.Application;
public class MyApp extends Application{
private String mylabel ;
public String getLabel(){
return mylabel;
}
public void setLabel(String s){
this.mylabel = s;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
setLabel("Welcome!"); //初始化全局变量
}
}
TestAndroid
package an.test.android;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
public class TestAndroid extends Activity {
/** Called when the activity is first created. */
private MyApp myApp;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myApp = (MyApp) getApplication(); //获得自定义的应用程序MyApp
Log.i("guoll", "InitLabel:"+myApp.getLabel()); //将我们放到进程中的全局变量拿出来,看是不是我们曾经设置的值
myApp.setLabel("Changing!"); //修改一下
Log.i("guoll", "ChangeLabel:"+myApp.getLabel()); //看下,这个值改变了没有
Intent intent = new Intent(); //再看一下在另一个Activity中是取到初始化的值,还是取到修改后的值
intent.setClass(this, otherActivity.class);
startActivity(intent);
}
}
otherActivity
package an.test.android;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class otherActivity extends Activity{
private MyApp myApp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myApp = (MyApp) getApplication(); //获得自定义的应用程序MyApp
Log.i("guoll", "OhterActivity receive the Label:"+myApp.getLabel()); //查看变量值是否修改了
}
}
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="an.test.android"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name" android:name="MyApp" >
<activity android:name=".TestAndroid"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".otherActivity">
</activity>
</application>
</manifest>
这里尤其要注意的一点就是:MyApp这个类要在manifest中进行注册,其实就是加上了一行代码
android:name="MyApp"
但是这个是必须的!