首先需要重寫Application,主要重寫裏面的onCreate方法,就是創建的時候,初始化變量的值。然後在整個應用中的各個文件中就可以對該變量進行操作了。
啓動Application時,系統會創建一個PID,即進程ID,所有的Activity就會在此進程上運行。那麼我們在Application創建的時候初始化全局變量,同一個應用的所有Activity都可以取到這些全局變量的值,換句話說,我們在某一個Activity中改變了這些全局變量的值,那麼在同一個應用的其他Activity中值就會改變。下面舉個例子詳細介紹一下應用步驟。
下面是MyApp.java
package com.android.test;
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!"); //初始化全局變量
}
}
下面是mainActivity.java
package com.ginwave.test;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
public class mainActivity extends Activity {
private MyApp myApp;
@Override
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.java:
package com.android.test;
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()); //查看變量值是否修改了
}
}
修改配置文件ApplicationManifest.xml,將要運行的應用程序MyApp加進去:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.test"
android:versionCode="1"
android:versionName="1.0">
<!-- 在這裏,將默認的Application設置成自己做的MyApp-->
<application android:name="MyApp"
android:icon="@drawable/icon"
android:label="@string/app_name"
>
<activity android:name=".mainActivity"
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>
運行的結果:
03-04 16:53:17.295: INFO/guoll(650): InitLabel:Welcome!
03-04 16:53:17.295: INFO/guoll(650): ChangeLabel:Changing!
03-04 16:53:17.426: INFO/guoll(650): OhterActivity receive the Label:Changing!