Android--全域變數 很好很強大

來源:互聯網
上載者:User

標籤:des   android   blog   http   io   ar   os   java   sp   

As you know, each Activity is also a Context, which is information about its execution environment in the broadest sense. Your application also has a context, and Android guarantees that it will exist as a single instance across your application.

The way to do this is to create your own subclass of android.app.Application, and then specify that class in the application tag in your manifest. Now Android will automatically create an instance of that class and make it available for your entire application. You can access it from any context using the Context.getApplicationContext() method (Activity also provides a method getApplication() which has the exact same effect):

 

  

Java代碼  
  1. class MyApp extends Application {  
  2.   
  3.   private String myState;  
  4.   
  5.   public String getState(){  
  6.     return myState;  
  7.   }  
  8.   public void setState(String s){  
  9.     myState = s;  
  10.   }  
  11. }  
  12.   
  13. class Blah extends Activity {  
  14.   
  15.   @Override  
  16.   public void onCreate(Bundle b){  
  17.     ...  
  18.     MyApp appState = ((MyApp)getApplicationContext());  
  19.     String state = appState.getState();  
  20.     ...  
  21.   }  
  22. }  

 

This has essentially the same effect as using a static variable or singleton,

but integrates quite well into the existing Android framework.

Note that this will not work across processes (should your app be one of the rare ones that has multiple processes).

 

 

然後再manifest中添加應用:

Xml代碼  
  1. <application android:name=".MyApp" android:icon="@drawable/icon" android:label="@string/app_name">  
  2.         <activity android:name=".ClickableListItemActivity"  
  3.                   android:label="@string/app_name">  
  4.             <intent-filter>  
  5.                 <action android:name="android.intent.action.MAIN" />  
  6.                 <category android:name="android.intent.category.LAUNCHER" />  
  7.             </intent-filter>  
  8.         </activity>  
  9.   
  10.     </application>  

  

說明:

  1. 需添加的內容:android:name=".your_App_Name"

  2. 位置:當前activity所在的位置,(我剛開始以為需要建立一個<application></application>)

Android--全域變數 很好很強大

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.