How to implement the deprecated methods of Notification

后端 未结 2 1394
甜味超标
甜味超标 2020-11-30 03:34

I have a small problem but dont understand how to get out of this.

I created a class for providing Notifications, but these lines are marked deprecated:



        
相关标签:
2条回答
  • 2020-11-30 03:46

    This is the correct way to get the level.

     final int sdkVersion = Integer.parseInt(Build.VERSION.SDK);
    
    if (sdkVersion < Build.VERSION_CODES.HONEYCOMB)
    {
    ...
    Notification notification = new Notification(icon, text, time); // deprecated in API level 11
    ...
    notification.setLatestEventInfo(this, title, text, contentIntent); // deprecated in API level 11
    ...
    }
    else
    {
    Notification noti = new Notification.Builder(mContext)
             .setContentTitle("New mail from " + sender.toString())
             .setContentText(subject)
             .setSmallIcon(R.drawable.new_mail)
             .setLargeIcon(aBitmap)
             .build(); // available from API level 11 and onwards
    } 
    

    All the version codes can be found at this developer link.

    0 讨论(0)
  • 2020-11-30 03:57

    This is how i ended up to the solution:

    if (currentapiVersion < android.os.Build.VERSION_CODES.HONEYCOMB) {
    
                notification = new Notification(icon, text, time);
                notification.setLatestEventInfo(this, title, text, contentIntent); // This method is removed from the Android 6.0
                notification.flags |= Notification.FLAG_AUTO_CANCEL;
                mNM.notify(NOTIFICATION, notification);
            } else {
                NotificationCompat.Builder builder = new NotificationCompat.Builder(
                        this);
                notification = builder.setContentIntent(contentIntent)
                        .setSmallIcon(icon).setTicker(text).setWhen(time)
                        .setAutoCancel(true).setContentTitle(title)
                        .setContentText(text).build();
    
                mNM.notify(NOTIFICATION, notification);
            }
    

    Edit:

    The above solution works. Still, since, NotificationCompat.Builder class was introduced, we can skip the if condition for checking that compares current API version. So, we can simply remove the if...else condition, and go with:

    NotificationCompat.Builder builder = new NotificationCompat.Builder(
                            this);
    notification = builder.setContentIntent(contentIntent)
                          .setSmallIcon(icon).setTicker(text).setWhen(time)
                          .setAutoCancel(true).setContentTitle(title)
                          .setContentText(text).build();
    mNM.notify(NOTIFICATION, notification);
    
    0 讨论(0)
提交回复
热议问题