接收广播意图ACTION_BATTERY_CHANGED时出现错误

3

我正在尝试通过使用广播接收器获取电池信息并将其存储在数据库中。我希望只在需要时才获取它,但我愿意保留一个仅运行记录的数据库。无论如何,问题是我的应用程序会崩溃,并出现以下错误:

java.lang.RuntimeException: Error receiving broadcast Intent { act=android.intent.action.BATTERY_CHANGED flg=0x60000010 (has extras) }
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:765)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4918)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x7f04006b
at android.content.res.Resources.getText(Resources.java:242)
at android.widget.TextView.setText(TextView.java:3773)
at com.Eddiecubed44.drunk.buddy.Main$2.onReceive(Main.java:180)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:755)

当我说崩溃时,我的意思是彻底崩溃。每次运行带有此代码的手机都会自动重启。
我使用调试器进行了逐步调试,但没有捕获到错误。我在主活动类中创建广播接收器,如下所示:

    BroadcastReceiver batteryReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            int temp = -1;
            TextView tempText;

            tempText = (TextView)findViewById(R.id.mybatttemptxt);
            temp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1);
            tempText.setText(R.string.temp + temp);

这是我注册广播接收器的方式。

this.registerReceiver(this.batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

我在onStart方法中进行了这个操作。问题是,如果我将this.batteryReceiver替换为null,我的应用程序可以运行,但是应用程序什么也不做。在此应用程序中未调用或使用接收器。

如果有影响,这是我正在使用的: 在root galaxy s3上测试 应用程序使用目标lvl15 api min 11。


1
发布您的清单权限 - Hoan Nguyen
1
关于@HoanNguyen的评论:更有可能是您在布局中引用元素不正确。但要知道这一点,您需要发布更大的代码片段和日志记录。 - DigCamara
你的整个接收器代码。 - Hoan Nguyen
看起来//将一些信息发布到TextView中可能是错误的地方。 - Hoan Nguyen
1
“第180行代码发生在'temp = intent.putIntExtra('行上。”--不,它并没有。堆栈跟踪清楚地显示您的错误来自于对setText()的调用。无论是在您的简略代码列表中的setText()调用还是其他地方,只有您自己能够确定。 - CommonsWare
显示剩余6条评论
2个回答

3

您在Main.java的第180行使用了不存在的资源。

我猜测这个资源是R.string.temp,但由于您甚至没有发布文件的名称,所以这只是一个猜测。

我刚刚发现问题所在:

tempText.setText(R.string.temp + temp);
文档允许将文本直接设置为资源标识符。但是,通过将temp添加到该值中,您已更改它并请求不存在的资源。

纠正方法之一是:

String resourceTemp = context.getString(R.string.temp);
tempText.setText(resourceTemp + " " + temp);

所以我假设如果我决定将其编写为单个字符串而不使用R.string.temp并包含“script”。 - eddiecubed

1
你将资源id添加到temp中,从而更改了id,你应该改为
tempText.setText(context.getString(R.string.temp) + temp);

圣物,我不认为我能在这里谈论,但它让一切变得更好。谢谢。我没想到这是一个初级错误。 - eddiecubed
@DigCamara 我没注意到,不是吗?不过,你的回答还是很好的。 - Hoan Nguyen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接