通知是Android系统中比较有特色的一个功能,当某个应用程序需要向用户发送一条提示信息的时候,而该程序又不在前台运行,就可以借助通知来实现。发送通知后,状态栏会显示一个特制的图标,下拉状态栏可以看到通知的详细内容。
我们通过一个项目来看下通知是怎么使用的吧!
布局文件activity_main.xml代码
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/send_notice"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="发送通知"/>
</LinearLayout>
一个按钮,用于发送这条通知。
MainActivity.java代码
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button send;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
send = findViewById(R.id.send_notice);
send.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.send_notice:
//得到一个NotificationManager,用于管理通知
NotificationManager manager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//需添加的代码
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
String channelId = "default";
String channelName = "默认通知";
m