2012-06-06 26 views
1

我學習Android和跨越的例子就是像意圖衍生服務調用明確的超類的構造函數

public static class A extends IntentService { 
    public A() { 
     super("AppWidget$A"); 
    } 
} 

有人能告訴我,爲什麼我們要調用父類(IntentService)明確的構造函數?參數字符串表示什麼?

回答

3

它僅用於調試。下面是一個使用這個的IntentService源代碼的一部分:

public abstract class IntentService extends Service { 

    ... 
    private String mName; 
    ... 

    /** 
    * Creates an IntentService. Invoked by your subclass's constructor. 
    * 
    * @param name Used to name the worker thread, important only for debugging. 
    */ 
    public IntentService(String name) { 
     super(); 
     mName = name; 
    } 

    ... 

    @Override 
    public void onCreate() { 
     super.onCreate(); 
     HandlerThread thread = new HandlerThread("IntentService[" + mName + "]"); 
     thread.start(); 

     mServiceLooper = thread.getLooper(); 
     mServiceHandler = new ServiceHandler(mServiceLooper); 
    } 

    ... 
} 
+0

你可以請解釋一下onCreate代碼,是否有必要以 $ 的形式傳遞參數,還是隻是一個約定? – deXter

+1

@deXter:我只會解釋'mName'的用法。正如你看到的,它用於爲處理程序線程創建一個名稱(有一個接受名稱的線程構造函數)。這隻在需要記錄正在運行的線程時纔有用。因此,Android內部使用它來進行人性化的日誌記錄。基本上這裏發生的是準備在非UI後臺線程上執行IntentService負載。 –

+1

@deXter:關於'<調用類> $ <工作類>' - 我相信這是代碼編寫者決定使用他/她自己的模式。在這種情況下,我通常只需傳遞我的IntentService類的名稱。 –

0

IntentService有一個構造函數的字符串參數 「名字」。我發現,它的唯一用途是命名爲IntentService工作線程。該線程被命名爲IntentService [name]。

相關問題