Android平台提供了默认的通知栏实现,如下的代码就能实现:
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setContentTitle(getNotificationTitle())
.setContentText(getNotificationContent())
.setSmallIcon(iconDrawableId)
.setTicker(getNotificationContent())
.setAutoCancel(true)
.setContentIntent(pendingIntent);
manager.notify(notifyTitleId, builder.build());
这种方式虽然简单,但图标不能为网络图片,因此我们需要使用自定义的方式。
刚开始想先显示通知栏,之后异步下载并图片并更新图标,但却一直不能显示网络图片,如下:
ImageRequest request = new ImageRequest(getNotificationStatusIcon(),
new Response.Listener<Bitmap>(){
@Override
public void onResponse(Bitmap response) {
remoteView.setImageViewBitmap(iconId, response);
}
}, 0, 0, Bitmap.Config.RGB_565,
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
但图片获取成功了,显示无法成功。后来改变了顺序,先将图片下载了,之后再显示通知栏,居然显示正常了。
ImageRequest request = new ImageRequest(getNotificationStatusIcon(),
new Response.Listener<Bitmap>(){
@Override
public void onResponse(Bitmap response) {
pushCustomNotification(context, response);
}
}, 0, 0, Bitmap.Config.RGB_565,
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
pushDefaultNotification(context);
}
});
......
private void pushCustomNotification(Context context, Bitmap icon){
Intent intent;
try {
intent = Intent.parseUri(getIntent(), 0);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
final int notifyTitleId = ResourceUtil.getStringId(context,"push_mail_notification_title");
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
final int iconDrawableId = ResourceUtil.getDrawableId(context, "mail_push_icon");
final int iconId = ResourceUtil.getId(context, "push_notification_icon");
final RemoteViews view = new RemoteViews(context.getPackageName(), ResourceUtil.getLayoutId(context, "layout_custom_notification"));
view.setTextViewText(ResourceUtil.getId(context, "push_notification_title"), getNotificationTitle());
view.setTextViewText(ResourceUtil.getId(context, "push_notification_content"), getNotificationContent());
view.setImageViewBitmap(iconId, icon);
builder.setCustomContentView(view)
.setSmallIcon(iconDrawableId)
.setTicker(getNotificationContent())
.setAutoCancel(true)
.setContentIntent(pendingIntent);
manager.notify(notifyTitleId+1, builder.build());
} catch (URISyntaxException e) {
e.printStackTrace();
}
}