我正在使用以下意图服务来处理GCM消息,它几乎所有时间都完美地工作,除了极少数情况下它会抛出一个空指针异常,因为它似乎是一个空的上下文,如周围的代码所示明星,我应该使用“这个”以外的其他东西吗?如果是,那么我应该使用什么?
public class GcmIntentService extends IntentService {
NetworkThread thread;
static final String TAG = "IntentService";
public GcmIntentService() {
super(TAG);
thread = new NetworkThread();
thread.start();
thread.getLooper();
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) {
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
.equals(messageType)) {
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
.equals(messageType)) {
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
.equals(messageType)) {
if (action.equalsIgnoreCase("NEW_MESSAGE")) {
***********************************
thread.handleMessage(new JsonObj(extras.getString("message"), this ));
***********************************
}
}
}
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
}
线程处理程序代码如下,
public class NetworkThread extends HandlerThread {
public void handleMessage(JsonObj jObj) {
mHandler.obtainMessage(HANDLE_MESSAGE, jObj)//this is line 153
.sendToTarget();
}
protected void onLooperPrepared() {
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
//here I handle different kinds of messages
case HANDLE_MESSAGE:
break;
}
}
}
错误低于
10-13 22:08:41.159: E/AndroidRuntime(18279): FATAL EXCEPTION: IntentService[GcmIntentService]
10-13 22:08:41.159: E/AndroidRuntime(18279): Process: com.messaging.android, PID: 18279
10-13 22:08:41.159: E/AndroidRuntime(18279): java.lang.NullPointerException
10-13 22:08:41.159: E/AndroidRuntime(18279): at com.messaging.android.NetworkThread.handleMessage(NetworkThread.java:153)
10-13 22:08:41.159: E/AndroidRuntime(18279): at com.messaging.android.GcmIntentService.onHandleIntent(GcmIntentService.java:106)
10-13 22:08:41.159: E/AndroidRuntime(18279): at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
10-13 22:08:41.159: E/AndroidRuntime(18279): at android.os.Handler.dispatchMessage(Handler.java:102)
10-13 22:08:41.159: E/AndroidRuntime(18279): at android.os.Looper.loop(Looper.java:136)
10-13 22:08:41.159: E/AndroidRuntime(18279): at android.os.HandlerThread.run(HandlerThread.java:61)