Notification is a feature in the Android system. Let's take a look at how Notification is used.
First, a NotificationManager is needed to manage notifications, which can be obtained through the getSystemService() method of Context. Here you need to pass in Context.NOTIFICATION_SERVICE to get NotificationManager. Next, you need to create a Notification object, which is used to store various information about the notification. The previous version of Andorid was constructed directly, that is, Notification notification = new Notification(); Now this is generally not done, and the Notification.Builder object is used to create the Notification.
First look at the usage of basic notification
public class NotificationActivity extends AppCompatActivity {
Button btn_notification;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
btn_notification = (Button) findViewById(R.id.btn_notification);
final NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(this);
builder.setContentTitle("我的通知")//设置标题
.setContentText("通知消息")//设置消息内容
.setContentIntent(getDefault(Notification.FLAG_AUTO_CANCEL))//这是必须的东西,用来设置点击事件
.setTicker("有新的消息来了")//设置通知来了时候的提示
.setOngoing(false)
.setWhen(System.currentTimeMillis())//设置通知的时间
.setPriority(Notification.PRIORITY_DEFAULT)
.setDefaults(Notification.DEFAULT_ALL)//设置条件
.setSmallIcon(R.drawable.zhenji);//设置通知的图标
final Notification mNotification = builder.build();
//创建notification
btn_notification.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
notificationManager.notify(1,mNotification);
}
});
}
public PendingIntent getDefault(int flag) {
PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, new Intent(), flag);
return pendingIntent;
}
}
The difference between Intent and pendingIntent
pendingIntent can be used to start an activity, start a service or send a broadcast. This is very similar to an Intent. A pendingIntent can be understood as a delayed-execution Intent. The way to get a PendingIntent is very simple, you can choose getActivity() or getService() or getBroadcast()
Summary: The basic usage of notification is very simple. If you want to add click events or carry parameters, you can do it in the third parameter Intent of PendingIntent.