1

我有一个从 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) {

为什么会这样?

4

1 回答 1

1

而不是mService.getSystemService(..)onReceive方法中,使用context.getSystemService(...)

于 2013-09-14T18:34:37.923 回答