2017-02-24 37 views
1

在我的應用程序中,當我收到推送通知時,我想向服務器發出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 
} 

回答

3

IntentServiceonHandleIntent()會由IntentService創建一個單獨的線程調用。因此,當您撥打new Handler()時,將爲該新線程創建一個處理程序實例。當你使用那個處理器發佈一個runnable時,它將被髮布到新線程的處理程序上,線程的onHandleMessage將被調用,它由IntentService實現,並被忽略。

如果修改了上面的代碼如下,將工作

public static void syncData(final Context content) { 
new Handler(Looper.getMainLooper()).post(new Runnable() { 
    @Override public void run() { 
     // ... my web request 
    } 
}); 
} 

但在上述Runable將在主線程調用,你不應該進行網絡操作

+0

感謝您詳細的解釋。現在很清楚。謝謝你的解決方法,但正如你所說我不能在那裏做網絡。所以我會擺脫處理程序,因爲我已經顯示,無論如何,我在過程中學到了新的東西:) –

相關問題