android BroadcastReceiver有时会在onReceive上抛出NullPointerException
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 receiver com.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){
为什么会这样?
答案
而不是mService.getSystemService(..)
方法中的onReceive
,使用context.getSystemService(...)
以上是关于android BroadcastReceiver有时会在onReceive上抛出NullPointerException的主要内容,如果未能解决你的问题,请参考以下文章
Android_组件_BroadcastReceiver基础
Android BroadcastReceiver广播:基本使用
Android -- BroadCastReceiver的简单使用