从推送通知 IntentService 中发布时可在处理程序中运行而不是 运行

Runnable in Handler not run when posted from inside a push notification IntentService

在我的应用程序中,当我收到推送通知时,我想向服务器发出网络请求以更新一些数据。这是我对 IntentService.onHandleIntent() 的实现,它在我收到推送时调用:

@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 运行 中,但事实是 运行nable 不是 运行。我什至检查了 post() 的 return 值,它是 true。如果我从 activity 或片段等内部调用 syncData(),它会按预期工作,但不会在 IntentService 中工作。 这是为什么?

如果改为这样做,一切正常:

public static void syncData(final Context content) {
    // ... my web request
}

IntentService 中,onHandleIntent() 将在 IntentService 创建的单独线程上调用。因此,当您调用 new Handler() 时,将为该新线程创建一个处理程序实例。当您 post 使用该处理程序的可运行对象时,它将在新线程的处理程序上被 post 编辑,并且线程的 onHandleMessage 将被调用,它由 IntentService 实现并被忽略.

如果您按如下方式修改上面的代码,它将起作用

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

但在上面 Runable 将在您不应执行网络操作的主线程上调用