JellyBean中的通知 - 添加操作不起作用

时间:2013-02-27 09:26:46

标签: android notifications broadcastreceiver broadcast android-4.2-jelly-bean

使用自定义按钮(使用addAction)构建Jelly Bean通知需要一些帮助。 问题是,我不能让它发挥作用。 基本上,我想使用以下参数构建通知:在通知单击它时必须启用我的一个活动,在按钮单击 - 播放暂停播放器,正在运行,当显示通知时。 我的代码是: 接收器:

private BroadcastReceiver onNotification = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("NOTIFICATION", "Received broadcast");
        Bundle extras = intent.getExtras();
        int state = extras.getInt("state");
        if (state == 1) {
            playPauseMethod();
        }

    }

};

在onCreate活动方法中我添加了:

IntentFilter notif_iff = new IntentFilter(
                    MainService.NOTIF_BROADCAST);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(
                    onNotification, notif_iff);

MainService中的代码如下:

public static final String ACTION = "com.formatbce.mdrive.action.UPDATE_UI";
public static final String NOTIF_BROADCAST = "com.formatbce.mdrive.action.NOTIF_BRD";
Intent in = new Intent(ACTION);
Intent notifInt = new Intent(NOTIF_BROADCAST);
private NotificationManager mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

private void showNotification(final int statusBarIconID,
        final int bigIconID, final int ppIconID, final String contentTitle,
        final String contentText, final boolean showIconOnly) {
    PendingIntent layoutIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, MediaFragmentActivity.class), 0);

        int state = 1;
        notifInt.setAction("blabla");
        notifInt.putExtra("state", state);
        PendingIntent mIntent = PendingIntent.getBroadcast(
                getApplicationContext(), 0, notifInt,
                PendingIntent.FLAG_UPDATE_CURRENT);
        notification = new Notification.Builder(this)
        .setContentTitle(contentTitle).setContentText(contentText)
        .setSmallIcon(bigIconID).setContentIntent(layoutIntent)
        .addAction(ppIconID, null, mIntent)
        .build();
            notification.flags |= Notification.FLAG_ONGOING_EVENT;
            mNM.notify(NOTIFICATION, notification);
}

因此,当我调用showNotification()方法时,会显示通知,并且单击它的正文正常运行。但是,当我点击一个使用addAction设置的按钮时,没有任何变化......我的意思是,即使onReceive()中的那一行也不起作用:

Log.d("NOTIFICATION", "Received broadcast");

这里有什么不对?我大量阅读手册,但无法获得。有人可以解释一下,如何让它运作起来? 谢谢!

P.S。当我将addAction PendingIntent更改为getActivity时,它工作正常,顺便说一句......

1 个答案:

答案 0 :(得分:0)

我认为你在这里遇到的问题是BroadcastReceiver设置不正确。我实际上建议使用服务而不是BroadcastReceiver,这只是因为BroadcastReceiver的延迟(同时,它应该很快发生,这可能不是什么大问题)。

您的Manifest中是否正确设置了BroadcastReceiver?

您是否能够创建仅调用BroadcastReceiver的活动(以验证它是否正常工作)?