2015-01-02 38 views
0

你好我試圖找出如何在下面工作的代碼及其含義:this關鍵字在下面的Android程序上下文

public Context mContext; 
    private Common mApp; 
    public Activity mActivity; 

    mContext = this; 
    mActivity = this; 
    mApp = (Common) mContext.getApplicationContext() 

對我來說,調用一個方法,我需要創建一個類的對象如下

Context mContext = new Context(); 

and then i would be able to invoke the method getAppliationContext as shown above: 

mContext.getApplicationContext() 

有人可以解釋的是,我請了,還怎麼是這個關鍵字的應用above.From我知道什麼是這個關鍵字是對對象本身的引用。 此外,我不明白怎麼「MAPP」被用來作爲一個對象來調用下面的各種方法:

 int startCount = mApp.getSharedPreferences().getInt("START_COUNT", 1); 
    mApp.getSharedPreferences().edit().putInt("START_COUNT", startCount+1).commit(); 

但它沒有被使用new關鍵字創建的,我想,我需要要執行以下操作以調用使用mApp的方法:

Common mApp = new Common();

,這樣我就能夠做到這一點

int startCount = mApp.getSharedPreferences().getInt("START_COUNT", 1); 
    mApp.getSharedPreferences().edit().putInt("START_COUNT", startCount+1).commit(); 

我覺得我在哪裏,在標題是,有沒有其他的辦法,而不只是使用new關鍵字來創建一個對象。

回答

0

您可以通過在任何擴展上下文對象的類上調用getApplicationContext()來獲取上下文。顧名思義,它是應用程序/對象當前狀態的上下文。

例如:ActivityIntentServiceBroadcastReceiver

Context context=getApplicationContext(); 

獲取上下文對象後,就可以調用任何類內部上下文類的方法。

如:

context.startActivity(); 
context.getSharedPrefereces(); 
context.getSystemService(LAYOUT_INFLATER_SERVICE);  
context.getContentResolver().query(uri, ...); 
+0

謝謝,這是否意味着getApplicationContext()方法返回一個Context類型的對象?並且我們將這個對象分配給refernce上下文? – kobewarui

+0

@kobewarui是的,它返回一個類型的對象上下文 – Darish

0

你說得對這個this關鍵字。

Activity類擴展了Context類。 this關鍵字因此可用於Activity類中,以引用Activity對象和Context對象,因爲Activity類型的對象只是Context的擴展版本,因此它的所有方法和變量都被繼承。在這裏看到:http://developer.android.com/reference/android/app/Activity.html

我從來沒有見過Common Android的API中,但它從Context對象鑄造,因此我將把它作爲如果它是一個Context對象。您無需實例化Context對象以調用其方法的原因是因爲在此示例中,您已將Context實例分配給mApp

+0

感謝您的洞察力 – kobewarui

+0

感謝您的洞察力,這是否意味着引用mContext和mActivity通過使用this關鍵字分配給一個對象:mContext = this; mActivity = this; – kobewarui

+0

沒錯。 'mContext'和'mActivity'將被賦予它們寫入的類的對象實例。 – Kavan