PendingIntent不会被发送

时间:2017-07-18 06:38:53

标签: android android-notifications android-pendingintent

我正在尝试按下按钮时发送通知,当用户点击通知时,活动ActPending应该开始。 以下发布的代码既没有发送通知也没有启动ActPending

请让我知道我做错了什么以及如何解决它。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.act_main);

    mBtn_send = (Button) findViewById(R.id.btn_send_notification);

    mBtn_send.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                send();
            } catch (PendingIntent.CanceledException e) {
                e.printStackTrace();
            }
        }
    });
}

public void send() throws PendingIntent.CanceledException {
    Intent intAct = new Intent(this, ActPending.class);
    PendingIntent pending = PendingIntent.getActivity(this, 1, intAct, PendingIntent.FLAG_UPDATE_CURRENT);
    //pending.send();

    String title = getString(R.string.app_name);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setStyle(new NotificationCompat.BigTextStyle().bigText("BIG TEXT")).setContentText("CONTENTS").setContentTitle(title);
    builder.setContentIntent(pending).setAutoCancel(true);

    ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(1, builder.build());
}

1 个答案:

答案 0 :(得分:0)

粘贴此代码:

        Intent intent = new Intent(this, ActPending.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), new Random().nextInt(), intent,PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

        //icon appears in device notification bar and right hand corner of notification
        builder.setSmallIcon(R.mipmap.ic_launcher);


        // Set the intent that will fire when the user taps the notification.
        builder.setContentIntent(pendingIntent);

        // Large icon appears on the left of the notification (it accepts Bitmap argument only)
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));

        // Content title, which appears in large type at the top of the notification
        builder.setContentTitle("Notifications Title");

        // Content text, which appears in smaller text below the title
        builder.setContentText("Your notification content here.");

        // The subtext, which appears under the text on newer devices.
        // This will show-up in the devices with Android 4.2 and above only
        builder.setSubText("Tap to view documentation about notifications.");

        //Will clear the notification once it has beeen clicked
        builder.setAutoCancel(true);



        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(5434, builder.build());