【问题标题】:Android Wear Intent from notification not firing通知中的 Android Wear Intent 未触发
【发布时间】:2016-10-27 18:32:07
【问题描述】:

我正在编写一个小型 Android Wear 应用程序,它的部分工作是创建一个包含两个操作的持续通知: 1. 再次打开应用程序。 2. 关闭(清除状态)应用。

第一个动作(打开)完美运行(即:我按下按钮,动作被执行)。但第二个动作不会触发任何东西。

这是通知本身的代码:

    // First action: open app's main activity
    Intent actionIntent = new Intent(this, MainActivity.class);
    PendingIntent actionPendingIntent =
            PendingIntent.getActivity(this, 0, actionIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Action action =
            new NotificationCompat.Action.Builder(R.drawable.close_button,
                    getString(R.string.open_app), actionPendingIntent)
                    .build();

    // Second action: clear the state of the app, by firing a service which will do so
    Intent tnsIntent = new Intent(this, TimerNotificationService.class);
    PendingIntent tnsPendingIntent =
            PendingIntent.getActivity(this, 0, tnsIntent,
                    PendingIntent.FLAG_CANCEL_CURRENT);

    NotificationCompat.Action closeAppAction =
            new NotificationCompat.Action.Builder(R.drawable.close_button,
                    getString(R.string.close_app), tnsPendingIntent)
                    .build();

    return new  NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.common_signin_btn_icon_dark)
            .setContentTitle(getString(R.string.time_tracking_on))
            .setContentText("Tap to open app")
            .setWhen(System.currentTimeMillis())
            .setOngoing(true)
            .extend(new NotificationCompat.WearableExtender().addAction(action).addAction(closeAppAction))
            .setLocalOnly(true)
            .build();

注意:我尝试以另一种方式实例化 tnsIntent Intent tnsIntent = new Intent(ACTION_TERMINATE_TRACKING, null, this, TimerNotificationService.class);,但它没有改变任何东西。

服务看起来像这样:

public class TimerNotificationService extends IntentService {
    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        clearSomeState();
    }
}

我在调试模式下运行应用程序并在服务的onHandleIntent() 中放置了一个断点,但我没有命中断点,因此服务甚至没有收到意图。我是否错过了一些我应该在某处为服务做的意图注册电话? (在清单中?)

【问题讨论】:

    标签: android android-intent wear-os android-wear-notification


    【解决方案1】:

    如果tnsPendingIntent 正在启动Service,它应该从PendingIntent.getService 设置,而不是PendingIntent.getActivity,如您的代码sn-p 所示。 (reference)

    【讨论】:

    • 好收获!这确实是问题之一。不过,主要问题是我必须在(磨损)应用程序的AndroidManifest.xml 中声明我的服务。没有它,Android 永远不会调用它:“所有服务必须由清单文件中的 元素表示。任何未在其中声明的服务都不会被系统看到并且永远不会运行。” (reference) 如果你能把它包含在你的答案中,那就完美了。谢谢!
    • 我实际上考虑过提及这一点,但由于您还没有发布您的清单,我认为批评它是冒昧的。 :^) 很高兴你把它整理好了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-11
    • 2016-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多