android BroadcastReceiver有时会在onReceive上抛出NullPointerException

人生难得几回搏,此时不搏待何时。这篇文章主要讲述android BroadcastReceiver有时会在onReceive上抛出NullPointerException相关的知识,希望能为你提供帮助。
我有一个从AlarmManager定期调用的BroadcastReceiver这是BroadcastReceiver:

package com.panic.receiver; import com.panic.service.MyService; import com.panic.utils.Analytics; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.PowerManager; import android.util.Log; public class KeepAliveReceiver extends BroadcastReceiver { final String TAG = "PeriodicUpdateReceiver"; private static MyService mService; @Override public void onReceive(Context context, Intent intent) { try { Log.v(TAG, "onReceive"); PowerManager pm = (PowerManager)mService.getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "PanicButton"); //Acquire the lock wl.acquire(); mService.sendKeepAlive(); //Release the lock wl.release(); } catch(Exception ex) { Analytics.sendException("KeepAliveReceiver onReceive", ex, false); }}public void startPeriodicUpdates(MyService service, int time) { mService = service; AlarmManager am=(AlarmManager)mService.getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(mService, KeepAliveReceiver.class); PendingIntent pi = PendingIntent.getBroadcast(mService, 0, intent, 0); //After after 30 seconds am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), time , pi); } }

接收器每小时调用一次,它运行良好但有时(很少)我得到以下异常:
java.lang.RuntimeException: Unable to start receivercom.ex.receiver.KeepAliveReceiver: java.lang.NullPointerException at android.app.ActivityThread.handleReceiver(ActivityThread.java:2277) at android.app.ActivityThread.access$1500(ActivityThread.java:140) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:4898) 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:1006) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.NullPointerException at com.ex.receiver.KeepAliveReceiver.onReceive(KeepAliveReceiver.java:19) at android.app.ActivityThread.handleReceiver(ActivityThread.java:2270) ... 10 more

第19行是函数头:public void onReceive(Context context,Intent intent){
为什么会这样?
答案【android BroadcastReceiver有时会在onReceive上抛出NullPointerException】而不是mService.getSystemService(..)方法中的onReceive,使用context.getSystemService(...)

    推荐阅读