android application類簡單介紹(一)

來源:互聯網
上載者:User

標籤:多個   private   執行個體化   package   extends   div   snippet   size   import   

每次應用程式執行時。應用程式的application類保持執行個體化的狀態。

通過擴充applicaiton類,能夠完畢下面3項工作:

1.對android執行時廣播的應用程式級事件如低低內做出響應。

2.在應用程式組件之間傳遞對象(全域變數)。

3.管理和維護多個應用程式組件使用的資源。

當中,後兩項工作通過使用單例類來完畢會更好。application會在建立應用程式進程的時候執行個體化。

以下是擴充Application的示範範例代碼:

import android.app.Application;public class MyApplication extends Application {private static MyApplication singleton;//返回應用程式執行個體public static MyApplication getInstance(){return singleton;}@Overridepublic void onCreate() {super.onCreate();singleton = this;}}
 在建立好自己的Application後,在mainfest裡面的application注冊。例如以下:

<application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:name="com.example.i18n.MyApplication"        android:theme="@style/AppTheme" >

至於get 和set :

假如MyApplication有變數str,並提供getter和setter,例如以下:

package com.example.i18n;import android.app.Application;public class MyApplication extends Application {private static MyApplication singleton;private String str;//返回應用程式執行個體public static MyApplication getInstance(){return singleton;}@Overridepublic void onCreate() {super.onCreate();singleton = this;}public String getStr() {return str;}public void setStr(String str) {this.str = str;}}

使用str和賦值:

MyApplication.getInstance().setStr("hello,bitch!");String mystr = MyApplication.getInstance().getStr();Log.e("str",mystr+"");


先寫到這裡。

晚安。

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.