Android官方推薦全域對象傳遞資料

來源:互聯網
上載者:User

雖然使用靜態變數可以傳遞任何類型的資料,但官方並不建議這樣做。如果在類中有大量使用靜態變數(尤其是使用很佔資源的變數,例如,Bitmap對象)可能會造成記憶體溢出異常,而且還可能因為靜態變數在很多類中出現而造成代碼難以維護和混亂,因此,用全域對象可以進行傳遞,這種方式可以完全取代靜態變數。

Android中的全域對象範圍:除非將Android程式徹底清除出記憶體,否則全域對象將一直可以訪問。

1.首先建一個全域類:

package cn.jiabin.demo.view;import android.app.Application;public class MyApplication extends Application {public String name;public int age;}

2.將這個全域類配置到AndroidManifest.xml檔案中:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="cn.jiabin.demo.view"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk android:minSdkVersion="8" />    <application        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:name=".MyApplication" >        <activity            android:label="@string/app_name"            android:name=".MyDemoActivity" >            <intent-filter >                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <activity android:name=".A" />    </application></manifest>

3.在正常的類中使用:

MyApplication myApp = (MyApplication) getApplication();myApp.name = "張三";myApp.age = 23;

官方推薦這種方式傳遞資料。

著作權,如需轉載,註明出處,謝謝合作。瀋陽--斌子。

註明:QQ技術交流群:108614806   感興趣的加一下。

相關文章

聯繫我們

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