【问题标题】:IntentService onHandleEvent( ) not startingIntentService onHandleEvent() 未启动
【发布时间】:2016-07-09 01:20:51
【问题描述】:

我希望在单击通知操作按钮时执行一些方法。 我在这个网站上进行了搜索,但一切似乎都井井有条,而且我的 IntentService 没有被调用。

我的操作按钮意图

    Intent off = new Intent();
    off.setAction("action");
    off.putExtra("test", "off");
    PendingIntent pOff = PendingIntent.getService(context, 22, off, 0);

通知生成器

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(/**/)
            .setContentTitle(/**/)
            .setContentText(/**/)
            .addAction(/**/, "Off", pOff)
            .setContentIntent(pendingIntent)
            .setDefaults(Notification.DEFAULT_SOUND)
            .setAutoCancel(true);

意图服务类

public class NotificationServiceClass extends IntentService {

public NotificationServiceClass(String name) {
    super(name);
}

public NotificationServiceClass () {
    super("NotificationServiceClass");
}

@Override
protected void onHandleIntent(Intent intent) {
    Log.i("test", "onHandle");
    if (intent.getAction().equals("action")) {
        Log.i("test", "action");
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            Log.i("test", "onHandleBundleNotNull");
            if (bundle.containsKey("test")) {
                Log.i("test", bundle.getString("test"));
            }
        }
    }
}
}

服务类的 XML 声明

    <service
        android:name=".Manager.NotificationServiceClass"
        android:exported="false">
    </service>

【问题讨论】:

    标签: android android-intent android-notifications intentservice


    【解决方案1】:

    根据Intents and Intent Filters training,您构建的 Intent 是一个隐式 Intent:

    隐式意图不命名特定组件,而是声明要执行的一般操作,这允许来自另一个应用程序的组件处理它。例如,如果您想向用户显示地图上的位置,您可以使用隐式 Intent 请求另一个有能力的应用在地图上显示指定位置。

    您真正想要的是一个明确的意图:根据同一页面上的注释指定要按名称开头的组件:

    注意:启动服务时,您应该始终指定组件名称。否则,您无法确定哪个服务会响应意图,并且用户无法看到哪个服务启动。 p>

    在构建 Intent 时,应该使用

    // Note how you explicitly name the class to use
    Intent off = new Intent(context, NotificationServiceClass.class);
    off.setAction("action");
    off.putExtra("test", "off");
    PendingIntent pOff = PendingIntent.getService(context, 22, off, 0);
    

    【讨论】:

    • 这是一个非常愚蠢的错误。感谢您指出这一点。
    【解决方案2】:

    在查看您的代码时,我没有看到您告诉 PendingIntent 为您的服务使用什么类。

    你应该添加:

    off.setClass(this, NotificationServiceClass.class);
    

    否则与PendingIntent无关。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-04
      • 1970-01-01
      相关资源
      最近更新 更多