【问题标题】:Status notifications talking to Android Service与 Android 服务对话的状态通知
【发布时间】:2014-03-06 15:21:18
【问题描述】:

我有一个 Android Service,它会创建一个通知和相应的状态图标。当用户对通知做出反应时,我希望将意图传递给我的Service。这一切看起来都很简单。

我可以创建通知,并且图标会出现在状态栏中,当我拉下窗帘时,我会看到我的通知。当我点击通知时,没有任何反应。当我什么都不说时,我的意思是意图没有传递给我的服务。

我感觉到我在 Notification、Intent 或 PendingIntent 中设置了错误的内容,但我很难弄清楚哪些是不正确的。

这是代码(全部在 Service 类中):

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(TAG, "onStartCommand(): intent=" + intent + ", startId=" + startId);
    Log.d(TAG, LKServiceMessages.dumpExtras(intent));

    String command = LKServiceMessages.getMessageKind(intent);


    if (command.equals(K_STATUS_NOTIFICATION)) {
        cancelNotification(0);
        command = null;
    } else {
        displayStatusNotification();
    }

    if (command == null) {
        Log.d(TAG, "Non-library command received - ignoring...");
    } else {
        Log.d(TAG, "Handling action - partially processing this action");
    }

    return START_REDELIVER_INTENT;
}

private void displayStatusNotification() {
    Intent intent = new Intent(K_STATUS_NOTIFICATION,null,this,LKService.class);

    PendingIntent pIntent = PendingIntent.getService(LKService.this, 0, intent, 0);

    mNotification = new NotificationCompat.Builder(this)
        .setContentTitle("Bacon")
        .setContentText("Bacon is good for you. Tap to dismiss.")
        .setSmallIcon(R.drawable.ic_status)

        .addAction(R.drawable.ic_status, "Notification getAction()", pIntent)

        .setAutoCancel(true)
        .setDeleteIntent(pIntent)

        .build();

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(0, mLeafNotification);
}

private void cancelNotification(int notificationId) {
    if (Context.NOTIFICATION_SERVICE != null) {
        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager nMgr = (NotificationManager) getApplicationContext().getSystemService(ns);
        nMgr.cancel(notificationId);
    }
}

我做错了什么,但我不知道是什么。我最初的想法是 PendingIntent 是错误的,但是这里有很多我不完全理解的活动部分。

有什么想法吗?

【问题讨论】:

    标签: android android-intent service notifications android-pendingintent


    【解决方案1】:

    在构建通知时,您正在调用

    .setDeleteIntent(pIntent)
    

    这将设置用户删除通知时将使用的Intent。听起来你想打电话

    .setContentIntent(pIntent)
    

    相反。这将设置用户单击通知时将使用的Intent。

    【讨论】:

    • 谢谢。就是这样。现在我的意图正如我所期望的那样到达 onStartCommand()。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-15
    相关资源
    最近更新 更多