- 生成application子类,类中包含需要全局的变量
public class MyApplication extends Application {
private String name;
public String myname;
@Override
public void onCreate() {
super.onCreate();
setName(NAME); //初始化全局变量
myname="初始化";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private static final String NAME = "MyApplication";
}
- 在配置文件ApplicationManifest.xml中配置MyApplication。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hisoft.app"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name"
android:name=".MyApplication"> 就是这儿,将我们以前一直用的默认Application给他设置成我们自己做的MyApplication
<activity android:name=".MyFirstActivity"
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=".MySecondActivity"></activity>
</application>
<uses-sdk android:minSdkVersion="8" />
</manifest>
- 在Activity中声明该该类,并使用
public class MyFirstActivity extends Activity {
private MyApplication app;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
app = (MyApplication) getApplication(); //获得我们的应用程序MyApplication
app.setName("is cool"); //OK,现在我们开始修改了
Intent intent = new Intent(); //更重要的是我们可以看在别的Activity中是拿到初始化的值,还是修改后的
intent.setClass(this, MySecondActivity.class);
startActivity(intent);
}
}
* 第二个Activity
public class MySecondActivity extends Activity {
private MyApplication app;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
app = (MyApplication) getApplication(); //获取应用程序
Log.e("MySecondActivity", app.getName()); //获取全局值
}
}