onReceive从未在BroadcastReceiver的子类中调用

时间:2015-04-18 00:59:31

标签: java android notifications

我是Android新手,我想创建一个带按钮的通知来取消。这是代码:

public class MainActivity extends ActionBarActivity implements OnItemClickListener
{
    ...stuff here...

    void myMethod()
    {
         Intent buttonIntent = new Intent(this,    NotificationButtonReceiver.class);
         buttonIntent.putExtra("notificationId", 8);

         PendingIntent btPendingIntent = PendingIntent.getBroadcast(this, 0, buttonIntent,0);

         Notification.Builder builder = new Notification.Builder(this)
                .setStyle(new Notification.BigTextStyle().bigText("lorem ipsum dollom"))
                .setAutoCancel(false)
                .setContentTitle("BigText")
                .setContentText("Hello from BigText")
                .setSmallIcon(R.drawable.like)
                .addAction(R.drawable.abc_btn_radio_material, "Dismiss", btPendingIntent);

         Notification notif = builder.build();
         NotificationManager manager = (NotificationManager)this.getSystemService(NOTIFICATION_SERVICE);

         manager.notify(8, notif);
    }

    ...stuff here...
}

public class NotificationButtonReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent) {

        int notificationId = intent.getIntExtra("notificationId", 0);

        Toast.makeText(context.getApplicationContext(), "received",
                Toast.LENGTH_SHORT).show();

        NotificationManager manager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
        manager.cancel(notificationId);
    }
}

成功调用了名为myMethod的方法,但是在我点击onReceive按钮时,从未使用方法dismiss

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

当您使用BroadCastReceiver时,您需要注册(@Harsh提到)。

这里你需要做什么

在清单的application代码

中添加以下代码
    <receiver android:name="your.package.name.NotificationButtonReceiver">
        <intent-filter>
            <action android:name="notify_dismiss" />
        </intent-filter>
    </receiver>

PendingIntent东西

    Intent buttonIntent = new Intent("notify_dismiss");
    buttonIntent.putExtra("notificationId", 8);

    PendingIntent btPendingIntent = PendingIntent.getBroadcast(this, 0, buttonIntent,0);