Android设置Notification从网络中加载图片,解决点击无法消失的bug

Notification的构造函数中只支持使用资源文件的图片作为图片,但是如果我们想用网络中的图片怎么办呢。

我们知道,给Notification设置内容的时候调用的是setLatestEventInfo方法,当我们点击去看该方法的时候,所有的结果都一目了然了。

public void setLatestEventInfo(Context context,
            CharSequence contentTitle, CharSequence contentText, PendingIntent contentIntent) {
        // TODO: rewrite this to use Builder
        RemoteViews contentView = new RemoteViews(context.getPackageName(),
                R.layout.notification_template_base);
        if (this.icon != 0) {
            contentView.setImageViewResource(R.id.icon, this.icon);
        }
        if (priority < PRIORITY_LOW) {
            contentView.setInt(R.id.icon,
                    "setBackgroundResource", R.drawable.notification_template_icon_low_bg);
            contentView.setInt(R.id.status_bar_latest_event_content,
                    "setBackgroundResource", R.drawable.notification_bg_low);
        }
        if (contentTitle != null) {
            contentView.setTextViewText(R.id.title, contentTitle);
        }
        if (contentText != null) {
            contentView.setTextViewText(R.id.text, contentText);
        }
        if (this.when != 0) {
            contentView.setViewVisibility(R.id.time, View.VISIBLE);
            contentView.setLong(R.id.time, "setTime", when);
        }
        if (this.number != 0) {
            NumberFormat f = NumberFormat.getIntegerInstance();
            contentView.setTextViewText(R.id.info, f.format(this.number));
        }

        this.contentView = contentView;
        this.contentIntent = contentIntent;
    }


从上述代码中我们很明显能够看出来,Notification使用了一个RemoteViews的类来实现自己的布局,最后通过调用  

  this.contentView = contentView;
  this.contentIntent = contentIntent;
这两个方法来实现界面布局和Intent的,那么我们可不可以自己写一个remoteView呢,废话。。。

看RemoteViews中的

public void setImageViewBitmap(int viewId, Bitmap bitmap) {
        setBitmap(viewId, "setImageBitmap", bitmap);
    }
这不就是我们想要的吗。。。。

我们只有一个目的,把图片换成网络中加载的图片,我们先把图片从网络中加载到本地,看代码:

public void set(final Context context, String urlStr, final Bundle bundle) {
		new AsyncTask<String, Void, Bitmap>() {
			@Override
			protected Bitmap doInBackground(String... params) {
				try {
					URL url = new URL(params[0]);
					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();
					conn.setConnectTimeout(6000);// 设置超时
					conn.setDoInput(true);
					conn.setUseCaches(false);// 不缓存
					conn.connect();
					int code = conn.getResponseCode();
					Bitmap bitmap = null;
					if (code == 200) {
						InputStream is = conn.getInputStream();// 获得图片的数据流
						bitmap = BitmapFactory.decodeStream(is);
					}
					return bitmap;
				} catch (MalformedURLException e) {
					e.printStackTrace();
					return null;
				} catch (IOException e) {
					e.printStackTrace();
					return null;
				}
			}

			@Override
			protected void onPostExecute(Bitmap result) {
				super.onPostExecute(result);
				if (result != null) {
					openNitifNews(context, result, bundle);
				}
			}
		}.execute(urlStr);
	}

我们从网络中把图片加载到本地形成了bitmap,然后通过setImageViewBitmap把bitmap设置进去就oK了。

再来看看openNitifNews方法:

/**
	 * 处理推送的逻辑
	 * 
	 * @param ct
	 * @param imgUrl
	 * @param bundle
	 */
	private void openNitifNews(Context ct, Bitmap bitmap, Bundle bundle) {
		Context context = ct.getApplicationContext();
		NewsBean bean = null;
		bean = (NewsBean) bundle.getSerializable("bean");
		if(bean == null)
		return;
		if (TextUtils.isEmpty(bean.getTitle())) {
			return;
		}
		if (TextUtils.isEmpty(bean.getDes())) {
			bean.setDes("  ");
		}
			NotificationManager nm = null;
		if (null == nm) {
			nm = (NotificationManager) context
					.getSystemService(Context.NOTIFICATION_SERVICE);
		}
		
		Notification notification = new Notification();
		// 采用默认声音
		notification.defaults |= Notification.DEFAULT_SOUND;
		// 使用默认的灯光
		notification.defaults |= Notification.DEFAULT_LIGHTS;
		// 通知被点击后,自动消失
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		notification.icon = R.drawable.ic_launcher;
		// 点击'Clear'时,无法清除通知
		// notification.flags |= Notification.FLAG_NO_CLEAR;
		// 点击清除按钮不会清除消息通知,可以用来表示在正在运行
		// notification.flags |= Notification.FLAG_ONGOING_EVENT;
		RemoteViews remoteView = new RemoteViews(context.getPackageName(),
				R.layout.notif_news);  //通过自己的布局来显示
		remoteView.setImageViewBitmap(R.id.iv_newspush_icon, bitmap);
		remoteView.setTextViewText(R.id.tv_newpush_title, bean.getTitle());
		remoteView.setTextViewText(R.id.tv_newpush_des, bean.getDes());

		Intent appIntent = new Intent(ct, NewsDetailsActivity.class);
		appIntent.putExtra("article_type", bean.getTypeId());
		appIntent.putExtra("News_ID", bean.getID());
		appIntent.putExtra("HEADTITLE", bean.getHeadTitle());
		PendingIntent contentIntent = PendingIntent.getActivity(ct, 0, appIntent,
				PendingIntent.FLAG_UPDATE_CURRENT);<span style="white-space:pre">	</span>
<span style="white-space:pre">		</span>// remoteView.setOnClickPendingIntent(R.id.ll_newpush_root,
<span style="white-space:pre">		</span>// contentIntent);  //如果在这里设置点击事件,不会消失,根据需求来。。

		notification.contentView = remoteView; 
		notification.contentIntent = contentIntent; 

		nm.notify(MySmsReceiver.NEWSPUAH, notification);
	}

ok了,接着就是调用吧。。。


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。