本文源代码托管在https://github.com/ASCE1885/asce-common,欢迎fork

Android项目做得多了。会发现原来非常多基础的东西都是能够复用,这个系列介绍一些自己项目中经常使用到的公共模块代码(当然仅仅谈技术不谈业务),一来整理好了自己以后能够直接用,二来也分享给大家,希望能略微降低大家的加班时间,提高些许效率。

Android Notification的原理和作用这里就不作说明了,相信是个android开发人员都用过不止一次了,下面仅仅介绍怎样封装成公共的模块。以供整个项目使用。

基于不同的目的。Notification的外观区别非常大,相应到代码上就是布局的差异,因此。我们首先须要有一个接口供使用者来创建不同布局的Notification,接口在Java中当然是以Interface的形式存在。如代码清单IMyNotificationBuilder.java所看到的。

/**
* Notification接口
*
* @author asce1885
* @date 2014-06-09
*
*/
public interface IMyNotificationBuilder { public static final String NOTIFICATION_ID = IMyNotificationBuilder.class.getSimpleName(); Notification buildNotification(String title, String content); }

看到这里,熟悉设计模式的同学应该知道我们使用的是Builder模式来构建不同的Notification,依照惯例,一般会有一个默认的Builder实现,我们将之命名为BasicNotificationBuilder.java。它使用的是Android系统默认的通知栏布局。

/**
* 默认Notification构造器
*
* @author asce1885
* @date 2014-06-09
*
*/
public class BasicNotificationBuilder implements IMyNotificationBuilder { private Context mContext;
private PendingIntent mPendingIntent; public int mIconDrawableId; public BasicNotificationBuilder(Context context, PendingIntent pendingIntent) {
mContext = context;
mPendingIntent = pendingIntent;
mIconDrawableId = PackageUtils.getAppInfo(context).icon;
} public BasicNotificationBuilder(Context context, PendingIntent pendingIntent, int iconDrawableId) {
mContext = context;
mPendingIntent = pendingIntent;
mIconDrawableId = iconDrawableId;
} @SuppressWarnings("deprecation")
@Override
public Notification buildNotification(String title, String content) {
Notification basicNotification = new Notification(mIconDrawableId, title,
System.currentTimeMillis());
basicNotification.setLatestEventInfo(mContext, title, content, mPendingIntent);
basicNotification.flags |= Notification.FLAG_AUTO_CANCEL;
basicNotification.defaults = Notification.DEFAULT_SOUND;
basicNotification.contentIntent = mPendingIntent; return basicNotification;
} }

对于其它须要自己定义布局的通知栏形式。我们另外实现一个类。布局文件由使用者自己定义,见代码清单CustomNotificationBuilder.java。

/**
* 自己定义样式Notification构造器
*
* @author asce1885
* @date 2014-06-09
*
*/
public class CustomNotificationBuilder implements IMyNotificationBuilder { private Context mContext;
private int mCustomeLayout;
private int mLayoutSubjectId;
private int mLayoutMessageId;
private int mLayoutIconId;
private int mStatusBarIconDrawableId;
private Uri mSoundUri;
private PendingIntent mPendingIntent; public CustomNotificationBuilder(Context context, int customeLayout, int layoutSubjectId, int layoutMessageId, int layoutIconId, int statusBarIconDrawableId, Uri soundUri, PendingIntent pendingIntent) {
mContext = context;
mCustomeLayout = customeLayout;
mLayoutSubjectId = layoutSubjectId;
mLayoutMessageId = layoutMessageId;
mLayoutIconId = layoutIconId;
mStatusBarIconDrawableId = statusBarIconDrawableId;
mSoundUri = soundUri;
mPendingIntent = pendingIntent;
} @SuppressWarnings("deprecation")
@Override
public Notification buildNotification(String title, String content) {
if (TextUtils.isEmpty(content)) {
return null;
} PreFroyoNotificationStyleDiscover.getInstance().discoverStyle(mContext); Notification customerNotification = new Notification(mStatusBarIconDrawableId, title,
System.currentTimeMillis());
RemoteViews customerRemoteView = new RemoteViews(mContext.getPackageName(), mCustomeLayout);
customerRemoteView.setTextViewText(mLayoutSubjectId, PackageUtils.getAppName(mContext));
customerRemoteView.setTextViewText(mLayoutMessageId, content);
customerRemoteView.setImageViewResource(mLayoutIconId, mStatusBarIconDrawableId);
customerNotification.flags |= Notification.FLAG_AUTO_CANCEL; if (mSoundUri != null) {
customerNotification.sound = mSoundUri;
} else {
customerNotification.defaults = Notification.DEFAULT_SOUND;
}
customerNotification.contentIntent = mPendingIntent; // Some SAMSUNG devices status bar cant't show two lines with the size,
// so need to verify it, maybe increase the height or decrease the font size customerRemoteView.setFloat(mLayoutSubjectId, "setTextSize",
PreFroyoNotificationStyleDiscover.getInstance().getTitleSize());
customerRemoteView.setTextColor(mLayoutSubjectId, PreFroyoNotificationStyleDiscover
.getInstance().getTitleColor()); customerRemoteView.setFloat(mLayoutMessageId, "setTextSize",
PreFroyoNotificationStyleDiscover.getInstance().getTextSize());
customerRemoteView.setTextColor(mLayoutMessageId, PreFroyoNotificationStyleDiscover
.getInstance().getTextColor()); customerNotification.contentView = customerRemoteView; return customerNotification;
} /**
* A class for discovering Android Notification styles on Pre-Froyo (2.3) devices
*/
private static class PreFroyoNotificationStyleDiscover { private Integer mNotifyTextColor = null;
private float mNotifyTextSize = 11;
private Integer mNotifyTitleColor = null;
private float mNotifyTitleSize = 12;
private final String TEXT_SEARCH_TEXT = "SearchForText";
private final String TEXT_SEARCH_TITLE = "SearchForTitle"; private static Context mContext; private static class LazyHolder {
private static final PreFroyoNotificationStyleDiscover sInstance = new PreFroyoNotificationStyleDiscover();
} public static PreFroyoNotificationStyleDiscover getInstance() {
return LazyHolder.sInstance;
} private PreFroyoNotificationStyleDiscover() { } public int getTextColor() {
return mNotifyTextColor.intValue();
} public float getTextSize() {
return mNotifyTextSize;
} public int getTitleColor() {
return mNotifyTitleColor;
} public float getTitleSize() {
return mNotifyTitleSize;
} private void discoverStyle(Context context) {
mContext = context;
// Already done
if (null != mNotifyTextColor) {
return;
} try {
Notification notify = new Notification();
notify.setLatestEventInfo(mContext, TEXT_SEARCH_TITLE, TEXT_SEARCH_TEXT, null);
LinearLayout group = new LinearLayout(mContext);
ViewGroup event = (ViewGroup) notify.contentView.apply(mContext, group);
recurseGroup(event);
group.removeAllViews();
} catch (Exception e) {
// Default to something
mNotifyTextColor = android.R.color.black;
mNotifyTitleColor = android.R.color.black;
}
} private boolean recurseGroup(ViewGroup group) {
final int count = group.getChildCount(); for (int i = 0; i < count; ++i) {
if (group.getChildAt(i) instanceof TextView) {
final TextView tv = (TextView) group.getChildAt(i);
final String text = tv.getText().toString();
if (text.startsWith("SearchFor")) {
DisplayMetrics metrics = new DisplayMetrics();
WindowManager wm = (WindowManager) mContext
.getSystemService(Context.WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(metrics); if (TEXT_SEARCH_TEXT == text) {
mNotifyTextColor = tv.getTextColors().getDefaultColor();
mNotifyTextSize = tv.getTextSize();
mNotifyTextSize /= metrics.scaledDensity;
} else {
mNotifyTitleColor = tv.getTextColors().getDefaultColor();
mNotifyTitleSize = tv.getTextSize();
mNotifyTitleSize /= metrics.scaledDensity;
} if (null != mNotifyTitleColor && mNotifyTextColor != null) {
return true;
}
}
} else if (group.getChildAt(i) instanceof ViewGroup) {
if (recurseGroup((ViewGroup) group.getChildAt(i))) {
return true;
}
}
}
return false;
}
} }

Notification的构建代码至此结束。而要发出Notification,使用的是NotificationManager,我们将它封装成代码清单MyNotificationManager.java。

/**
* Notification管理器
*
* @author asce1885
* @date 2014-06-09
*
*/
public class MyNotificationManager { private IMyNotificationBuilder mMyNotificationBuilder; private static final int START_ID = 1000;
private static final int RANGE = 50;
private int mCurrentId = START_ID; private MyNotificationManager() { } private static class LazyHolder {
private static final MyNotificationManager sInstance = new MyNotificationManager();
} public static MyNotificationManager getInstance() {
return LazyHolder.sInstance;
} public IMyNotificationBuilder getMyNotificationBuilder() {
return mMyNotificationBuilder;
} public void setMyNotificationBuilder(IMyNotificationBuilder builder) {
mMyNotificationBuilder = builder;
} public void deliverNotification(Context context, String title, String content) {
buildAndDisplayNotification(context, title, content);
} private void buildAndDisplayNotification(Context context, String title, String content) {
if (null != mMyNotificationBuilder) {
Notification notification = mMyNotificationBuilder.buildNotification(title, content);
if (null != notification) {
notification.flags |= Notification.FLAG_AUTO_CANCEL;
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(generateNotification(), notification);
}
}
} private int generateNotification() {
mCurrentId++;
if (mCurrentId >= START_ID + RANGE) {
mCurrentId = START_ID;
}
return mCurrentId;
}
}

最后给下使用的演示样例代码例如以下所看到的,仅仅作为參考。里面的部分变量不用深究。

				Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra(BundleConstant.KEY_NOTIFICATION_TYPE, action);
intent.putExtra(BundleConstant.KEY_WEBVIEW_TITLE, notice.webview_title);
intent.putExtra(BundleConstant.KEY_WEBVIEW_URL, notice.webview_url);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), (int) notice.nid, intent, PendingIntent.FLAG_UPDATE_CURRENT); builder = new BasicNotificationBuilder(getApplicationContext(), pendingIntent);
MyNotificationManager.getInstance().setMyNotificationBuilder(builder);
MyNotificationManager.getInstance().deliverNotification(getApplicationContext(), notice.notification_title, notice.notification_content);

——欢迎转载。请注明出处 http://blog.csdn.net/asce1885 ,未经本人允许请勿用于商业用途。谢谢——

【直接拿来用のandroid公共代码模块解析与分享】の Notification和NotificationManager的更多相关文章

  1. Android实用代码模块集锦

    1. 精确获取屏幕尺寸(例如:3.5.4.0.5.0寸屏幕) 1 2 3 4 5 6 public static double getScreenPhysicalSize(Activity ctx)  ...

  2. 系统管理模块_部门管理_改进_抽取添加与修改JSP页面中的公共代码_在显示层抽取BaseAction_合并Service层与Dao层

    系统管理模块_部门管理_改进1:抽取添加与修改JSP页面中的公共代码 commons.jspf <%@ page language="java" import="j ...

  3. android开源代码

    Android开源项目--分类汇总 转自:https://github.com/Trinea/android-open-project Android开源项目第一篇——个性化控件(View)篇 包括L ...

  4. 160多个android开源代码汇总

    第一部分 个性化控件(View) 主要介绍那些不错个性化的View,包括ListView.ActionBar.Menu.ViewPager.Gallery.GridView.ImageView.Pro ...

  5. Android 开源项目android-open-project工具库解析之(一) 依赖注入,图片缓存,网络相关,数据库orm工具包,Android公共库

    一.依赖注入DI 通过依赖注入降低View.服务.资源简化初始化.事件绑定等反复繁琐工作 AndroidAnnotations(Code Diet) android高速开发框架 项目地址:https: ...

  6. (通用)Android App代码混淆终极解决方案【转】

    App虽然没有那么的高大上,但是代码的混淆是代表了程序员对App的责任心, 也是对App安全的一点点保证.今天我会将自己做Android混淆的过程和体会分享给大家,也避免大家少走弯路,少跳坑. 本篇博 ...

  7. 系统中异常公共处理模块 in spring boot

    最近在用spring boot 做微服务,所以对于异常信息的 [友好展示]有要求,我设计了两点: 一. 在业务逻辑代码中,异常的抛出 我做了限定,一般只会是三种: 1. OmcException // ...

  8. Android开发代码规范(转)

    Android开发代码规范 1.命名基本原则    在面向对象编程中,对于类,对象,方法,变量等方面的命名是非常有技巧的.比如,大小写的区分,使用不同字母开头等等.但究其本,追其源,在为一个资源其名称 ...

  9. 黑客破译android开发代码真就那么简单?

    很多程序员辛辛苦苦开发出的android开发代码,很容易就被黑客翻译了. Google似乎也发现了这个问题,从SDK2.3开始我们可以看到在android-sdk-windows\tools\下面多了 ...

随机推荐

  1. 关联Anaconda和最新Pycharm2018.3.2

    在Anaconda和Pycharm 2018.3.2 x64都安装好之后,进行Anaconda 与Pycharm的关联操作 首先File -->New Project 打开以后切记要把Proje ...

  2. 紫书 习题 10-1UVa 111040(找规律)

    通过观察可以得 图可以分成很多个上面一个,中间两个,下面三个的"模板" 这个时候最上面一个知道,最下面得左右知道 那么可以设下面中间为x,左边为a1, 右边为a2, a1a2已知 ...

  3. 洛谷—— P1036 选数 || Vijos——选数

    https://vijos.org/p/1128|| https://www.luogu.org/problem/show?pid=1036#sub 描述 已知 n 个整数 x1,x2,…,xn,以及 ...

  4. 一 梳理 从 HDFS 到 MR。

      MapReduce 不仅仅是一个工具,更是一个框架.我们必须拿问题解决方案去适配框架的 map 和 reduce 过程   很多情况下,需要关注 MapReduce 作业所需要的系统资源,尤其是集 ...

  5. [问题]HDOJ1032 The 3n + 1 problem

    http://acm.hdu.edu.cn/showproblem.php? pid=1032 这题能够用暴力求解.求出在[ni,nj]之间全部数字产生的最大值. 通过观察能够知道,当nk靠近nj的时 ...

  6. linux添加开机启动项的方法介绍

    使用chkconfig命令可以查看在不同启动级别下课自动启动的服务(或是程序),命令格式如下:chkconfig --list可能输出如下:openvpn 0:关闭 1:开启 ...... 6:关闭 ...

  7. Entity Framework介绍和DBFirst开发方式

    一.ORM概念  什么是ORM? 对象关系映射(英语:(Object Relational Mapping,简称ORM,或O/RM,或O/R mapping),是一种程序技术.简单来说,就是将关系型数 ...

  8. 113.dynamic_cast 虚函数 通过子类初始化的父类转化为子类类型

    #include <iostream> using namespace std; //子类同名函数覆盖父类 //父类指针存储子类地址,在有虚函数情况会调用子类方法,否则会调用父类方法 cl ...

  9. Sqoop1与Sqoop2的比较

    1.sqoop1和sqoop2是两个不同的版本,它们是完全不兼容的. 2.版本划分方式:Apache 1.4.x 之后的版本属于sqoop1,1.99.x之上的版本属于sqoop2. 3.与sqoop ...

  10. Android自定义组件系列【14】——Android5.0按钮波纹效果实现

    今天任老师发表了一篇关于Android5.0中按钮按下的波纹效果实现<Android L中水波纹点击效果的实现>,出于好奇我下载了源代码看了一下效果,正好手边有一个Nexus手机,我结合实 ...