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了,接着就是調用吧。。。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章