android中使用Application

來源:互聯網
上載者:User

標籤:application   android開發   全域變數   單例   

在android開發過程中,我們可能儲存一些全域的變數,最好在正在app的任何一個activity或者service中都可以訪問到,這時我們可以使用application。

我們的一個應用就叫application,那麼應該很好理解一個應用裡面只會存在一個單例的application,也不難想到用這個在儲存全域變數,那麼到底是怎麼儲存呢?

首先,我們建立一個Application,繼承android.app.Application:

<span style="font-size:18px;">package com.podongfeng.firstapplication.app;import android.app.Application;public class MyApplication extends Application {private Integer allViewInteger;public Integer getAllViewInteger() {return allViewInteger;}public void setAllViewInteger(Integer allViewInteger) {this.allViewInteger = allViewInteger;}}</span>

然後,在AndroidManifest.xml去聲明這個Application,有點類似於聲明Activity。

其實,在AndroidManifest.xml中肯定會存在一個系統聲明的Application,類似於這樣:

<span style="font-size:18px;"><application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name=".SplashActivity"            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=".MainActivity"            android:label="@string/app_name" >        </activity>    </application></span>

那麼,怎麼替換成為我們自己的application呢?

其實,只要在application標籤中增加android:name屬性指向我們自訂的application就可以了:

<span style="font-size:18px;"><application        android:name="com.podongfeng.firstapplication.app.MyApplication"        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <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=".SecActivity"            android:label="@string/app_name" >        </activity>    </application></span>

OK,這樣的話,我們就可以在activity中使用getApplicationContext()來擷取這個我們自訂的Application了。

等等,是不是局的這樣還不是特別的方便,如果寫了一些共用的java方法,為了代碼的良好複用,沒有放在activity裡面呢?

通過一個參數把context傳過去,然後再用context去擷取Application?

這樣做當然可以,不過,既然Application是單例的,我們很容聯想到在單例的設計模式中使用getInstance方法來得到單例的對象。事實上,我們的MyApplication整合了Application,可以直接覆寫onCreate方法,在Application被建立時把對象賦值給一個靜態成員變數,這樣,就可以任何地方通過MyApplication的靜態方法去擷取這個單例了:

<span style="font-size:18px;">package com.podongfeng.firstapplication.app;import android.app.Application;public class MyApplication extends Application {private static MyApplication myApplication = null;public static MyApplication getMyApplication() {return myApplication;}private Integer allViewInteger;public Integer getAllViewInteger() {return allViewInteger;}public void setAllViewInteger(Integer allViewInteger) {this.allViewInteger = allViewInteger;}@Overridepublic void onCreate() {super.onCreate();myApplication = this;}}</span>

OK,我們目前只在裡面寫了一個可用的全域變數allViewInteger,這僅僅用來說明問題就足夠了,想存什麼就存什麼,擷取起來也很方便,最後附上在2個activity中set和get的一個全域變數的範例:

<span style="font-size:18px;">package com.podongfeng.firstapplication;import com.podongfeng.firstapplication.app.MyApplication;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class MainActivity extends Activity implements OnClickListener {private Button nextBtn;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);MyApplication myApplication = MyApplication.getMyApplication();myApplication.setAllViewInteger(100);nextBtn = (Button) findViewById(R.id.btn_next);nextBtn.setOnClickListener(this);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {// Handle action bar item clicks here. The action bar will// automatically handle clicks on the Home/Up button, so long// as you specify a parent activity in AndroidManifest.xml.int id = item.getItemId();if (id == R.id.action_settings) {return true;}return super.onOptionsItemSelected(item);}@Overridepublic void onClick(View v) {Intent intent = new Intent();intent.setClass(getApplicationContext(), SecActivity.class);startActivity(intent);}}</span>

<span style="font-size:18px;">package com.podongfeng.firstapplication;import com.podongfeng.firstapplication.app.MyApplication;import android.app.Activity;import android.os.Bundle;import android.widget.TextView;public class SecActivity extends Activity {private TextView textView = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activiry_sec);textView = (TextView) findViewById(R.id.tv_sec);textView.setText(String.valueOf(MyApplication.getMyApplication().getAllViewInteger()));}}</span>


android中使用Application

聯繫我們

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