Android通知.addAction在api中不推荐使用

自从addAction(int icon, CharSequence title, PendingIntent intent)被弃用以来,在API 23向通知添加操作的正确方法是什么? 找不到任何例子,谢谢。

我的旧操作: .addAction(R.drawable.ic_prev, "Previous", prevPendingIntent)

Solutions Collecting From Web of "Android通知.addAction在api中不推荐使用"

而不是这个:

addAction(int图标,CharSequence标题,PendingIntent意图)

此方法在API级别23中已被弃用。

使用:

addAction(Notification.Action动作)

这一切都在开发人员的文档!

所以要使用这个:

首先用NotificationCompat.Action.Builder构build你的动作

 NotificationCompat.Action action = new NotificationCompat.Action.Builder(R.drawable.ic_prev, "Previous", prevPendingIntent).build(); 

注意:使用NotificationCompat.Action

而不是将其添加到您的通知:

 yournotification.addAction(action); 

如果API等级> = 23(棉花糖),则在第一个参数中使用Icon类,

https://developer.android.com/reference/android/app/Notification.Action.Builder.html

https://developer.android.com/sdk/api_diff/23/changes/android.app.Notification.Action.Builder.html

例)

 Notification.Action action = new Notification.Action.Builder( Icon.createWithResource(this, R.drawable.ic_prev), "action string", pendingIntent).build(); 
 //Exemple of notification with Button private void scheduleNotificationWithButton(String message) { int notifReCode = 1; //What happen when you will click on button Intent intent = new Intent(this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, intent, PendingIntent.FLAG_ONE_SHOT); //Button NotificationCompat.Action action = new NotificationCompat.Action.Builder(R.mipmap.ic_launcher, "Go", pendingIntent).build(); //Notification Notification notification = new NotificationCompat.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) .setContentText("Back to Application ?") .setContentTitle("Amazing news") .addAction(action) //add buton .build(); //Send notification NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(1, notification); } 

您只需使用NotificationCompat.Builder构build器代替Notification.Builder构build器,因为NotificationCompat.Builder允许您在Android版本4.1

通过使用NotificationCompat.builder解决:

  String strTitle = getString(R.string.new_message); String strText = getString(R.string.hi_whats_up); Intent intent = new Intent(this, NotificationView.class); intent.putExtra("title", strTitle); intent.putExtra("text", strText); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) .setTicker("Notification Ticker") .setContentTitle("Notification Title") .setContentText("Notification Text") .addAction(R.mipmap.ic_launcher, "Notification Action", pendingIntent) .setContentIntent(pendingIntent) .setAutoCancel(true); NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); notificationManager.notify(0, builder.build());