1.盡量不要使用靜態變數,靜態常量除外(static final).
http://blog.csdn.net/zhangyue0503/article/details/7614944
2.自訂一個MyApplication繼承android.app.Application,在其中定義全域變數。
啟動Application時,系統會建立一個PID,即進程ID,所有的Activity就會在此進程上運行。那麼我們在Application建立的 時候初始化全域變數,同一個應用的所有Activity都可以取到這些全域變數的值
import android.app.Application;import android.util.Log;public class MyApplication extends Application {public static final String TAG = MyApplication.class.getSimpleName();private User user;@Overridepublic void onCreate() {Log.i(TAG, "onCreate ::");super.onCreate();}public User getUser() {return user;}public void setUser(User user) {this.user = user;}}
AndroidManifest.xml中
Activity、Service中
MyApplication app = (MyApplication)getApplication().MyApplication app = (MyApplication)getApplicationContext();app.getUser();app.setUser(xxx);
BroadcastReceiver中onReceive()方法
MyApplication app = (MyApplication)context.getApplicationContext();app.getUser();app.setUser(xxx);
ContentProvider中
MyApplication app = (MyApplication)getContext().getApplicationContext();app.getUser();app.setUser(xxx);
其他類中,可以通過傳遞context,通過如下方式調用
MyApplication app = (MyApplication)context.getApplicationContext();app.getUser();app.setUser(xxx);