Android設定Notification從網路中載入圖片,解決點擊無法消失的bug

來源:互聯網
上載者:User

標籤:

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>() {@Overrideprotected 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;}}@Overrideprotected 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了,接著就是調用吧。。。


Android設定Notification從網路中載入圖片,解決點擊無法消失的bug

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.