Android自定义Notification通知
程序员文章站
2022-07-13 15:39:00
...
效果图:
Activity中的代码:
//通过点击事件触发自定义的通知
@Override
public void onClick(View v) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
Date curDate = new Date(System.currentTimeMillis());//获取当前时间
String str = formatter.format(curDate);
switch (v.getId()) {
case R.id.start:
Notification notification = new Notification(R.mipmap.ic_launcher,"title",System.currentTimeMillis());
// FLAG_AUTO_CANCEL 该通知能被状态栏的清除按钮给清除掉
// FLAG_NO_CLEAR 该通知不能被状态栏的清除按钮给清除掉
// FLAG_ONGOING_EVENT 通知放置在正在运行
notification.flags = Notification.FLAG_ONGOING_EVENT;// 点击通知之后自动消失
RemoteViews remoteView = new RemoteViews(this.getPackageName(), R.layout.layout_notification);
remoteView.setImageViewResource(R.id.image, R.mipmap.ic_launcher_round);
remoteView.setTextViewText(R.id.title, "标题:Notification "+str);
remoteView.setTextViewText(R.id.content, "前面我们说过,NotificationManager是所有Notification的大管家,它的主要职责是加入/移除Notification。");
// remoteView.setTextViewText(R.id.nowTime,str );
notification.contentView = remoteView;
// 3、为Notification的contentIntent字段定义一个Intent(注意,使用自定义View不需要setLatestEventInfo()方法)
//这儿点击后简答启动Settings模块
PendingIntent contentIntent = PendingIntent.getActivity(MainActivity.this, 0, new Intent("android.settings.SETTINGS"), 0);
notification.contentIntent = contentIntent;
// 发送一个标识为100的通知
notificationManager.notify(100,notification);
// 发送一个标识为zjh和100的通知
// notificationManager.notify("zjh",100,notification);
break;
case R.id.stop:
//清除掉所有标识为100的通知
notificationManager.cancel(100);
//清除掉所有的通知
// notificationManager.cancelAll();
//清除掉所有标识为zjh和100的通知
// notificationManager.cancel("zjh",100);
break;
default:
break;
}
}
layou_noticfication的布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@mipmap/ic_launcher_round" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginLeft="20dp"
>
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Title"
android:textSize="16sp"
android:textColor="@android:color/holo_red_light"
android:textStyle="bold"
/>
<TextView
android:id="@+id/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Content"
android:textColor="@android:color/holo_blue_light"
android:textSize="14sp"
android:singleLine="true"
android:ellipsize="end"
/>
</LinearLayout>
</LinearLayout>