在我的應用程序中,當我收到推送通知時,我想向服務器發出Web請求以更新一些數據。這是我實現的IntentService.onHandleIntent()
,被稱爲當我收到一推:在處理程序中運行時,無法運行時從推送通知中發佈IntentService
@Override protected void onHandleIntent(Intent intent) {
final NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
final NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
// ... notification setup
notificationManager.notify(Integer.parseInt(intent.getStringExtra("id")), notificationBuilder.build());
// Web request to the server to update data
syncData(this);
// Release the wake lock provided by the WakefulBroadcastReceiver.
PushNotificationsReceiver.completeWakefulIntent(intent);
}
public static void syncData(final Context content) {
new Handler().post(new Runnable() {
@Override public void run() {
// ... my web request
}
});
}
有沒有在包裝中的一個處理器一個Runnable運行的要求毫無道理,但事實是可運行未運行。我甚至檢查了post()
的返回值,它是true
。如果我從活動或片段等內部調用syncData()
,它可以按預期工作,但不在此IntentService
中。 這是爲什麼?
如果做到這一點,而不是一切工作正常:
public static void syncData(final Context content) {
// ... my web request
}
感謝您詳細的解釋。現在很清楚。謝謝你的解決方法,但正如你所說我不能在那裏做網絡。所以我會擺脫處理程序,因爲我已經顯示,無論如何,我在過程中學到了新的東西:) –