onReceive 从未在 BroadcastReceiver 的子类中调用 [英] onReceive never called in subclass of BroadcastReceiver

查看:34
本文介绍了onReceive 从未在 BroadcastReceiver 的子类中调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Android 真的很陌生,我想创建带有取消按钮的通知.代码如下:

I'm really new to Android, and I would like to create notifications with a button to cancel. Here is the code:

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.

The method called myMethod is successfully called, but never the method onReceive despite I click on the button dismiss.

有什么建议吗?

推荐答案

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

As you are using BroadCastReceiver you need to register (@Harsh mentioned).

这里是你需要做的

在 manifest 的 application 标签中添加以下代码

Add below code in manifest's application tag

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

这篇关于onReceive 从未在 BroadcastReceiver 的子类中调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆