IntentService onHandleEvent()无法启动

时间:2016-07-09 01:20:52

标签: android android-intent android-notifications intentservice

我想在点击通知操作按钮时执行一些方法。 我在这个网站上搜索过,但一切似乎都是有序的,我的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>

2 个答案:

答案 0 :(得分:2)

根据Intents and Intent Filters training,您构建的意图是隐含的意图:

  

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

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

  

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

构建你的意图时,你应该使用

// 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);

答案 1 :(得分:0)

在查看您的代码时,我没有看到您告诉PendingIntent将哪个类用于您的服务。

你应该添加:

off.setClass(this, NotificationServiceClass.class);

否则PendingIntent无关。