这是我的代码:
public static void generateNotification(Context context, String message) {
int icon = R.mipmap.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context, NotificationView.class);
notificationIntent.putExtra("msg", message);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent =
PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
}
如何使用API 23解决此代码中的setLatestEventInfo
方法?
答案 0 :(得分:0)
我遇到了同样的问题。以下是使这项工作和编译所需的代码。
public class AlertReceiver extends BroadcastReceiver{
// Called when a broadcast is made targeting this class
@Override
public void onReceive(Context context, Intent intent) {
createNotification(context, "Times Up", "5 Seconds Has Passed", "Alert");
}
public void createNotification(Context context, String msg, String msgText, String msgAlert){
// Define an Intent and an action to perform with it by another application
PendingIntent notificIntent = PendingIntent.getActivity(context, 0,
new Intent(context, MainActivity.class), 0);
// Builds a notification
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ntt_logo_24_24)
.setContentTitle(msg)
.setTicker(msgAlert)
.setContentText(msgText);
// Defines the Intent to fire when the notification is clicked
mBuilder.setContentIntent(notificIntent);
// Set the default notification option
// DEFAULT_SOUND : Make sound
// DEFAULT_VIBRATE : Vibrate
// DEFAULT_LIGHTS : Use the default light notification
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
// Auto cancels the notification when clicked on in the task bar
mBuilder.setAutoCancel(true);
// Gets a NotificationManager which is used to notify the user of the background event
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// Post the notification
mNotificationManager.notify(1, mBuilder.build());
}
在API 11中折旧了.setLatestEventInfo。希望这会有所帮助。