Android--全局變量是用public&nbsp…

 在Android中編寫過程序的開發人員都知道。在Activity、Service等組件之間傳遞數據(尤其是複雜類型的數據)很不方便。一般可以使用Intent來傳遞可序列化或簡單類型的數據。看下面的代碼。
Intent intent = new Intent( this , Test. class );
intent.putExtra(
"
param1
"
, "
data1
"
);
intent.putExtra(
"
intParam1
"
, 20
);
startActivity(intent);


這樣就ok了。在當前Activity將兩個值傳到了Test中。但如果遇到不可序列化的數據,如Bitmap、InputStream等,intent就無能爲力了。因此,我們很自然地會想到另外一種方法,靜態變量。如下面的代碼所示:

public class Product extends Activity
{
public
static
Bitmap mBitmap;

}


對於上面的代碼來說,其他任何類可以直接使用Product中的mBitmap變量。這麼做很easy、也很cool,但卻very very wrong。我們千萬不要以爲Davlik虛擬機的垃圾回收器會幫助我們回收不需要的內存垃圾。事實上,回收器並不可靠,尤其是手機上,是更加的不可靠。 因此,除非我們要使自己的程序變得越來越糟糕,否則儘量遠離static。

注:如果經常使用static的Bitmap、Drawable等變量。可能就會拋出一個在Android系統中非常著名的異常(以前budget這個單詞一直記不住什麼意思,自從經常拋出這個異常後,這個單詞終於爛熟於心了,

ERROR/AndroidRuntime(4958): Caused by: java.lang.OutOfMemoryError: bitmap size exceeds VM budget


如果不使用static,總得有方法來代替它(儘管我很喜歡public static,我相信很多人也喜歡它,但爲了我們的程序,建議還是忍痛割愛吧),那麼這個新的解決方案就是本文的主題,這就是Application Context,相當於Web程序的Application,它的生命週期和應用程序一樣長(這個我喜歡)。

那麼現在來看看如何使用這個Application Context。我們可以通過Context.getApplicationContext或Context.getApplication方法獲得 Application Context。但要注意,我們獲得的只是Context對象,而更理想的方法是獲得一個類的對象。ok,說幹就幹,下面來定義一個類。

package net.blogjava.mobile1;

import
android.app.Application;
import
android.graphics.Bitmap;

public
class
MyApp extends
Application
{
private
Bitmap mBitmap;

public
Bitmap getBitmap()
{
return
mBitmap;
}

public
void
setBitmap(Bitmap bitmap)
{
this
.mBitmap =
bitmap;
}

}


上面這個類和普通的類沒什麼本質的不同。但該類是Application的子類。對了,這就是使用Application Context的第一步,定義一個繼承自Application的類。然後呢,就在這個類中定義任何我們想使其全局存在的變量了,如本例中的 Bitmap。下面還需要一個重要的步驟,就是在標籤中使用android:name屬性來指定這個類,代碼如 下:

<</SPAN> application android:name =".MyApp" android:icon ="@drawable/icon" android:label ="@string/app_name" >

</</SPAN> application?


接下來的最後一步就是向MyApp對象中存入Bitmap對象,或從MyApp對象中取出Bitmap對象了,存入Bitmap對象的代碼如下:

MyApp myApp = (MyApp)getApplication();

Bitmap bitmap
=
BitmapFactory.decodeResource(
this
.getResources(), R.drawable.icon);

myApp.setBitmap(bitmap);


獲得Bitmap對象的代碼:

ImageView imageview = (ImageView)findViewById(R.id.ivImageView);

MyApp myApp
=
(MyApp)getApplication();

imageview.setImageBitmap(myApp.getBitmap());
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章