2017-02-24 49 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

感谢您详细的解释。现在很清楚。谢谢你的解决方法,但正如你所说我不能在那里做网络。所以我会摆脱处理程序,因为我已经显示,无论如何,我在过程中学到了新的东西:) –

相关问题