由于在Android 8.0之后,对通知进行过重大的调整和加入了一些新的功能,所以本篇文章将分别介绍,在Android 8.0中和在Android 8.0以下的版本中怎么使用通知,以及怎么在Android 8.0和Android 8.0以下的版本中兼容使用通知。
在Android 8.0以下的版本中使用通知,代码如下:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button mBtn_Send_Notice;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBtn_Send_Notice = findViewById(R.id.btn_send_notification);
mBtn_Send_Notice.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_send_notification:
// 调用getSystemService()方法得到一个NotificationManager的实例
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent intent = new Intent(MainActivity.this, DisplayActivity.class);
// 设置一个待定意图,因为我们是在活动中跳转,所以使用getActivity()方法得到实例,在广播中和服务中应使用getBroadcast()和getService来得到实例
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);