Android 使用 if else 将侦听器放入通知函数时工作室出错

Android studio error in putting listener in notification function using if else

我试图将 PendingIntent Notification 放入我的 android 项目中,但我遇到了这个错误,它说 找到错误的第一个参数 android view.View.OnClickListener 需要 android 内容,上下文。

我要显示代码错误,else 通知下的 "this" 有错误。

PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
                        Notification noti = new Notification.Builder(this)

这个错误

button.setOnClickListener(new View.OnClickListener() {


    @Override
    public void onClick(View view) {

        int targetId = view.getId();


        if (targetId == R.id.button) {


            Toast.makeText(getApplicationContext(), "You have " + numMessages++ + " message", Toast.LENGTH_SHORT).show();


        } else {
            if (numMessages > 0) {
                Intent intent = new Intent();
                PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
                Notification noti = new Notification.Builder(this)
                        .setTicker("You Have " + numMessages++ + " message")
                        .setContentTitle("OneDiver")
                        .setContentText("Content")
                        .setSmallIcon(R.drawable.ic_od_icon_24dp)
                        .setContentIntent(pIntent).getNotification();
                noti.flags = Notification.FLAG_AUTO_CANCEL;
                NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                notificationManager.notify(0, noti);


            }
        }

如果此代码在 activity 中,比如 YourActivity.class,您需要将 "this" 替换为 "YourActivity.this"。因为在 OnClickListener 中,"this" 指的是 OnClickListener 而不是 activity。