1. 程式人生 > >[Android] Notification.setLatestEventInfo()方法被移除的問題

[Android] Notification.setLatestEventInfo()方法被移除的問題

前言

今天看《第一行程式碼》看到使用前臺服務章節,發現Notification.setLatestEventInfo()報錯,經過自己的摸索,發現此方法在 API23 中被移除,遂翻了一下API文件,發現可以用 Notification.Builder 來替代:

Notification.Builder 是什麼?

Builder class for Notification objects. Provides a convenient way to set the various fields of a Notification and generate content views using the platform’s notification layout template. If your app supports versions of Android as old as API level 4, you can instead use NotificationCompat.Builder, available in the Android Support library.

Notification 的 Builder 類,提供了一個便捷的方式來設定 Notification,並使用平臺的 notification 的 layout 模板生成 content views。如果您的 app 支援 Android API4 的老版本,你可以改用在Android的支援庫中可用的 NotificationCompat.Builder。

Example:

Notification noti = new Notification.Builder(mContext)
     .setContentTitle("New mail from " + sender.toString())
     .setContentText(subject)
     .setSmallIcon(R.drawable.new_mail)
     .setLargeIcon(aBitmap)
     .build();

然後呼叫 Notification.Builder 的

setContentTitle(CharSequence title);
setContentText(CharSequence text);
setSmallIcon(Icon icon);
setContentIntent(PendingIntent intent);

方法。

《第一行程式碼》中原始碼如下:

Notification notification = new Notification(
R.mipmap.iic_launcher,"Notification comes",System.currentTimeMillis());
Intent notificationIntent = new Intent(this,MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,notificationIntent,0);
notification.setLatestEventInfo(this,"This is title","This is content",pendingIntent);
startForeground(1,notification);

由於 Notification.setLatestEventInfo()方法的刪除導致以上程式碼不能使用,現有如下方法可以替代,使用 Notification.Builder:

Notification.Builder builder = new Notification.Builder(this);//新建Notification.Builder物件
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
builder.setContentTitle("This is title");//設定標題
builder.setContentText("This is content");//設定內容
builder.setSmallIcon(R.mipmap.ic_launcher);//設定圖片
builder.setContentIntent(pendingIntent);//執行intent
Notification notification = builder.getNotification();//將builder物件轉換為普通的notification
startForeground(1,notification);//讓 MyService 變成一個前臺服務,並在系統狀態列中顯示出來。

補充:

NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(1,notification);//執行notification

notification.flags |= Notification.FLAG_AUTO_CANCEL;//點選通知後通知消失