【问题标题】:Starting JobIntentService from PendingIntent (Notification button)?从 PendingIntent(通知按钮)启动 JobIntentService?
【发布时间】:2018-02-18 18:14:59
【问题描述】:

在我的应用程序中,我有一个通知按钮,它使用 IntentService 在后台触发一个简短的网络请求。在这里显示 GUI 是没有意义的,这就是我使用服务而不是 Activity 的原因。请参阅下面的代码。

// Build the Intent used to start the NotifActionService
Intent buttonActionIntent = new Intent(this, NotifActionService.class);
buttonActionIntent.setAction(NotifActionService.ACTION_SEND_CONFIRM);
buttonActionIntent.putExtra(NotifActionService.EXTRA_CONFIRM_ID, confirmId);
buttonActionIntent.putExtra(NotifActionService.EXTRA_NOTIF_ID, notifId);

// Build the PendingIntent used to trigger the action
PendingIntent pendingIntentConfirm = PendingIntent.getService(this, 0, buttonActionIntent, PendingIntent.FLAG_UPDATE_CURRENT);

这很可靠,但由于 Android 8.0 中的新背景限制让我想改用 JobIntentService。更新服务代码本身似乎非常简单,但我不知道如何通过 PendingIntent 启动它,这是通知操作所需要的。

我怎样才能做到这一点?

在 API 级别 26+ 上使用 PendingIntent.getForegroundService(...) 并在 API 级别 25 及以下级别上使用当前代码会更好吗?这将需要我手动处理唤醒锁、线程并在 Android 8.0+ 上导致丑陋的通知。

编辑:除了将 IntentService 直接转换为 JobIntentService 之外,下面是我最终得到的代码。

BroadcastReceiver 只是将意图类更改为我的 JobIntentService 并运行其 enqueueWork 方法:

public class NotifiActionReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        intent.setClass(context, NotifActionService.class);
        NotifActionService.enqueueWork(context, intent);
    }
}

原代码的修改版:

// Build the Intent used to start the NotifActionReceiver
Intent buttonActionIntent = new Intent(this, NotifActionReceiver.class);
buttonActionIntent.setAction(NotifActionService.ACTION_SEND_CONFIRM);
buttonActionIntent.putExtra(NotifActionService.EXTRA_CONFIRM_ID, confirmId);
buttonActionIntent.putExtra(NotifActionService.EXTRA_NOTIF_ID, notifId);

// Build the PendingIntent used to trigger the action
PendingIntent pendingIntentConfirm = PendingIntent.getBroadcast(this, 0, buttonActionIntent, PendingIntent.FLAG_UPDATE_CURRENT);

【问题讨论】:

    标签: android android-8.0-oreo


    【解决方案1】:

    我怎样才能做到这一点?

    使用BroadcastReceivergetBroadcast() PendingIntent,然后让接收者从其onReceive() 方法调用JobIntentService enqueueWork() 方法。我承认我没有尝试过这个,但是 AFAIK 它应该可以工作。

    【讨论】:

    • 是的,这可行。一旦我确定它确实解决了我在新旧平台上的问题,我会试一试并将您的答案标记为已接受。
    • 你成功了吗?而且,如果是的话,你能举个例子吗? THX
    • @tomseitz 我还没有尝试过,因为到目前为止我专注于其他更改。在这一点上,我真的没有从针对 Android O 中获得太多好处。我更愿意这样做,因为我喜欢以最新版本为目标。你有同样的问题吗?
    • 谁能举个例子,你是怎么做到的。我正在为我的应用小部件尝试它。
    • @LoveForDroid:我不确定您的问题中的“它”是什么,但我的答案中的所有内容都应该有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多