【问题标题】:onReceive never called in subclass of BroadcastReceiveronReceive 从未在 BroadcastReceiver 的子类中调用
【发布时间】:2015-06-25 00:59:51
【问题描述】:

我真的是 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的方法被成功调用,但是尽管我点击了按钮dismiss,但从未调用方法onReceive

有什么建议吗?

【问题讨论】:

  • NotificationButtonReceiver 是否已在应用程序中注册?如果它在哪里注册?接收方有广播吗?
  • 谢谢!您的评论对我和巴拉特的回答都有帮助!

标签: java android notifications


【解决方案1】:

当您使用 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多