在android开发中, Notification的应用十分的广泛,比如短信通知,软件更新,消息推送都需要用到 Notification来帮助实现,下面就分析一下android的 Notification构建流程:
首先,我们要先构建通知对象
private NotificationManager nManager;
nManager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);//获得系统服务 这个必须要有
//.构建通知对象
Notification ntf=new Notification.Builder(this)
//new NotificationCompat.Builder(this) //兼容(使用此方法创建也可以)
.setSmallIcon(R.drawable.ic_launcher)//必选
.setContentTitle("标题")
.setContentText("内容")
.setTicker("您有新消息了")//引爆消息(可选)
.setContentIntent(//设置点击以后要执行什么动作
PendingIntent.getActivity(this,100,new Intent(this,OtherActivity.class), PendingIntent.FLAG_UPDATE_CURRENT)).build();
ntf.flags=Notification.FLAG_AUTO_CANCEL;
//发送通知对象
nManager.notify(0, ntf);
这样一个简单的Notification就做好了
下面我们也可以制作一个自定义的通知
首先在布局文件中设置好自己想要的布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="64dp" >
<ImageView
android:id="@+id/logoId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher"
android:layout_centerVertical="true"
/>
<TextView
android:id="@+id/titleId"
android:layout_width="wrap_content"
android:layout_height="32dp"
android:layout_toEndOf="@id/logoId"
android:gravity="bottom"
android:text="TITLE"
/>
<TextView
android:id="@+id/contentId"
android:layout_width="wrap_content"
android:layout_height="32dp"
android:layout_toEndOf="@id/logoId"
android:layout_below="@id/titleId"
android:text="Content"
/>
<ImageView
android:id="@+id/closeId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentEnd="true"
android:src="@android:drawable/ic_menu_close_clear_cancel"
android:layout_marginRight="10dp"
/>
</RelativeLayout>
我这里的用了两个TextView和两个ImageView
接下来在代码中实现使用自己的布局,这里需要借助 RemoteViews对象来帮助我们完成。
</pre><pre name="code" class="java">//借助此对象封装通知栏自己定义的布局view对象
RemoteViews views=new RemoteViews(getPackageName(),R.layout.activity_nft_01)//这里是引用我们自己写的布局
//设置RemoteViews中要显示的内容及相关事件
views.setTextViewText(R.id.titleId, "歌曲名称");
views.setTextViewText(R.id.contentId, "歌手名");
//views.setImageViewResource(R.id.logoId, srcId);
//views.setImageViewBitmap(viewId, bitmap);
//views.setOnClickPendingIntent(R.id.closeId, pendingIntent);//设置点击事件监听
Notification ntf=new Notification.Builder(this).setSmallIcon(R.drawable.ic_launcher)//必选
//设置自己定义的内容view
.setContent(views)
.build();
设置完成之后再添加一段发送通知对象的代码
//.发送通知对象
nManager.notify(0, ntf);