闹钟代码:无法解析上下文变量

时间:2012-04-12 06:19:39

标签: android

我正在尝试在我的文件中复制粘贴后构建闹钟源代码 编译时,我得到错误,mContext无法解析。 以下是此段代码的链接:http://www.netmite.com/android/mydroid/2.0/packages/apps/AlarmClock/src/com/android/alarmclock/DigitalClock.java

我已经复制了一些使用下面的mContext

的代码
protected void onAttachedToWindow() {
    super.onAttachedToWindow();

    if (Log.LOGV) Log.v("onAttachedToWindow " + this);

    if (mAttached) return;
    mAttached = true;

    if (mAnimate) {
        setBackgroundResource(R.drawable.animate_circle);
        /* Start the animation (looped playback by default). */
        ((AnimationDrawable) getBackground()).start();
    }

    if (mLive) {
        /* monitor time ticks, time changed, timezone */
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_TIME_TICK);
        filter.addAction(Intent.ACTION_TIME_CHANGED);
        filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
        mContext.registerReceiver(mIntentReceiver, filter, null, mHandler);

    }

    /* monitor 12/24-hour display preference */
    mFormatChangeObserver = new FormatChangeObserver();

    mContext.getContentResolver().registerContentObserver(

            Settings.System.CONTENT_URI, true, mFormatChangeObserver); 

    updateTime();
}

private void setDateFormat() {      

    mFormat = Alarms.get24HourMode(mContext) ? Alarms.M24 : M12;
    mAmPm.setShowAmPm(mFormat == M12);
}

要解决此编译错误,我将此语句放在我的代码中

Context mContext;

但是,虽然编译错误已经解决,但在模拟器中启动时,应用程序会抛出异常并在不启动的情况下退出。

有人可以告诉我如何使用这个上下文的东西,或者作为替代方案写的shud shud?

4 个答案:

答案 0 :(得分:3)

您需要启动mContext。有一些不同的方法可以做到这一点。在您可以执行的活动中:

Context mContext = this;

或一般:

Context mContext = getContext();

答案 1 :(得分:2)

使用getContext()方法来获取上下文,而不是mContext。那里的示例代码可能错过了这一部分。

答案 2 :(得分:2)

而不是 mContext 使用 getApplicationContext()。希望它能正常工作

答案 3 :(得分:1)

在这里你需要添加你的活动的上下文试试我的代码

mFormat = Alarms.get24HourMode(this) ? Alarms.M24 : M12;
        mAmPm.setShowAmPm(mFormat == M12)

;

需要更多代码

但我的建议是你在这个视图或活动中获取你的mContext变量的上下文,它会起作用

相关问题