【问题标题】:Intent Service derived call explicit super class constructorIntent Service 派生调用显式超类构造函数
【发布时间】:2012-06-06 11:29:51
【问题描述】:

我正在学习android,遇到了一个例子

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

谁能告诉我为什么我们必须显式调用超类的构造函数(IntentService)?参数字符串是什么意思?

【问题讨论】:

    标签: android android-intent android-widget


    【解决方案1】:

    它仅用于调试。下面是使用这个的 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);
        }
    
        ...
    }
    

    【讨论】:

    • 能否请您稍微解释一下 onCreate 代码,是否需要以 $ 形式传递参数,还是只是一种约定?
    • @deXter:我将仅对mName 的用法进行解释。如您所见,它用于为处理程序线程创建一个名称(有一个接受名称的 Thread 构造函数)。这仅在您需要记录当前正在运行的线程时才有用。因此,Android 内部的某个地方使用它来进行人类友好的日志记录。基本上这里发生的事情是准备在非 UI 后台线程上执行 IntentService 负载。
    • @deXter:关于<calling class>$<working class> - 我相信这是代码编写者决定用作他/她自己的模式的东西。在这种情况下,我通常只是传递我的 IntentService 类的名称。
    【解决方案2】:

    IntentService 有一个接受字符串参数的构造函数 “名称”。我发现它的唯一用途是为 IntentService 命名工作线程。这个线程被命名为 IntentService [name]。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-19
      • 2012-11-06
      • 2018-07-21
      • 1970-01-01
      • 2015-08-18
      • 2018-07-16
      • 2013-01-28
      • 2011-05-03
      相关资源
      最近更新 更多