Java、ios、android開發總結(二) Android中全域變數和靜態變數的使用

來源:互聯網
上載者:User


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);



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.