我正在尝试为我的应用程序创建一个小部件,以显示设备的 CPU 使用率、电池电量和剩余 RAM;不是存储空间。
CPU 级别和电池充电代码工作正常;但 RAM 代码没有。我已经读过,为了在 AppWidgetProvider 中使用 .getSystemService() ,您必须将上下文从活动传递到此处。
问题是,当该方法尝试使用 ActivityManager 设置 systemService 时,它会抛出:
01-11 21:29:21.468: E/AndroidRuntime(30759): java.lang.RuntimeException: Unable to instantiate receiver com.example.myfirstappex.AppWidget: java.lang.NullPointerException
我已将问题缩小到这段代码:
import com.example.myfirstappex.MainActivity;
public class AppWidget extends AppWidgetProvider {
...
public long getRam()
{
MemoryInfo mi = new MemoryInfo();
Context mainCon = MainActivity.getAppContext();
ActivityManager activityManager = (ActivityManager)mainCon.getSystemService(Context.ACTIVITY_SERVICE);
activityManager.getMemoryInfo(mi);
long availableMegs = mi.availMem / 1048576L;
//Returning the value
return(availableMegs);
}
...
}
关于如何解决此问题的任何想法?还是在小部件中获取和显示 RAM 的替代方法?
编辑:整个错误日志是:
01-11 22:21:32.426: E/AndroidRuntime(32059): FATAL EXCEPTION: main
01-11 22:21:32.426: E/AndroidRuntime(32059): java.lang.RuntimeException: Unable to start receiver com.example.myfirstappex.AppWidget: java.lang.NullPointerException
01-11 22:21:32.426: E/AndroidRuntime(32059): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2383)
01-11 22:21:32.426: E/AndroidRuntime(32059): at android.app.ActivityThread.access$1500(ActivityThread.java:141)
01-11 22:21:32.426: E/AndroidRuntime(32059): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1310)
01-11 22:21:32.426: E/AndroidRuntime(32059): at android.os.Handler.dispatchMessage(Handler.java:99)
01-11 22:21:32.426: E/AndroidRuntime(32059): at android.os.Looper.loop(Looper.java:137)
01-11 22:21:32.426: E/AndroidRuntime(32059): at android.app.ActivityThread.main(ActivityThread.java:5039)
01-11 22:21:32.426: E/AndroidRuntime(32059): at java.lang.reflect.Method.invokeNative(Native Method)
01-11 22:21:32.426: E/AndroidRuntime(32059): at java.lang.reflect.Method.invoke(Method.java:511)
01-11 22:21:32.426: E/AndroidRuntime(32059): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-11 22:21:32.426: E/AndroidRuntime(32059): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-11 22:21:32.426: E/AndroidRuntime(32059): at dalvik.system.NativeStart.main(Native Method)
01-11 22:21:32.426: E/AndroidRuntime(32059): Caused by: java.lang.NullPointerException
01-11 22:21:32.426: E/AndroidRuntime(32059): at com.example.myfirstappex.AppWidget.getRam(AppWidget.java:82)
01-11 22:21:32.426: E/AndroidRuntime(32059): at com.example.myfirstappex.AppWidget.onUpdate(AppWidget.java:35)
01-11 22:21:32.426: E/AndroidRuntime(32059): at android.appwidget.AppWidgetProvider.onReceive(AppWidgetProvider.java:66)
01-11 22:21:32.426: E/AndroidRuntime(32059): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2376)
01-11 22:21:32.426: E/AndroidRuntime(32059): ... 10 more
这仅在主应用程序未运行时发生。