我的用户正在慢慢迁移到 ICS(Android 4.0 及更高版本),从那时起,我可以看到出现新的崩溃报告......看起来我的 WakefulIntentService 实现触发了以下错误:
java.lang.NullPointerException at com.cousinHub.meteo.AppService.doWakefulWork(AppService.java:104) at com.cousinHub.meteo.WakefulIntentService.onHandleIntent(WakefulIntentService.java:70) at android.app.IntentService$ServiceHandler.handleMessage( IntentService.java:59) 在 android.os.Handler.dispatchMessage(Handler.java:99) 在 android.os.Looper.loop(Looper.java:123) 在 android.os.HandlerThread.run(HandlerThread.java:60 )
第 70 行在 onHandleIntent 中查找问题:
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
abstract public class WakefulIntentService extends IntentService {
abstract protected void doWakefulWork(Intent intent);
public static final String LOCK_NAME_STATIC="com.commonsware.cwac.wakeful.WakefulIntentService";
private static PowerManager.WakeLock lockStatic=null;
public static void acquireStaticLock(Context context) {
getLock(context).acquire();
}
synchronized private static PowerManager.WakeLock getLock(Context context) {
if (lockStatic==null) {
PowerManager mgr=(PowerManager)context.getSystemService(Context.POWER_SERVICE);
lockStatic=mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, LOCK_NAME_STATIC);
lockStatic.setReferenceCounted(true);
}
return(lockStatic);
}
public static void sendWakefulWork(Context ctxt, Intent i) {
acquireStaticLock(ctxt);
ctxt.startService(i);
}
@SuppressWarnings("unchecked")
public static void sendWakefulWork(Context ctxt, Class clsService) {
sendWakefulWork(ctxt, new Intent(ctxt, clsService));
}
public WakefulIntentService(String name) {
super(name);
}
@Override
public void onStart(Intent intent, int startId) {
if (!getLock(this).isHeld()) { // fail-safe for crash restart
getLock(this).acquire();
}
super.onStart(intent, startId);
}
@Override
final protected void onHandleIntent(Intent intent) {
try {
doWakefulWork(intent);
}
finally {
getLock(this).release();
}
}
}
知道为什么这段代码可以在 Gingerbread (Android < 4.0) 上正常工作并且现在中断了吗?
try {
doWakefulWork(intent);
}
=> 由于某种原因,意图看起来为空?
或者可能是触发 NullPointer Exception 的下一个代码块:
finally {
getLock(this).release();
}
- 你会怎么解决这个问题?
这种方式可能吗?
if ((this!=null)&&(intent!=null)) {
try {
doWakefulWork(intent);
}
finally {
getLock(this).release();
}
}